$(document).ready(function() {
	
// ******************************************************* SNIFFING  FOR PROBLEM BROWSERS *******************************************************

		 if( navigator.userAgent.indexOf("Opera") != -1 ){ mf.browser = "opera"; mf.browserVersion = 0; }
	else if( navigator.userAgent.indexOf("MSIE 8") != -1 ){ mf.browser = "IE"; mf.browserVersion = 8; }
	else if( navigator.userAgent.indexOf("MSIE 7") != -1 ){ mf.browser = "IE"; mf.browserVersion = 7; }
	else if( navigator.userAgent.indexOf("MSIE 6") != -1 ){ mf.browser = "IE"; mf.browserVersion = 6; } 	
	else if( navigator.userAgent.indexOf("Android") != -1 || navigator.userAgent.indexOf("webOS") != -1 || navigator.userAgent.indexOf("Palm") != -1 || navigator.userAgent.indexOf("Nokia") != -1 || navigator.userAgent.indexOf("Mini") != -1 || navigator.userAgent.indexOf("IEMobile") != -1 || navigator.userAgent.indexOf("iPhone") != -1 || navigator.userAgent.indexOf("iPod") != -1 || navigator.userAgent.indexOf("BlackBerry") != -1)
	{
		mf.browser = "smartphone"; mf.browserVersion = 0;
	}
	
	else if( navigator.userAgent.indexOf("iPad") != -1 )
	{
		mf.browser = "ipad"; mf.browserVersion = 0;
	}
	
	else{ mf.browser = 'decent browser'; mf.browserVersion = 0; }
	
	// attach a class of "mobile" to the page if we're on smartphone or ipad
	if( mf.browser == "smartphone" || mf.browser == "ipad" )
	{
	$('body').addClass('mobile');
	}

// ******************************************* ROLLOVERS, FOCUS IN/OUT ETC. *******************************************

	// remove and replace input field default values
	// first lets' find all the input fields on the page that have a default value and remove the placeholder values into a separate array
	mf.defaultInputValues = new Array();
	
	$('input[type=text], input[type=email]').each( function(i)
	{		
		if( $(this).attr('placeholder') )
		{
			mf.defaultInputValues[$(this).attr('id')] = $(this).attr('placeholder');
			
			$(this).prop('placeholder', ''); // clear the placeholder attribute - we're using the array to store the values
			
			// now assign the functions that will cause the default text to be hidden and shown
			$(this).focus( function()
			{		
				if( $(this).prop('value') == mf.defaultInputValues[$(this).attr('id')] )
				{
					$(this).prop('value', '')
				}
			});
			
			$(this).focusout( function()
			{
				if( $(this).prop('value') == '' )
				{
					$(this).prop('value', mf.defaultInputValues[$(this).attr('id')])
				}
			});
		}
	});
	
// ************************************************ IPHONE HEADER MENUS ************************************************	
	 
	if( mf.browser == "smartphone" )
	{	
		
		mf.mobileHeader = {};
		
		mf.mobileHeader.mainMenuObject = $('#main_nav_menu li');
		mf.mobileHeader.supplementaryMenuObject = $('#supplementary_menu li');
		mf.mobileHeader.topicsMenuObject = $('#categories_nav li');
		
		// mf.mobileHeader.menus = [mf.mobileHeader.mainMenuObject, mf.mobileHeader.supplementaryMenuObject, mf.mobileHeader.topicsMenuObject]
		mf.mobileHeader.menus = [mf.mobileHeader.supplementaryMenuObject];
		
		mf.mobileHeader.topicsMenuHeight = mf.mobileHeader.topicsMenuObject.outerHeight() * ( Math.ceil(mf.mobileHeader.topicsMenuObject.length / 3) );
		
		// to get correct display of borders to simulate a complete grid, we'll have to fill in with extra <li> elements if we're a few short
		for( i=0; i < mf.mobileHeader.menus.length; i++ ) // loop through the menus
		{
			
			if( mf.mobileHeader.menus[i] == mf.mobileHeader.supplementaryMenuObject )
			{
				var modulus = (mf.mobileHeader.menus[i].length - 1) % 3; // the remainder if we divide by 3 - needs to take into account language 
			}
			else
			{
				var modulus = mf.mobileHeader.menus[i].length % 3; // the remainder if we divide by 3
			}
			
			if( modulus != 0 ) // if the number of <li> elements in the menu is not a multiple of three we need to add filler <li> elems
			{
				for( j=0; j < 3 - modulus; j++ )
				{
					if( mf.mobileHeader.menus[i] == mf.mobileHeader.supplementaryMenuObject )
					{
						$('#supplementary_menu li.lanuage_select').before('<li>&nbsp;</li>');
					}
					else
					{
						mf.mobileHeader.menus[i].parent().append('<li>&nbsp;</li>');
					}
				}
			}
		}
		
		
		// on clicking 'view themes', apply .themes_shown class to the categories nav (toggle on and off)		
		$('#categories_nav h3').toggle
		(
			function()
			{
				$('#banner').addClass('themes_shown');
				// $('#categories_nav ul').css('height', mf.mobileHeader.topicsMenuHeight + 'px');
			},
			function()
			{
				$('#banner').removeClass('themes_shown');
				// $('#categories_nav ul').css('height', '0px');
			}
		);

	}

	
// ************************************************ ISOTOPE ************************************************
	
	mf.resetIsotope = function()
	{
		if( mf.browser != "smartphone" )
		{
			$('#main').not('#blog #main').isotope({
				itemSelector : 'article.article, article.promotion, article.advert, article.display, article.magazine, article.facebook_box, #homepage_promo_panel, #takeover_sidepanel',
				masonry: { columnWidth: 320 },
				animationEngine: 'best-available',
				animationOptions: { duration: 400, queue: false },
				hiddenStyle: {  },
				visibleStyle: {  }
			});
		}
	}
	
	
// ************************************************ ON TYPEKIT FONTS LOADING ************************************************

// ******************************************************* MISC. ARTICLE-RELATED FUNCTIONS ***********************************

	// applies class of .first to first paragraph in article main content & gallery descriptions
	$('#article_body p').first().addClass('first');
	$('.mf_gallery_description p:first-child').addClass('first');


// ******************************************************* ADVERT TRACKING FUNCTIONS ***************************************** 

// track clickthroughs on all types of advert

mf.adverts = {};

// function that actions the google analytics click tracking event
mf.adverts.trackClick = function( adID, adClientName, adTitle )
{
	if (_gaq) _gaq.push([ '_trackEvent', 'advert', 'click', adID + ': ' + adTitle + ' (' + adClientName + ')' ]);
}

// attach event handlers to all adverts on the page to track clicks on the advert
$('.banner_advert, .advert, .promotion, #takeover_sidepanel, #takeover_main_image').live( 'click', function(e)
{
	advertElem = $(this);
	
	adID = advertElem.attr('data-ad-id')
	adClientName = advertElem.attr('data-ad-advertiser')
	adTitle = advertElem.attr('data-ad-title')
	
	mf.adverts.trackClick( adID, adClientName, adTitle );
});

	
// ******************************************************* DYNAMICALLY LOAD DISPLAY ARTICLE **********************************
	
	mf.pageLoad = {};
	
	mf.pageLoad.setup = function()
	{		
		// if there's an article already on the page
		if( $('article.display').length > 0 )
		{ 
			mf.pageLoad.articleIsInPlace = true; // is set to true if the HTML container for the display article is present on the page
			$('.close_button').click( function(e){ mf.pageLoad.closeArticle(e) });
		}
		else
		{
			mf.pageLoad.articleIsInPlace = false;
		}	
		
		if( mf.pageLoad.articleIsInPlace )
		{	
			// Triggers function when images are loaded - we'll then resize the images and apply isotope.
			$('#article_body_container').imagesLoaded( function()
			{
				mf.pageLoad.resizeArticleImages();
			});
			
			// cause the articles in the article list to become unghosted when the user clicks somewhere in the panel
			$('#articles_list').bind( 'mouseover', function(){ mf.pageLoad.fadeInArticlesList() } );
		}
		
		
		// if someone clicks on the article list while an article is displayed, the articles become unghosted
		mf.pageLoad.fadeInArticlesList = function()
		{
			$('#articles_list').removeClass('ghosted');
			$('#articles_list').unbind('mouseover');
			$('article.display').bind( 'mouseover', function(){ mf.pageLoad.fadeOutArticlesList() } );
		}
		
		// if someone clicks on the article being displayed when the article list isn't ghosted, it becomes ghosted		
		mf.pageLoad.fadeOutArticlesList = function()
		{
			$('#articles_list').addClass('ghosted');
			$('article.display').unbind('mouseover');
			$('#articles_list').bind( 'mouseover', function(){ mf.pageLoad.fadeInArticlesList() } );
		}
	}
	
	
	mf.pageLoad.closeArticle = function(e, callerObject, linkUrl)
	{							   		
		if(e){
			e.preventDefault();
		}
		
		// remove rollover ghosting and unghosting effects from display article & articles list
		$('#articles_list').unbind('mouseover');
		$('article.display').unbind('mouseover');
		
		// remove the isotope-item class - this will aid a smooth fade out transition
		$('article.display').removeClass('isotope-item');
		
		// transition out the display article and remove it from the HTML document on completion
		$('article.display').fadeOut(600, function()
		{												  
			$('article.display').remove();			
			mf.pageLoad.articleIsInPlace = false;

			// if the closeArticle function was called due to another link being clicked while an article was already open, load the new article
			if( callerObject || linkUrl )
			{
				// mf.pageLoad.loadNewArticle( null, callerObject, linkUrl );
			}		
			// else reset the layout & reset the URL in the address bar
			else
			{
				$('#main').isotope('reLayout', function()
				{
					$('#articles_list').removeClass('ghosted');	
				});	
						
				//typetoken.updateBrowserHistory('index', mf.wp.siteUrl + '/');
			}
		});
	}
	
	
	
	mf.pageLoad.resizeArticleImages = function( videoOnly )
	{				
		var affectedElements = '#article_video object, #article_video video, #article_video embed, #article_video iframe, #article_body p video, #article_body p object, #article_body p embed, #article_body p iframe';
		
		// var affectedElements = '#article_video object, #article_video video, #article_video embed, #article_video iframe';
		
		if( !videoOnly )
		{
			// affectedElements += ', #article_body_container p img';
		}
		
		// set the sizes of the article body images & video
		$( affectedElements ).each( function(i)
		{				
			// if it's a video, size according to the #article_video container element, as videos may or may not appear in the #article_body_container element
			
			// is the current element a video?
			//var tagName = $(this).get(0).tagName;
			//tagName = tagName.toLowerCase();			
			//var isVideo = (tagName == 'iframe' || tagName == 'embed' || tagName == 'video') ? true : false;
			
			// if it's a video, resize according to #article_video element width, else, it's an image, so resize according to #article_body_container element width
			//var mediaContainerElement = (isVideo) ? '#article_video' : '#article_body_container';
			
			var mediaContainerElement = $(this).parent();
			var mediaWidth = $(this).attr('width');
			// var imagesPanelWidth = ($('#article_body_container').width() <= imageWidth) ? $('#article_body_container').width() : imageWidth ;
			// var mediaPanelWidth = (mediaContainerElement.width() <= mediaWidth) ? mediaContainerElement.width() : mediaWidth ;
			var mediaPanelWidth = mediaContainerElement.width();			
			var mediaScale = mediaPanelWidth / mediaWidth;
			$(this).css( 'height', ( $(this).attr('height') * mediaScale) + 'px' );			
		});	
		
		if( mf.browser != "smartphone" ){ $('#main').isotope('reLayout'); }
	}

	
// ******************************************************* DYNAMICALLY LOAD MORE ARTICLES VIA AJAX *******************************************************

	mf.articlesLoad = {};
	
	mf.articlesLoad.previousTotalArticles = 0;
	//mf.articlesLoad.articlesLoadedTotal = 0;
    
    mf.articlesLoad.articlesContainer = {};    
    
	function loadMorePosts(e)
	{
		e.preventDefault();	
		
		// if there are no more posts to load in, do nothing.
		if( mf.wp.currentPage >= mf.wp.totalPages )
		{
			return;
		}
		
		if( !mf.articlesLoad.currentlyLoadingMore  )
		{	
			mf.articlesLoad.previousTotalArticles = $('#articles_list article').length;
			
			// let's make sure the user can't try and load even more articles while the first lot hasn't finished settling into place
			mf.articlesLoad.currentlyLoadingMore  = true;
			
			// apply loading visual style to the loadmore link
			$('#load_more').addClass('currently_loading');
			
			// let's create an empty container for the articles to go into (we'll attach it to the DOM later)
			mf.articlesLoad.articlesContainer = $(document.createElement('div'));	
			
			// build the list of parameters to append to the url for the ajax request
			var urlParams = 'paged=' + (mf.wp.currentPage + 1);
			if( mf.wp.currentCategory.length > 0 ){ urlParams += '&category_name=' + mf.wp.currentCategory };
			if( mf.wp.currentTag.length > 0 ){ urlParams += '&tag=' + mf.wp.currentTag };
			if( mf.wp.currentSearchTerm.length > 0 ){ urlParams += '&s=' + mf.wp.currentSearchTerm };
			if( mf.wp.postType.length > 0 ){ urlParams += '&post_type=' + mf.wp.postType };
			if( mf.wp.currentTopic.length > 0 ){ urlParams += '&topic=' + mf.wp.currentTopic };
			if( mf.wp.promoIDs.length > 0 ){ urlParams += '&promo_IDs=' + mf.wp.promoIDs };
			if( mf.wp.adIDs.length > 0 ){ urlParams += '&ad_IDs=' + mf.wp.adIDs };
			if( mf.wp.topicFilter.length > 0 ){ urlParams += '&filter=' + mf.wp.topicFilter };
			if( mf.wp.isPage ){ urlParams += '&isPage=true' };
			
			// load in the new articles and define the call back
			mf.articlesLoad.articlesContainer.loadShiv( mf.wp.siteUrl + ' #articles_list article', urlParams, mf.articlesLoad.articlesLoaded );
			// console.log(mf.wp.siteUrl + '?' + urlParams);
		}
	}
		
	mf.articlesLoad.articlesLoaded = function()
	// called when finished loading in more articles via ajax
	{			
		// take the new article thumbnail and hide them before moving them into the main articles list
		var newArticles = mf.articlesLoad.articlesContainer.find('article');
		//mf.articlesLoad.articlesLoadedTotal = mf.articlesLoad.articlesContainer.find('article').length;
		newArticles.css('display', 'none');
		
		// console.log( mf.articlesLoad.articlesContainer.html() );
		
		/*
		newArticles.each( function()
		{
			console.log($(this).html());
		});
		*/

		// add the new articles to the list and then apply isotope layout
		$('#articles_list').append(newArticles);		
		if( mf.browser != "smartphone" ){ $('#main').isotope( 'appended', newArticles ); }
		newArticles.removeClass('isotope-item'); // makes the reveal transition smoother - we'll reinstate it as soon as the transition is complete
		
		var currentThumbnail = 0;
		var revealDelay = 0;
		
		// fade in the thumbnails sequentially
		for( i=0; i<newArticles.length; i++ )
		{
			//currentThumbnail = ( (mf.wp.currentPage - mf.articlesLoad.pageOffset) * mf.wp.postsPerPage) + i;
			currentThumbnail = mf.articlesLoad.previousTotalArticles + i;
			revealDelay = 400 + (i * 100);
			
			$('#articles_list article').eq(currentThumbnail).delay(revealDelay).fadeIn(1000, function(){ $(this).addClass('isotope-item'); });
		}
		
		// advance the page counter to the current page
		mf.wp.currentPage++;
		mf.articlesLoad.finishedLoadingMore();
		
		// generate a google analytics event - more info:
		// http://blogs.sitepoint.com/google-analytics-track-javascript-ajax-events/
		// http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html)
		if ( typeof _gaq != 'undefined' ) _gaq.push(['_trackEvent', 'load_more', 'load', 'page ' + mf.wp.currentPage]); 
		
	}
		
	mf.articlesLoad.finishedLoadingMore = function()
	// called when the last of the articles have loaded in via the infinite scroll feature
	{								
		// now the reveals are all finished we can allow loading in a new set of articles
		mf.articlesLoad.currentlyLoadingMore  = false;
		
		// restore the load more icon only if there are more posts available
		if( mf.wp.currentPage < mf.wp.totalPages )
		{
			$('#load_more').removeClass('currently_loading');
		}
		
		mf.articlesLoad.checkForMorePosts();
	}
				
	function checkForMorePosts()
	{
		// check to see of we actually have any more posts beyond the current page (do we need the load more button?)
		
		// if we've reached the last page
		if( mf.wp.currentPage >= mf.wp.totalPages )
		{			
			// change the rollover text for the more posts link
			$('#load_more_text').hide();
			$('#no_articles_text').show();			
			
			// remove the rollover animation from the load more button
			$('#load_more').removeClass('morePosts');
			
			return false;
		}
		else
		{
			// add the rollover animation to the load more button if it isn't already present
			if( !$('#load_more').hasClass('morePosts') )
			{
				$('#load_more').addClass('morePosts');
			}
			return true;	
		}
	}
	
	function setupDynamixIndexLoading()
	{
		// get the WP variables that were exposed to javascript via footer.php
		mf.wp.determineWpVariables();
		
		// if we're starting the dynamic page x pages into paginated results, set the page offset accordingly		
		mf.articlesLoad.pageOffset = 0;
		if( mf.wp.currentPage != 1 )
		{
			mf.articlesLoad.pageOffset = mf.wp.currentPage - 1;	
		}
			
		mf.wp.queryString = mf.wp.queryString.length > 0 ? '&' + mf.wp.queryString : '';		
		mf.articlesLoad.currentlyLoadingMore = false;
		
		mf.articlesLoad.checkForMorePosts = checkForMorePosts;
		// mf.articlesLoad.loadMorePosts = loadMorePosts;		

		// call the loadMorePosts function when the user clicks the Load More button
		$('#load_more').click( function(e){ loadMorePosts(e); });
		
		mf.articlesLoad.checkForMorePosts();
	}
	
	// ******************************************* ARTICLE PAGE CAROUSEL *******************************************
	
	// carousel namespace
	mf.carousel = {};
	
	// ******** carousel properties ******** 
	mf.carousel.carousel = '#article_gallery';
	mf.carousel.slideContainer = '#article_slides_container';
	mf.carousel.slide = '.article_slide';
	mf.carousel.slideImg = '.article_slide img';
	mf.carousel.thumbnail = '#article_gallery_thumbnails li';
	mf.carousel.thumbnailImg = '#article_gallery_thumbnails img';
	mf.carousel.nextButton = '#article_gallery_next_slide';
	mf.carousel.prevButton = '#article_gallery_previous_slide';	
	
	mf.carousel.caption = '.mf_gallery_caption';
	mf.carousel.description = '.mf_gallery_description';
	
	//mf.carousel.slideWidth = $('#article_gallery_slides').width();
	mf.carousel.slideWidth = 940;
	// this shouldn't be hard coded, but was causing some issues on ipad with gutters sometimes appearing between slides
	// (it thought the slides were wider than they actually were)
	
	mf.carousel.slideHeight = 0;
	
	mf.carousel.currentSlide = 0;
	mf.carousel.previousSlide = 0;
	mf.carousel.totalSlides = $(mf.carousel.slide).length;
	
	// touch swipe-related properties	
	mf.carousel.touchStartX = 0;
	mf.carousel.touchPreviousX = 0;
	mf.carousel.touchCurrentX = 0;
	mf.carousel.touchXMovement = 0;	
	
	mf.carousel.touchStartY = 0;
	mf.carousel.touchCurrentY = 0;
	mf.carousel.touchYMovement = 0;
	
	mf.carousel.swipeSpeedThreshold = 3;
	mf.carousel.touchInProgress = false;
	mf.carousel.touchScrollPage = false;
	mf.carousel.firstTouchMove = true;
	mf.carousel.usingTouchEvents = false;	
	
	mf.carousel.slideContainerPosition = 0;
	
	mf.carousel.useDynamicCaptions = $(mf.carousel.caption).length > 0 ? true : false;

	
	// ******** carousel methods ******** 
	
	mf.carousel.repositionSlides = function()
	{
		// resposition each slide
		$(mf.carousel.slide).each( function(i)
		{
			$(this).css('position', 'absolute');
			$(this).css('left', (i * mf.carousel.slideWidth) + 'px');
			$(this).css('top', 0 + 'px');
		});
	}

	mf.carousel.repositionSlideContainer = function()
	{
		// cancel any CSS transitions applied to the slideshow, then effect the position change
		$(mf.carousel.slideContainer).css( '-webkit-transition' , 'none');			
		$(mf.carousel.slideContainer).css('-webkit-transform', 'translate3D(' + (0 - (mf.carousel.slideWidth * mf.carousel.currentSlide)) + 'px,0,0)');;
	}
	
	mf.carousel.resizeSlideContainer = function()
	{
		$(mf.carousel.slideContainer).css('width', (mf.carousel.slideWidth * mf.carousel.totalSlides) + 'px');
	}
	
	
	mf.carousel.resizeSlides = function()
	{
		// resizes the slides and carousel for smartphones
		
		// set the new width;
		mf.carousel.slideWidth = $(mf.carousel.carousel).width();
		$(mf.carousel.slide).css('width', mf.carousel.slideWidth + 'px');
		
		// use the first image in the slideshow as the basis for determining the height / width ratio
		// var imageWidth = $(mf.carousel.slideImg).first().attr('width');
		// var imageHeight = $(mf.carousel.slideImg).first().attr('height');
		// we know that amusement slideshow images are maximum 940 x 640, so that's what we'll use for image size
		var imageWidth = 940;
		var imageHeight = 640;
		
		var imageRatio = imageWidth / imageHeight;		
		var newImageHeight = mf.carousel.slideWidth / imageRatio;
		
		// set the new carousel height
		mf.carousel.slideHeight = newImageHeight;
		$(mf.carousel.carousel).css('height', mf.carousel.slideHeight + 'px');
		
		// set the height of each slide
		$(mf.carousel.slide).each( function()
		{
			$(this).css('height', mf.carousel.slideHeight + 'px');
		});
		
		// resposition the next and previous buttons
		var nextPrevBtnHeight = $(mf.carousel.nextButton).height();
		
		$(mf.carousel.nextButton).css('top', ((mf.carousel.slideHeight / 2) - (nextPrevBtnHeight / 2)) + 'px');
		$(mf.carousel.prevButton).css('top', ((mf.carousel.slideHeight / 2) - (nextPrevBtnHeight / 2)) + 'px');

		/*
		$('#article_gallery_previous_slide').css('width', (mf.carousel.slideWidth) / 2 + 'px');
		$('#article_gallery_next_slide').css('width', (mf.carousel.slideWidth) / 2 + 'px');
		$('#article_gallery_previous_slide').css('height', (mf.carousel.slideHeight) +'px');
		$('#article_gallery_next_slide').css('height', (mf.carousel.slideHeight) + 'px');
		*/

	}
	
	mf.carousel.advanceCounter = function( desiredSlide )
	{		
		newSlide = desiredSlide;
		
		if( newSlide > mf.carousel.totalSlides - 1 )
		{
			newSlide = mf.carousel.totalSlides - 1;
		}
		else if( newSlide < 0 )
		{
			newSlide = 0;
		}
		
		if( newSlide == mf.carousel.currentSlide )
		{
			return;
		}
		
		// sort out the classes on the nav buttons
		$( mf.carousel.thumbnail ).eq( newSlide ).addClass('selected');
		$( mf.carousel.thumbnail ).eq( mf.carousel.currentSlide ).removeClass( 'selected' );
		
		mf.carousel.previousSlide = mf.carousel.currentSlide;
		mf.carousel.currentSlide = newSlide;
	}
	
	mf.carousel.clickSlideNav = function(e)
	{
		e.preventDefault();		
		if( ! touchEventsInUse() )
		{
			mf.carousel.advanceCounter( $(e.target).attr('data-goto-slide') )
			mf.carousel.effectTransition();
		}
	}
	
	mf.carousel.touchSlideNav = function(e)
	{
		mf.carousel.usingTouchEvents = true;
		
		e.preventDefault();
		e.stopPropagation();
		mf.carousel.advanceCounter( $(e.currentTarget).attr('data-goto-slide') );		
		mf.carousel.effectTransition();
	}
	
	mf.carousel.effectTransition = function()
	{	
		// teansition the slides
		if( $('html').hasClass('csstransforms3d') )
		{
			$(mf.carousel.slideContainer).css( '-webkit-transition' , '-webkit-transform 0.4s');		
			$(mf.carousel.slideContainer).css( '-webkit-transform','translate3D(' + (0 - (mf.carousel.currentSlide * mf.carousel.slideWidth)) + 'px,0,0)' );
		}
		else
		{
			$(mf.carousel.slideContainer).animate( { left: (0 - (mf.carousel.currentSlide * mf.carousel.slideWidth)) }, 400 );
		}
		
		// now transition the captions and descriptions (if applicable)
		if( mf.carousel.useDynamicCaptions )
		{			
			$( mf.carousel.caption ).eq( mf.carousel.previousSlide ).hide();
			$( mf.carousel.caption ).eq( mf.carousel.currentSlide ).show();
			
			$( mf.carousel.description ).eq( mf.carousel.previousSlide ).hide();
			$( mf.carousel.description ).eq( mf.carousel.currentSlide ).show();
		}
	}
	
	mf.carousel.clickNext = function(e)
	{
		e.preventDefault();
		if( ! touchEventsInUse() )
		{
			mf.carousel.advanceCounter( mf.carousel.currentSlide + 1 );
			mf.carousel.effectTransition();
		}
	}
	
	mf.carousel.clickPrev = function(e)
	{
		e.preventDefault();
		if( ! touchEventsInUse() )
		{
			mf.carousel.advanceCounter( mf.carousel.currentSlide - 1 );	
			mf.carousel.effectTransition();
		}
	}
	
	mf.carousel.touchNext = function(e)
	{
		mf.carousel.usingTouchEvents = true;
		
		e.preventDefault();
		e.stopPropagation();
		
		mf.carousel.advanceCounter( mf.carousel.currentSlide + 1 );		
		mf.carousel.effectTransition();
	}
	
	mf.carousel.touchPrev = function(e)
	{
		mf.carousel.usingTouchEvents = true;
		
		e.preventDefault();
		e.stopPropagation();
		
		mf.carousel.advanceCounter( mf.carousel.currentSlide - 1 );		
		mf.carousel.effectTransition();
	}
	
	mf.carousel.touchCancel = function(e)
	{
		e.preventDefault();
		e.stopPropagation();
	}
	
	mf.carousel.touchStart = function(e)
	{
		mf.carousel.usingTouchEvents = true;
		
		// cancel any CSS transitions applied to the slideshow
		$(mf.carousel.slideContainer).css( '-webkit-transition' , 'none');	
		
		mf.carousel.touchInProgress = true;
		
		mf.carousel.touchStartX = e.touches[0].pageX;
		mf.carousel.touchStartY = e.touches[0].pageY;
		mf.carousel.touchPreviousX = 0;
		mf.carousel.touchCurrentX = e.touches[0].pageX;
		mf.carousel.touchCurrentY = e.touches[0].pageY;
		mf.carousel.touchXMovement = 0;
		mf.carousel.touchYMovement = 0;
		mf.carousel.touchScrollPage = false;
		mf.carousel.firstTouchMove = true;
		
		mf.carousel.nextSlidePosition = mf.carousel.slideWidth * (mf.carousel.currentSlide + 1);
		mf.carousel.previousSlidePosition = mf.carousel.slideWidth * (mf.carousel.currentSlide - 1);
		
		// get the initial position of the user's finger
		mf.carousel.touchCurrentX = mf.carousel.touchPreviousX = mf.carousel.touchStartX;
	}
	
	mf.carousel.touchMove = function(e)
	{		
		mf.carousel.touchXMovement = e.touches[0].pageX - mf.carousel.touchStartX;
		mf.carousel.touchYMovement = e.touches[0].pageY - mf.carousel.touchStartY;
		
		// determine how much horizontal & vertical finger movement there has been since the touch event started
		mf.carousel.touchPreviousX = mf.carousel.touchCurrentX;
		mf.carousel.touchCurrentX = e.touches[0].pageX;
		mf.carousel.touchCurrentY = e.touches[0].pageY;
		
		// if it's the first time touchMove has been called during the current touch event, determine whether this will be a vertical page scroll or a carousel swipe
		if( mf.carousel.firstTouchMove && Math.abs(mf.carousel.touchYMovement) > Math.abs(mf.carousel.touchXMovement) )
		{
			mf.carousel.touchScrollPage = true;
		}
		
		mf.carousel.firstTouchMove = false;
		
		// if the current touch movement is not a page scroll movement, move the carousel accordingly
		if( !mf.carousel.touchScrollPage )
		{
			e.stopPropagation();
			e.preventDefault();
	
			// get the current horizontal offset of the corrent slide
			mf.carousel.getSlideContainerPosition( mf.carousel.currentSlide );
			
			// move the slides according to how far the user's finger has moved
			$(mf.carousel.slideContainer).css('-webkit-transform', 'translate3D(' + (mf.carousel.slideContainerPosition + mf.carousel.touchXMovement) + 'px,0,0)');
		}
	}
	
	mf.carousel.touchEnd = function(e)
	{
		e.stopPropagation();
		e.preventDefault();
		
		mf.carousel.touchInProgress = false;
		
		var touchXSpeed = mf.carousel.touchCurrentX - mf.carousel.touchPreviousX;
		var xTravelSinceStart = Math.abs( mf.carousel.touchCurrentX - mf.carousel.touchStartX );
		var yTravelSinceStart = Math.abs( mf.carousel.touchCurrentY - mf.carousel.touchStartY );
		var nextSlide = mf.carousel.currentSlide;
		
		// if we've had virtually no movement since the use pressed his finger, it's a press / tap rather than a swipe, so let's load the link
		
		// if the finger has moved more than half a slide width in either direction, or was moving fast enough, trigger a slide change
		if( (mf.carousel.touchXMovement > mf.carousel.slideWidth / 2 ||  touchXSpeed > mf.carousel.swipeSpeedThreshold) && mf.carousel.currentSlide > 0 )
		{
			nextSlide = parseInt(mf.carousel.currentSlide) - 1;
		}
		else if( (mf.carousel.touchXMovement < 0 - (mf.carousel.slideWidth / 2) || touchXSpeed < 0 - mf.carousel.swipeSpeedThreshold) && mf.carousel.currentSlide < mf.carousel.totalSlides - 1 )
		{
			nextSlide = parseInt(mf.carousel.currentSlide) + 1;
		}
		
		// initiate the transition
		//mf.carousel.getSlideContainerPosition( nextSlide );
		//$(mf.carousel.slideContainer).css( '-webkit-transition' , '-webkit-transform 0.4s');		
		//$(mf.carousel.slideContainer).css( '-webkit-transform','translate3D(' + mf.carousel.slideContainerPosition + 'px,0,0)' );
		
		//mf.carousel.currentSlide = nextSlide;
		mf.carousel.advanceCounter( nextSlide );
		mf.carousel.effectTransition();
		
	}
	
	
	// checks to see if the user has previously interacted using touch. if so, returns true and cancels all click event handlers
	function touchEventsInUse()
	{
		if( mf.carousel.usingTouchEvents == true )
		{
			$(mf.carousel.nextButton).unbind( 'click');			
			$(mf.carousel.prevButton).unbind( 'click');
			$(mf.carousel.thumbnailImg).unbind( 'click' );
			
			return true;
		}
		else
		{
			return false	
		}
	}
	
	mf.carousel.getSlideContainerPosition = function( slideNumber )
	{
		mf.carousel.slideContainerPosition = 0 - (slideNumber * mf.carousel.slideWidth);
	}
	
// ******************************************* INITIALISE ARTICLE PAGE CAROUSEL *******************************************
	
	// show all slides
	// $('#main_carousel .carousel_slides article').css('display', 'block');
	
	// loop through all slides and position one after the other horizontally
	mf.carousel.repositionSlides();
	
	// set the width of the slide container element to be large enough to contain all slides
	mf.carousel.resizeSlideContainer();
	
	// event handlers for clicking the slide advance button
	$(mf.carousel.nextButton).bind( 'click', function(e){
		mf.carousel.clickNext(e);
	});
	
	$(mf.carousel.prevButton).bind( 'click', function(e){
		mf.carousel.clickPrev(e);
	});
	
	//event handlers for the navigation buttons
	$(mf.carousel.thumbnailImg).bind( 'click', function(e){
		mf.carousel.clickSlideNav(e);
	});
	
	// event handler for touchstart event
	if ( 'ontouchstart' in document && $(mf.carousel.carousel ).length > 0 && mf.carousel.totalSlides > 1 )
	{		
		// slideshow swiping
		document.getElementById('article_slides_container').addEventListener("touchstart", mf.carousel.touchStart, false);
		document.getElementById('article_slides_container').addEventListener("touchmove", mf.carousel.touchMove, false);
		document.getElementById('article_slides_container').addEventListener("touchend", mf.carousel.touchEnd, false);
		/*
		document.getElementById('article_gallery_previous_slide').addEventListener("touchstart", mf.carousel.touchStart, false);
		document.getElementById('article_gallery_previous_slide').addEventListener("touchmove", mf.carousel.touchMove, false);
		document.getElementById('article_gallery_previous_slide').addEventListener("touchend", mf.carousel.touchEnd, false);
		*/
		// touch advance button
		document.getElementById('article_gallery_next_slide').addEventListener("touchstart", mf.carousel.touchNext, false);
		document.getElementById('article_gallery_previous_slide').addEventListener("touchstart", mf.carousel.touchPrev, false);
		
		$(mf.carousel.thumbnailImg).each( function()
		{
			var mfThumbnailImgId = $(this).attr('id');
			document.getElementById( mfThumbnailImgId ).addEventListener("touchstart", mf.carousel.touchSlideNav, false);
		})
	}
	
	/*
	// event handler for touchstart event
	if ( 'ontouchstart' in document && $(mf.carousel.carousel ).length > 0 && mf.carousel.totalSlides > 1 )
	{		
		
		document.getElementById('article_gallery_next_slide').addEventListener("touchstart", mf.carousel.touchStart, false);
		document.getElementById('article_gallery_next_slide').addEventListener("touchmove", mf.carousel.touchMove, false);
		document.getElementById('article_gallery_next_slide').addEventListener("touchend", mf.carousel.touchEnd, false);
		
		document.getElementById('article_gallery_previous_slide').addEventListener("touchstart", mf.carousel.touchStart, false);
		document.getElementById('article_gallery_previous_slide').addEventListener("touchmove", mf.carousel.touchMove, false);
		document.getElementById('article_gallery_previous_slide').addEventListener("touchend", mf.carousel.touchEnd, false);
		
		// touch advance button
		document.getElementById('article_gallery_next_slide_image').addEventListener("touchstart", mf.carousel.touchNext, false);
		document.getElementById('article_gallery_previous_slide_image').addEventListener("touchstart", mf.carousel.touchPrev, false);
		
		document.getElementById('article_gallery_next_slide_image').addEventListener("touchmove", mf.carousel.touchCancel, false);
		document.getElementById('article_gallery_previous_slide_image').addEventListener("touchmove", mf.carousel.touchCancel, false);
		
		document.getElementById('article_gallery_next_slide_image').addEventListener("touchend", mf.carousel.touchCancel, false);
		document.getElementById('article_gallery_previous_slide_image').addEventListener("touchend", mf.carousel.touchCancel, false);
		
		$(mf.carousel.thumbnailImg).each( function()
		{
			var mfThumbnailImgId = $(this).attr('id');
			document.getElementById( mfThumbnailImgId ).addEventListener("touchstart", mf.carousel.touchSlideNav, false);
		})
	}
	*/
	
	// if we have dynamic captions & descriptions, hide all descriptions and captions but the first
	if( mf.carousel.useDynamicCaptions )
	{
		$( mf.carousel.caption ).each( function(i)
		{
			if( i > 0 ) { $(this).hide(); }
		});
		
		$( mf.carousel.description ).each( function(i)
		{
			if( i > 0 ) { $(this).hide(); }
		});
	}
	
	// if it's a smartphone, resize the slides & container elements accordingly

	if( mf.browser == "smartphone" )
	{
		mf.carousel.resizeSlides();
		mf.carousel.repositionSlides();
		
		window.onorientationchange = function(){
			mf.carousel.resizeSlides();
			mf.carousel.repositionSlides();
			mf.carousel.resizeSlideContainer();
			mf.carousel.repositionSlideContainer();
		}
		
		$(window).resize( function(){
			mf.carousel.resizeSlides();
			mf.carousel.repositionSlides();
			mf.carousel.resizeSlideContainer();
			mf.carousel.repositionSlideContainer();
		});
	}

	
// ******************************************************* INITIALISATION *******************************************************	

	// initialisation for all devices
	
	// initialisation for everything but smartphones AND iPads

	function initNotSmartphoneNotIpad()
	{
		// setupShowNavPanel();
	}

	// initialisation for everything but smartphones	
	function initNotSmartphone()
	{
		mf.resetIsotope();
		mf.pageLoad.setup();
		setupDynamixIndexLoading();
		
		//setupSearchinput();
	}
	
	// initialisation for smartphones	
	function initSmartphone()
	{
		mf.pageLoad.resizeArticleImages( true );
		window.onorientationchange = function(){ mf.pageLoad.resizeArticleImages( true ) };
		setupDynamixIndexLoading();
	}
	
	//init_all();
	//if( typetoken.browser != "smartphone" && typetoken.browser != "ipad" ){ initNotSmartphoneNotIpad(); }
	if( mf.browser != "smartphone" ){ initNotSmartphone(); }
	if( mf.browser == "smartphone" ){ initSmartphone(); }
});
