$(document).ready(function(){
	// Animation variables
	var galleryImageSlideAcrossEase = 'easeInBack';
	var galleryImageSlideAcrossSpeed = 400;

	$('.expandable .section .article').hide();
	$('.expandable .section').addClass('closed');
	
	$('.expandable .section .read-more').click(function() {
		if($(this).parents('.section:first').hasClass('closed')) {
			$(this).html('Read Less').removeClass('read-more').addClass('read-less');
			$(this).removeClass('closed').addClass('open');
			$(this).parents('.section:first').find('.article').slideDown();
			$(this).parents('.section:first').removeClass('closed');
			$(this).parents('.section:first').addClass('open');
		}
		else {
			$(this).html('Read More').removeClass('read-less').addClass('read-more');
			$(this).removeClass('open').addClass('closed');
			$(this).parents('.section:first').find('.article').slideUp();
			$(this).parents('.section:first').removeClass('open');
			$(this).parents('.section:first').addClass('closed');
		}
		return false;
	});
	
	//
	//
	//	Social Media Bar
	//
	//
	
	$('#social-media-bar ul.links li a').click(function(event) {
		var popup = $(this).parent().find('.popup');
		if (popup.hasClass('active')) {
			popup.removeClass('active');
			popup.parent().removeClass('active');
		}
		else {
			$('#social-media-bar ul.links li .popup').removeClass('active');
			popup.addClass('active');
			popup.parent().addClass('active');
		}
		if (popup.length > 0) {
			event.preventDefault();
		}
	});
	
	$('#social-media-bar ul.links li > a').hover(
		function() {
			var className = $(this).parents('li:first').attr('class').split(" ")[0]; // Gets the first class (e.g. blog, twitter, flickr)
			var popup = $(this).parent().find('.popup');
			$('#social-media-bar ul.links li .popup').removeClass('active'); // Remove 'active' from any already open popups
			popup.addClass('active');
			$(this).parent().addClass(className+'-active');
		}, function() {
			var className = $(this).parents('li:first').attr('class').split(" ")[0];
			var popup = $(this).parent().find('.popup');
			$(this).parent().removeClass().addClass(className); // Adds the classname-active rather than just active to get it to work in IE6
			popup.removeClass('active');
		}
	);
  
	$('#social-media-bar ul.links li .popup').hover(
		function() {
			var popup = $(this);
			$('#social-media-bar ul.links li .popup').removeClass('active');
			popup.addClass('active');
			popup.parent().addClass('active');
		}, function() {
			var popup = $(this);
			popup.removeClass('active');
			popup.parent().removeClass('active');
		}
	);
	
	
	$('#social-media-bar ul.links li .popup .inner .flickr-thumbs li a, #social-media-bar ul.links li .popup .inner .flickr-thumbs li a img').hover(
		function() {
			var popup = $(this).parents('.popup:first');
			$('#social-media-bar ul.links li .popup').removeClass('active');
			popup.addClass('active');
			popup.parent().addClass('active');
		}, function() {
			//var popup = $(this).parents('.popup:first');
			//popup.removeClass('active');
			//popup.parent().removeClass('active');
		}
	);
	
	$('#social-media-bar p.expand-collapse a').click(function() {
		if($(this).hasClass('collapse')) {
			$('#social-media-bar .content ul.links').fadeOut(function() {
				$('#social-media-bar>div').animate({'width':'30px'});
			});
			$(this).removeClass('collapse').addClass('expand');
		}
		else if($(this).hasClass('expand')) {
			$('#social-media-bar>div').animate({'width':'100%'}, function() {
				$('#social-media-bar ul.links').fadeIn();
			});
			$(this).removeClass('expand').addClass('collapse');
		}
		return false;
	});
	
	if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
		$('#social-media-bar').css('position', 'relative');
	}
	
	//
	//
	//	Overlays
	//
	//
	
	$('.experience-gallery ul.experience-thumbs li, .brand-machine .clients .client-list li').hover(function() {
		if($(this).find('.details').length == 0) {
			$(this).append('<div class="details-transparency"></div>');
			$(this).append('<div class="details"><p>'+$(this).find('img').attr('alt')+'</p><a href="'+$(this).find('a').attr('href')+'">See case study</a></div>');
			$(this).find('a').click(function() {
				displayGalleryItem($(this));
				return false;
			});
		}
		$(this).find('.details-transparency').stop();
		$(this).find('.details').stop();
		$(this).find('.details-transparency').fadeTo(500, 0.8);
		$(this).find('.details').fadeTo(500, 1);
	}, function() {
		$(this).find('.details-transparency').stop();
		$(this).find('.details').stop();
		$(this).find('.details-transparency').fadeOut(500);
		$(this).find('.details').fadeOut(500);
	});
	
	//
	//
	//	Experience Gallery
	//
	//
	
	var galleryItemWidth = $('.experience-gallery .overlay').width();
	var galleryItemIndex = 0;
	var numberOfGalleryItems = $('.experience-gallery ul.experience-thumbs li a:first-child').length;
	var galleryItemsPerView = 16;
	var galleryViewWidth = $('.experience-gallery ul.experience-thumbs').outerWidth(true);
	var numberOfGalleryViews =  $('.experience-gallery ul.experience-thumbs').length;
	var currentGalleryViewIndex = 0;
	$('.experience-gallery .overlay .case-study-container ul').width(galleryItemWidth*numberOfGalleryItems);
	setupGalleryPrevNextButtons();
	setupGalleryItemThumbs();
	
	$('.experience-gallery ul.experience-thumbs li a').click(function() {
		displayGalleryItem($(this));
		return false;
	});
	
	
	
	$('.experience-gallery .overlay .close-overlay').click(function() {
		$('.experience-gallery .overlay').fadeOut().removeClass('show');
		$('.experience-gallery ul.experience-thumbs li').fadeTo('slow', 1);
		setupGalleryPrevNextButtons();
		return false;
	});
	
	$('.experience-gallery .prev').click(function() {
		if(galleryIsDisplaying()) {
			galleryItemIndex--;
			setActiveGalleryItem(galleryItemIndex);
		}
		else {
			currentGalleryViewIndex--;
			setActiveGalleryView(currentGalleryViewIndex);
		}
		
		return false;
	});
	
	$('.experience-gallery .next').click(function() {
		if(galleryIsDisplaying()) {
			galleryItemIndex++;
			setActiveGalleryItem(galleryItemIndex);
		}
		else {
			currentGalleryViewIndex++;
			setActiveGalleryView(currentGalleryViewIndex);
		}
		
		return false;
	});
	
	function displayGalleryItem(item) {
		currentThumb = item.parents('li');
		galleryItemIndex = $('.experience-gallery ul.experience-thumbs li').index(currentThumb);
		setActiveGalleryItem(galleryItemIndex);
	}
	
	function setActiveGalleryItem(index) {
		$('.experience-gallery ul.experience-thumbs li').removeClass('active');
		if(galleryIsDisplaying()) {
			$('.experience-gallery ul.experience-thumbs li:eq('+index+')').addClass('active').css('opacity', '1');
			$('.experience-gallery ul.experience-thumbs li').not('.active').css('opacity', '0.1');
			switchGalleryItem(galleryItemIndex);
			setupGalleryPrevNextButtons();
		}
		else {
			$('.experience-gallery ul.experience-thumbs li:eq('+index+')').addClass('active').fadeTo('slow', 1);
			$('.experience-gallery ul.experience-thumbs li').not('.active').fadeTo('slow', 0.1);
			$('.experience-gallery .overlay').fadeIn('fast');
			switchGalleryItem(galleryItemIndex);
			
			$('.experience-gallery .overlay').addClass('show');
			setupGalleryPrevNextButtons();
		}
		
		
		setActiveGalleryView(Math.floor(index/galleryItemsPerView));
	}
	
	function switchGalleryItem(index) {
		$('.experience-gallery .overlay .case-study-container ul').animate({
			left: (index*galleryItemWidth*-1+'px')
		}, galleryImageSlideAcrossSpeed, galleryImageSlideAcrossEase);
	}
	
	function setActiveGalleryView(index) {
		$('.experience-gallery .experience-thumbs-container').animate({
			left: (index*galleryViewWidth*-1+'px')
		}, 100);
		currentGalleryViewIndex = index;
		setupGalleryPrevNextButtons();
	}
	
	function setupGalleryPrevNextButtons() {
		if(numberOfGalleryItems <= galleryItemsPerView && !galleryIsDisplaying()) {
			$('.experience-gallery .prev').hide();
			$('.experience-gallery .next').hide();
		}
		else if(galleryItemIndex == 0 && galleryIsDisplaying()) {
			$('.experience-gallery .prev').hide();
			$('.experience-gallery .next').show();
		}
		else if((galleryItemIndex == numberOfGalleryItems - 1) && galleryIsDisplaying()) {
			$('.experience-gallery .prev').show();
			$('.experience-gallery .next').hide();
		}
		else if(galleryIsDisplaying()){
			$('.experience-gallery .prev').show();
			$('.experience-gallery .next').show();
		}
		else if(currentGalleryViewIndex == 0 && !galleryIsDisplaying()) {
			$('.experience-gallery .prev').hide();
			$('.experience-gallery .next').show();
		}
		else if((currentGalleryViewIndex == numberOfGalleryViews - 1) && !galleryIsDisplaying()) {
			$('.experience-gallery .prev').show();
			$('.experience-gallery .next').hide();
		}
		else if(!galleryIsDisplaying()) {
			$('.experience-gallery .prev').show();
			$('.experience-gallery .next').show();
		}
	}
	
	function setupGalleryItemThumbs() {
		$('.experience-gallery').css('overflow', 'hidden');
		$('.experience-gallery .experience-thumbs-container').width(Math.ceil(numberOfGalleryItems/galleryItemsPerView) * galleryViewWidth + 5); // Additional 5 added to fix IE6 issue where the width still wasn't long enough.
	}
	
	function galleryIsDisplaying() {
		return $('.experience-gallery .overlay').hasClass('show');
	}
	
	
	//
	//
	//	Feature A
	//
	//
	
	var featureItemIndex = 0;
	var featureAnimationSpeed = 'fast';
	var switchSpeed = 15000;
	var featureCount = $('#a-feature .content ul li').size();
	var animate = true;
	var timer = null;
	startTimer();
	$('#a-feature .content ul li').hide();
	$('#a-feature .content ul li:first').fadeIn('slow').addClass('current');
	
	$('#a-feature .selection ul li a').click(function() {
		animate = false;
		currentFeatureItem = $(this).parents('li');
		featureItemIndex = $('#a-feature .selection ul li').index(currentFeatureItem);
		switchFeatureItem(featureItemIndex);
		return false;
	});
	
	$('#a-feature .content ul li').hover(
		function() {
			clearTimeout(timer);
		},
		function() {
			animate = true;
			startTimer();
		});
	
	function startTimer() {
		if(timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(function() {
			if(animate) {
				featureItemIndex++;
				if(featureItemIndex == featureCount) {
					featureItemIndex = 0;
				}
				switchFeatureItem(featureItemIndex);
			}
		}, switchSpeed);
	}
	
	function switchFeatureItem(index) {
		$('#a-feature .selection ul li a.current').removeClass('current');
		$('#a-feature .selection ul li a:eq('+index+')').addClass('current');
		$('#a-feature .content ul li.current').removeClass('current').fadeOut(featureAnimationSpeed, function() {
			$('#a-feature .content ul li:eq('+index+')').addClass('current').fadeIn(featureAnimationSpeed);
			startTimer();
		});
	}
	


	//
	//
	//	BG containers
	//
	//
	
	var featureItemIndex = 0;
	var featureAnimationSpeed = 'fast';
	var switchSpeed = 15000;
	var featureCount = $('#bg_containers .content ul li').size();
	var animate = true;
	var timer = null;
	startTimer();
	$('#bg_containers .content ul li').hide();
	$('#bg_containers .content ul li:first').fadeIn('slow').addClass('current');
	
	/*$('#bg_containers .selection ul li a').click(function() {
		animate = false;
		currentFeatureItem = $(this).parents('li');
		featureItemIndex = $('#bg_containers .selection ul li').index(currentFeatureItem);
		switchFeatureItem(featureItemIndex);
		return false;
	});*/
	
	$('#bg_containers .content ul li').hover(
		function() {
			clearTimeout(timer);
		},
		function() {
			animate = true;
			startTimer();
		});
	
	function startTimer() {
		if(timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(function() {
			if(animate) {
				featureItemIndex++;
				if(featureItemIndex == featureCount) {
					featureItemIndex = 0;
				}
				switchFeatureItem(featureItemIndex);
			}
		}, switchSpeed);
	}
	
	function switchFeatureItem(index) {
		$('#bg_containers .selection ul li a.current').removeClass('current');
		$('#bg_containers .selection ul li a:eq('+index+')').addClass('current');
		$('#bg_containers .content ul li.current').removeClass('current').fadeOut(featureAnimationSpeed, function() {
			$('#bg_containers .content ul li:eq('+index+')').addClass('current').fadeIn(featureAnimationSpeed);
			startTimer();
		});
	}


	//
	//
	//	Brands
	//
	//
	
	var numberOfBrandItems = $('.brand-machine ul.client-list li').length;
	var brandItemsPerView = 15;
	var brandViewWidth = $('.brand-machine ul.client-list').outerWidth(true);
	var brandViewHeight = $('.brand-machine ul.client-list').outerHeight(true);
	var brandItemWidth = $('.brand-machine ul.client-list li').outerWidth(true);
	var brandItemHeight = $('.brand-machine ul.client-list li').outerHeight(true);
	var brandItemsX = brandViewWidth / brandItemWidth; // How many items will fit horizontally
	var brandItemsY = brandViewHeight / brandItemHeight; // How many items will fit horizontally
	var numberOfBrandViews =  Math.ceil($('.brand-machine ul.client-list li').length / brandItemsPerView);
	var currentBrandViewIndex = 0;
	var brandFadeSpeed = 250;
	var brandAnimationSpeed = 400;
	var startingBrandPositions = new Array();
	var newBrandPositions = new Array();
	var brandsHaveMoved = false;
	$('.brand-machine .clients .client-list li').addClass('category-match'); // Sets all to matching category for now (as it defaults to all)
	
	setupBrandPrevNextButtons();
	setupBrandItemThumbs();
	getStartingBrandPositions($('.brand-machine .clients .client-list li'));
	setBrandPositions($('.brand-machine .clients .client-list'), startingBrandPositions);
	
	
	$('.brand-machine .categories li a').click(function() {
		var categoryToSwitchTo = $(this).attr('rel');
		filterBrandsByCategory(categoryToSwitchTo);
		$('.brand-machine .categories li').removeClass('active');
		$(this).parents('li:first').addClass('active');
		return false;
	});
	
	$('.brand-machine .prev').click(function() {
			currentBrandViewIndex--;
			setActiveBrandView(currentBrandViewIndex);
		
		return false;
	});
	
	$('.brand-machine .next').click(function() {
			currentBrandViewIndex++;
			setActiveBrandView(currentBrandViewIndex);
		
		return false;
	});
	
	function filterBrandsByCategory(category) {
		$('.brand-machine .clients .client-list li').stop(true, true); // Stop all animations which were running.
		if(brandsHaveMoved) {
			resetMovedBrandPositions();
		}
		
		
		
		var numberOfMovedBrands = 0;
		
		// If category is all, we don't want the elements currently there to fade out as they'll just fade back in.
		if(category!='all') {
			// First we remove any old classes added to define matches from the last category, then we hide all items. We do not do this to elements which also have the new category (we don't want them to fade out).
			$('.brand-machine .clients .client-list li.category-match:not(.'+category+')').removeClass('category-match').fadeOut(brandFadeSpeed, function() {
				
			});
		}
		animateBrandPositions(category, numberOfMovedBrands);
		
	}
	
	function animateBrandPositions(category, numberOfMovedBrands) {
		
		$('.brand-machine .clients .client-list li').each(function(index) {
			if($(this).hasClass(category) || category=='all') {
				$(this).addClass('category-match');
				numberOfMovedBrands++;
				////console.log(numberOfMovedBrands);
			}
		});
		getNewBrandPositions($('.brand-machine .clients .client-list li.category-match'));
	}
	
	function getNewBrandPositions(listItems) {
		numberOfBrandsToShow = listItems.length;
		//console.log('numberOfBrandsToShow was set to '+ numberOfBrandsToShow);
		numberOfBrandViews = Math.ceil(numberOfBrandsToShow / brandItemsPerView);
		//console.log('numberOfBrandViews was set to '+ numberOfBrandViews);
		
		rows = Math.ceil(brandItemsPerView / brandItemsX);
		////console.log('Row count is '+rows);
		
		currentIndex = 0;
		for(i=0;i<numberOfBrandViews;i++) {
			for(r = 0; (r < rows) && (currentIndex < brandItemsPerView*(i+1)); r++) {
			////console.log('CurrentIndex('+currentIndex+') < '+brandItemsPerView*(i+1));
				for(c=0; c < brandItemsX && currentIndex < numberOfBrandsToShow; c++) {
					////console.log('('+brandItemWidth+' * ' + c + ') + ('+ brandViewWidth + ' * ' + i + ')');
					newBrandPositions[currentIndex] = {'top': ((brandItemHeight * r)), 'left': ((brandItemWidth * c) + (brandViewWidth*i))};
					////console.log('Top of '+currentIndex+': '+(newBrandPositions[currentIndex].top)+' Left: '+(newBrandPositions[currentIndex].left));
					currentIndex++;
				}
			}
		}
		
		//resetMovedBrandPositions();
		listItems.css({'opacity':'1'});
		listItems.fadeIn(brandFadeSpeed);
		setBrandPositions(listItems.parents('ul:first'), newBrandPositions);
		//newBrandPositions = new Array();
		brandsHaveMoved = true;
	}
	
	function getStartingBrandPositions(listItems) {	
		numberOfBrandsToShow = listItems.length;
		numberOfBrandViews = Math.ceil(numberOfBrandsToShow / brandItemsPerView);
		rows = Math.ceil(brandItemsPerView / brandItemsX);
		////console.log('Row count is '+rows);
		
		currentIndex = 0;
		for(i=0;i<numberOfBrandViews;i++) {
			for(r = 0; (r < rows) && (currentIndex < brandItemsPerView*(i+1)); r++) {
			////console.log('CurrentIndex('+currentIndex+') < '+brandItemsPerView*(i+1));
				for(c=0; c < brandItemsX && currentIndex < numberOfBrandsToShow; c++) {
					////console.log('('+brandItemWidth+' * ' + c + ') + ('+ brandViewWidth + ' * ' + i + ')');
					startingBrandPositions[currentIndex] = {'top': ((brandItemHeight * r)), 'left': ((brandItemWidth * c) + (brandViewWidth*i))};
					////console.log('Top of '+currentIndex+': '+(startingBrandPositions[currentIndex].top)+' Left: '+(startingBrandPositions[currentIndex].left));
					currentIndex++;
				}
			}
		}
	}
	
	function setBrandPositions(list, positions) {
		
		list.find('li.category-match').each(function(index) {
			$(this).css({'position': 'absolute'});
			$(this).animate({'top': positions[index].top, 'left': positions[index].left}, brandAnimationSpeed);
		});
		setActiveBrandView(0); // Move main view back to start
	}
	
	function resetMovedBrandPositions() {
		$('.brand-machine .clients .client-list li').each(function(index) {
			if($(this).hasClass('category-match')) {
				$(this).css({'position':'absolute'});
				$(this).animate({'top': startingBrandPositions[index].top, 'left': startingBrandPositions[index].left, 'opacity': 1}, brandAnimationSpeed);
			}
		});
	}
	
	function setActiveBrandView(index) {
		$('.brand-machine .clients-container').animate({
			left: (index*brandViewWidth*-1+'px')
		}, 100);
		currentBrandViewIndex = index;
		setupBrandPrevNextButtons();
		//console.log('Buttons setup');
	}
	
	function setupBrandPrevNextButtons() {
		if(currentBrandViewIndex == 0) {
			$('.brand-machine .prev').hide();
			if(numberOfBrandViews == 1) {
				$('.brand-machine .next').hide();
			}
			else {
				$('.brand-machine .next').show();
			}
		}
		else if(currentBrandViewIndex == numberOfBrandViews - 1) {
			$('.brand-machine .prev').show();
			$('.brand-machine .next').hide();
		}
		else {
			$('.brand-machine .prev').show();
			$('.brand-machine .next').show();
		}
	}
	
	function setupBrandItemThumbs() {
		$('.brand-machine').css('overflow', 'hidden');
		$('.brand-machine .clients-container').width(Math.ceil(numberOfBrandItems/brandItemsPerView) * brandViewWidth);
	}
	
	
	//
	//
	//	Case Study Slideshow
	//
	//
	
	currentActiveImageGalleryView = 0;
	imageGalleryThumbnailAnimationSpeed = 200;
	imageGalleryThumbnailAnimationTypeIn = 'easeInSine';
	imageGalleryThumbnailAnimationTypeOut = 'easeOutSine';
	imageGalleryThumbnailWidth = $('.image-gallery .thumbnail-tray .thumbnails').outerWidth(true);
	imageGalleryThumbnailTrayHeight = $('.image-gallery .thumbnail-tray').height();
	imageGalleryBigPictureWidth = $('.image-gallery .big-picture-container ul .big-picture').outerWidth(true);
	numberOfImageGalleryBigPictures = $('.image-gallery .big-picture-container ul .big-picture').length;
	$('.image-gallery .big-picture-container').width(imageGalleryBigPictureWidth*numberOfImageGalleryBigPictures);
	$('.image-gallery .thumbnail-tray .thumbnails').css({'left':10});
	
	$('.image-gallery .thumbnail-tray .expand-collapse a').click(function() {
		if($(this).hasClass('collapse')) {
			
			$('.image-gallery .thumbnail-tray .thumbnails').animate({'left':-imageGalleryThumbnailWidth + 10, 'opacity': 50}, imageGalleryThumbnailAnimationSpeed, function() {
				$('.image-gallery .thumbnail-tray').animate({'height':'20px'}, imageGalleryThumbnailAnimationTypeIn);
			});
			$('.image-gallery .thumbnail-tray .expand-collapse a').removeClass('collapse').addClass('expand');
		}
		else if($(this).hasClass('expand')) {
			$('.image-gallery .thumbnail-tray').animate({'height':imageGalleryThumbnailTrayHeight}, imageGalleryThumbnailAnimationSpeed, imageGalleryThumbnailAnimationTypeOut, function() {
				$('.image-gallery .thumbnail-tray .thumbnails').animate({'left':10, 'opacity': 100});
			});
			
			$('.image-gallery .thumbnail-tray .expand-collapse a').removeClass('expand').addClass('collapse');
		}
		return false;
	});
	
	$('.image-gallery .thumbnail-tray .thumbnails li a').click(function() {
		clickedImageItem = $(this).parents('li');
		index = $('.image-gallery .thumbnail-tray .thumbnails li').index(clickedImageItem);
		setActiveImageGalleryView(index);
		return false;
	});
	
	function setActiveImageGalleryView(index) {
		$('.image-gallery .big-picture-container').animate({
			left: (index*imageGalleryBigPictureWidth*-1+'px')
		}, galleryImageSlideAcrossSpeed, galleryImageSlideAcrossEase);
		currentImageGalleryViewIndex = index;
	}
	
	//
	//
	//	Section Header Effects
	//
	//
	sectionHeaderImageAnimationTypeIn = 'easeOutSine';
	
	$('.section-header-b img').animate({'right': '35px', 'opacity':'0'}, 1);
	$('.section-header-b img').animate({'right': '65px', 'opacity': '1'}, 2000, sectionHeaderImageAnimationTypeIn);

	$('#form-subscribe').validate({
		messages: {
			firstname: "Please enter your first name",
			lastname: "Please enter your last name",
			email: "Please enter a valid email address"
		},
		submitHandler: function(form) {
			form.submit();
		}
	});
	
	$('#form-email').validate({
		messages: {
			email: "Please enter your email address"
		},
		submitHandler: function(form) {
			$('#form-email .form').remove();
			$('#form-email .hidden-content').show();
			return false;
		}
	});
});
