/*!
 #####################################################################
 # 
 # FaR Partners
 # JavaScript setup routines
 #
 # Hand-crafted by Phenotype (phenotype.net)
 #
 #####################################################################
 */
	
	/* =Assign setup routines
	------------------------------------------------------------------- */
	
		// Called when DOM is ready
		$(document).ready( domSetup( 'global' ) );
		
		// Called when entire page is loaded
		$(window).load( pageSetup( 'global' ) );
		
		// Called when DOM is unloaded
		$(window).unload( domUnload );
	
	/* =Global variables
	------------------------------------------------------------------- */
	
	
	/* =Declare setup routines
	------------------------------------------------------------------- */
	
	/**
	 * domSetup()
	 *
	 * All JavaScript requiring initialisation on DOM LOAD should be called
	 * from this routine.
	 */
	function domSetup( mode ) {

		/* =Multi-mode setup
		------------------------------------------------------------------- */
		
		// Determine setup mode
		mode = typeof( mode ) != 'undefined' ? mode : 'global';
		
		// Perform setup, based on specified mode
		switch ( mode ) {
			
			/**
			 * Global
			 */
			case 'global':
				
				/* =Redirect navigation back to single page (#mono)
				------------------------------------------------------------------- */
				
					// Perform redirect on any page that isn't #mono
					if ( !$('#mono')[0] ) {

						// Get base URL
						var base = $('base').attr('href');
						
						// Get current path
						var path = window.location.href;
						path = path.replace( base, '' );
						
						// Redirect to corresponding section of #mono, if set
						if ( path != '' ) {
							window.location = base + '#' + path;
						} else {
							window.location = base;
						}
						
					}
				
				/* =Enhancements
				------------------------------------------------------------------- */
				
					/**
					 * Content sections accordion
					 */
					
					// Wrap articles with div to animate contents
					$('#mono #primary-content section > article').wrapInner('<div class="article-content" />');
					// Add classes to accordion components
					$('#mono #primary-content section > article').addClass('pane');
					$('#mono #primary-content section > header a').addClass('tab');
					
					// Create custom slide effect
					$.tools.tabs.addEffect( 'customSlide', function( i, done ) {

						// Hide all panes
						this.getPanes().slideUp( 400 );
						// Reveal new pane and call callback function
						this.getPanes().eq( i ).slideDown( 600, done );
						
					});
					
					// Init accordion
					$('#mono #primary-content').tabs( '.content-section > article', {
						tabs			: '.content-section > header a',
						effect			: 'customSlide',
						history			: false, 	// Disable built-in history, we've rolled our own
						initialIndex	: null,
						rotate			: true,
						onBeforeClick	: function( e, i ) {
						},
						onClick			: function( e, i ) {
							
							// Make API reference
							var api = this;
							
							// Get hash
							var hash = window.location.hash
							
							// Get content URL
							var url = hash.substring( 1 );

							// Load pane content
							loadPane( api, i, url );
							
							// Continue
							return true;
						}
					} );
					
					/**
					 * Accordion history
					 */
					
					// Get hash
					var hash = window.location.hash
					
					// If hash is specified, work out which tab to show and load
					if ( hash ) {
						// Make tabs API reference
						var api = $('#mono #primary-content').data('tabs');
						
						// Explode hash to get top-level URL of section, which corresponds to a tab
						hash = hash.split( '/' );
						
						// Get tab URL
						var url = hash[0].substring( 1 );
						
						// Select tab
						api.click( url );

					}

			//break;
			
			/**
			 * Home
			 */
			case 'home':

				/* =Enhancements
				------------------------------------------------------------------- */
					 
					/**
					 * Case study previews slideshow
					 */
					$('#home #case-study-previews.scrollable')
					.append('<a class="cycle previous">Previous</a> <a class="cycle next">Next</a>')
					.scrollable( {
						items		:	'ul',
						circular	: 	true,
						mousewheel	:	false,
						speed		:	800,
						easing		:	'easeInSine',
						next		:	'.scrollable .next',
						prev		:	'.scrollable .previous'
					} )
					.autoscroll( {
						steps		:	1,
						interval	:	6000,
						autoplay	:	true,
						autopause	:	true
					} );
			
			//break;
			
			/**
			 * Case studies
			 */
			case 'case-studies':

				/* =Enhancements
				------------------------------------------------------------------- */

					/**
					 * Case studies list centring
					 */
					
					// Make reference
					$case_studies_list = $('#case-studies #case-study-listings');
					
					// Horizontally centre case studies list
					$case_studies_list.css( {
						'margin-left'	:	( ( 870 - $case_studies_list.width() ) / 2 ),
						'margin-right'	:	( ( 870 - $case_studies_list.width() ) / 2 )
					} );
					
					$case_studies_list.find('li a').each(function(i) {
						// Make reference
						$this = $(this);
						// Calculate if text will wrap onto 2 lines
						if ( $this.text().length <= 9 ) {
							$this.addClass('single-line');
						}
						
					} );
			
			//break;
			
			/**
			 * Services
			 */
			case 'services':
			
				/* =Enhancements
				------------------------------------------------------------------- */

					/**
					 * Services list centring
					 */
					
					// Make reference
					$services_list = $('#services #services-listings');
					
					// Horizontally centre case studies list
					$services_list.css( {
						'margin-left'	:	( ( 870 - $services_list.width() ) / 2 ),
						'margin-right'	:	( ( 870 - $services_list.width() ) / 2 )
					} );
					
					$services_list.find('li a').each(function(i) {
						// Make reference
						$this = $(this);
						// Calculate if text will wrap onto 2 lines
						if ( $this.text().length <= 9 ) {
							$this.addClass('single-line');
						}
						
					} );
				
			//break;
			
			/**
			 * Trends
			 */
			case 'trends':
			
				/* =Enhancements
				------------------------------------------------------------------- */
				
					/**
					 * Trends listings slideshow
					 */
					$('#trends #trends-listings.scrollable')
					.append('<a class="cycle previous">Previous</a> <a class="cycle next">Next</a>')
					.scrollable( {
						items		:	'ul',
						circular	: 	false,
						mousewheel	:	false,
						speed		:	300,
						easing		:	'easeInSine',
						next		:	'.scrollable .next.disabled', // Fake next and previous selectors to disable built-in seek functionality
						prev		:	'.scrollable .previous.disabled',
						size		:	3 // Custom 'size' parameter (emulates parameter from Tools v1.0)
					} );
					
					// Bind custom seek handlers to scroll multiple items at once
					$('#trends #trends-listings.scrollable .next').bind( 'click', function() {
						// Get scrollable API reference
						var api = $(this).parent().data('scrollable');
						// Get size of increment to seek
						var size = api.getConf().size;
						// Seek to new index
						api.move( size );
					});
					$('#trends #trends-listings.scrollable .previous').bind( 'click', function() {
						// Get scrollable API reference
						var api = $(this).parent().data('scrollable');
						// Get size of increment to seek
						var size = api.getConf().size;
						// Seek to new index
						api.move( -size );
					});
					
					/**
					 * Trends Twitter feed
					 */
					$('#trends #twitter-feed').jTweetsAnywhere( {
						username		: 'farpartners',
						count			: 1,
						showTweetFeed	: {
							showTimestamp		: true,
							showSource			: true,
							showGeoLocation		: true,
							showProfileImages	: false,
							showUserScreenNames	: true,
							includeRetweets		: true,
							autorefresh			: {
								mode		: 'auto-insert', 
								interval	: 60,
								duration	: 3600
							}
						}
					} );
				
			//break;
			
			/**
			 * About
			 */
			case 'about':

				/* =Enhancements
				------------------------------------------------------------------- */
					
					/**
					 * People line breaks
					 */
					$('#about #people-listings li a').each( function() {
						// Make reference
						$this = $(this);
						// Get title
						var title = $this.text();
						// Explode title
						title = title.split( ' ' );
						// Wrap each word
						for ( var i in title ) {
							title[i] = '<span>' + title[i] + '</span>';
						}
						// Replace title
						$this.html( title.join( ' ' ) );
					} );
				
			//break;
			
			/**
			 * Contact
			 */
			case 'contact':
			
				/* =Forms
				------------------------------------------------------------------- */
				
				/**
				 * Contact form handler
				 */
				
				$('#contact form#contact-form').bind( 'submit', function(e) {
					
					// Prevent default
					e.preventDefault();
					
					// Make reference
					var $this = $(this);
					
					// Init POST data object
					var post = {};
					
					// Capture value of all form elements
					$this.find('input:not([type="submit"]), select, textarea').each( function() {
						// Make reference
						var $this = $(this);
						// Add data to post object
						post[ $this.attr('name') ] = $this.val();
					} );
					
					// Make reference to pane
					var $pane = $( $this.parents('.content-section > article') );
					
					// Set filter for returned HTML
					var filter = ' #primary-content > article > *:not(header)';
					
					// POST data to form and load resulting HTML
					$.post( $this.attr('action'), post, function( data ) {
						
						// Fade out existing form
						$pane.find('.article-content').fadeOut( 200, 'easeInSine', function() {
							// Make reference
							var $this = $(this);
							
							// Inject filtered content
							$this.html( $( data ).find( filter ) ).fadeIn( 200, 'easeOutSine' );
							
							// Determine mode for post-load setup routines
							var mode = $pane.parent().attr('id');
							
							// Re-run setup routines
							domSetup( mode );
							pageSetup( mode );

						} );
						
					}, 'html' );
					
				} );
				
			//break;
			
			/**
			 * Default
			 */
			default:
			
				/* =Navigation
				------------------------------------------------------------------- */
					
					/**
					 * Bind internal links in content accordion panes to load via AJAX
					 */
					$('#mono a:not([href^="http"], [href^="mailto"], .cycle)').unbind('click').bind( 'click', function(e) {
						// Prevent default
						e.preventDefault();
				
						// Make reference
						var $this = $(this);
						
						// Make tabs API reference
						var api = $this.parents('#mono #primary-content').data('tabs');
						
						// Get content URL
						var url = $this.attr('href');
						
						// Change hash
						window.location.hash = url;
							
						// Get hash
						var hash = window.location.hash;
	
						// Explode hash to get top-level URL of section, which corresponds to a tab
						hash = hash.split( '/' );
						
						// Get tab URL
						var tabUrl = hash[0].substring( 1 );
						
						// Get current tab index
						var index = api.getIndex();
						
						// Compare tab URL index to currently-active tab
						if ( index != $('#mono #primary-content .content-section > header a[href="'+tabUrl+'"]').index( '#mono #primary-content .content-section > header a') ) {
							
							// Select tab
							api.click( tabUrl );
							
						} else {
							
							// Just load new content
							loadPane( api, index, url );
							
						}

					} );

					/*
					Setup external links (target attribute not allowed by XHTML 1.1)
					(see http://www.sitepoint.com/article/standards-compliant-world/)
					*/
					$('a[rel="external"]').attr( 'target', 'blank' );
			
			//break;		
			
		}
		
	}
	
	/**
	 * pageSetup()
	 *
	 * All JavaScript requiring initialisation on PAGE LOAD should be called
	 * from this routine (all images and elements should be loaded and ready to
	 * manipulate by this point)
	 */
	function pageSetup( mode ) {
		
		/* =Multi-mode setup
		------------------------------------------------------------------- */
		
		// Determine setup mode
		mode = typeof( mode ) != 'undefined' ? mode : 'global';
	
	}
	
	/**
	 * domUnload()
	 *
	 * Called when page/DOM is unloaded
	 */
	function domUnload() {

	}
	
	/* =Helper functions
	------------------------------------------------------------------- */
	
	/**
	 * loadPane()
	 *
	 * Loads and filters content from given URL into accordion pane at given index
	 */
	function loadPane( api, i, url ) {
		
		// Make reference to pane
		var $pane = $( api.getPanes()[i] );
		
		// Build content filter
		if ( url == 'home' ) {
			var filter = '#primary-content > section:eq(0) > article';
		} else {
			var filter = '#primary-content > article';
		}
		
		// Load content and filter into selected pane
		$.get( url, function( data ) {
			
			// Get all panes
			var $panes = api.getPanes();
			
			// Clear all the other panes' content and classes
			$panes.attr('class', 'pane').find('.article-content').html('');
			
			// Inject filtered content
			$pane.find('.article-content').hide().html( $( data ).find( filter + ' > *:not(header)' ) ).fadeIn( 200, 'easeOutSine' );
			
			// Add class to pane
			$pane.addClass( $( data ).find( filter ).attr('class') );
			
			// Determine mode for post-load setup routines
			var mode = $pane.parent().attr('id');
			
			// Re-run setup routines
			domSetup( mode );
			pageSetup( mode );
		}, 'html' );
		
	}

