// Namespace

	var Gravity = Gravity || {};

// Functions
	
	Gravity.desktop = {
		
		init : function() {
			
			// JS on
				
				$('html').removeClass('no-js').addClass('js');
			
			// Check for hashes in URL and scroll there if required
				
				$('#our-work').localScroll();
			
			// Global Navigation
			
				Gravity.desktop.globalNav();
				
			// Social network status
			
				Gravity.desktop.socialStatus();
				
			// Work
			
				Gravity.desktop.workNav();
				
			// About 
				
				Gravity.desktop.aboutNav();
			
			// People 
			
				Gravity.desktop.peopleInfo();
				
			// Footer 
			
				Gravity.desktop.footerDrawer();
				
		},
		
		globalNav : function() { // Set up global navigation and target click event
			
			// Cache selectors
				
				var $globalNav = $('.header nav')
				
			// Enable home link on logo
			
				Gravity.desktop.homeClick();
			
			// Set initial current nav link
			
				$globalNav.find('li:first-child').addClass('current');
					
			// Insert current nav item holder	
				
				$globalNav.prepend('<div id="marker"></div>');
				
			// Change current nav item depending on which section header h1 is currently visible
			
				$(window).bind('scroll', function() {
					
					// Check id of section with currently visible H1
					
						var sectionID = $('#page > section > header h1:in-viewport').parent().parent().attr('class');
						
					// Get appropriate link in nav to set to current
						
						if (typeof sectionID != 'undefined') {
							
							// Set new current item
								
								$globalNav.find('.current').removeClass('current');
								
								$globalNav.find('a[href="#'+sectionID+'"]').parent().addClass('current');
								
							// Position nav in page depending on 'current' list
								
								$('.header nav').attr('class', sectionID);
							
						}
						
					
				});
				
			// Assign localscroll plugin to global navigation links
			
				$('.header nav li').localScroll({
					hash:true,
					duration:500,
					easing:'swing'
				});
				
		},
		
		socialStatus : function () { // Construct HTML and run AJAX calls to social networks
			
			// Set up holder HTML
			
				$('#work-nav .work-item-content').append('<ul id="social-status"></ul>');
				$('#social-status').append('<li id="tweet-feed"></li>').append('<li id="facebook-feed"></li>').append('<li id="news-blog-feed"></li>').append('<li id="blog-feed"></li>');
			
			// Get latest Tweets
				
				$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=Gravitythinking&trim_user=1&count=1&include_rts=1&callback=?', function(data) {
					Gravity.desktop.displayTwitterFeed(data);
				});
				
			// Get latest facebook status
				
				$.getJSON('https://graph.facebook.com/gravitymarketing/feed?access_token=220527441328495%7C6e5c64d922ec3dce7d24e1d9.1-736690234%7C1T95tMdnEgFnqR6FeN9Qsn0SDY4&limit=1&callback=?', function(data) {
					Gravity.desktop.displayFacebookFeed(data);
				});
				
			// Get latest opinion blog links
				
				$.getJSON('http://gravitythinking.blogspot.com/feeds/posts/default?alt=json&max-results=1&callback=?', function(data) {
					Gravity.desktop.displayBlogFeed(data)
				});
				
			// Get latest news blog links

				$.getJSON('http://gravitythinkingnews.blogspot.com/feeds/posts/default?alt=json&max-results=1&callback=?', function(data) {
					Gravity.desktop.displayNewsBlogFeed(data)
				});
				
			/* Methods */
				
				String.prototype.parseURL = function () {
					
					/* 
						return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function (url) {
							var constructedLink = url.link(url);	
							constructedLink = $(constructedLink).attr('target','_blank');
							console.log(constructedLink);
							return constructedLink;
						});
					*/
					return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function (url) {
						return url.link(url);;
					});
					
				},
				
				String.prototype.parseUsername = function () {

					return this.replace(/[@]+[A-Za-z0-9-_]+/g, function (u) {
						var username = u.replace("@", "")
						return u.link("http://twitter.com/" + username);
					});

				},

				String.prototype.parseHashtag = function () {

					return this.replace(/[#]+[A-Za-z0-9-_]+/g, function (t) {
						var tag = t.replace("#", "%23")
						return t.link("http://search.twitter.com/search?q=" + tag);
					});

				},

				String.prototype.format = function () {

					var s = this,
				        i = arguments.length;
					while (i--) {
						s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
					}
					return s;
				}
			
		},
		
		displayTwitterFeed : function (result) {
			
			// Construct HTML
							
				$('#tweet-feed').prepend('<h2><a href="http://twitter.com/GravityThinking">FOLLOW US ON TWITTER</a></h2>');
			
			// Tweet template
			
				var outputTemplate = "<p>{0}<br /> <small><a target=\"_blank\" href=\"{1}\">{2} via {3}</a></small></p>";
			
			// Parse each tweet into HTML
			
				$.each(result, function (i, item) {
					//var tweet = item.text.parseURL().parseUsername().parseHashtag();
					var tweet = item.text;
					var createdAt = $.timeago(item.created_at);
					//var createdAt = $.browser.msie ? item.created_at : $.timeago(dateFormat(item.created_at, "isoUtcDateTime"));
					var source = item.source;
					var tweetURL = "http://twitter.com/GravityThinking/status/" + item.id_str;
					$('#tweet-feed').append(outputTemplate.format(tweet, tweetURL, createdAt, source));
				});
			
		},
		
		displayFacebookFeed : function (result) {
	
			// Construct HTML 
							
				$('#facebook-feed').prepend('<h2><a href="http://www.facebook.com/gravitymarketing">LIKE US ON FACBOOK</a></h2>');
			
			// Status template
			
				var outputTemplate = "<p>{0}<br /> <small><a target=\"_blank\" href=\"{1}\">{2}</a></small></p>";
				
			// Parse each status into HTML
			
				$.each(result.data, function (i, item) {
					
					var username = item.from.name;
					
					var pageURL = "http://www.facebook.com/" + item.from.name.replace(/ /g, '');
					var date = $.timeago(item.created_time);
					//var date = $.browser.msie ? item.created_time : $.timeago(dateFormat(item.created_time));
					
					var body = item.message;
					if (!body) {
						body = "<a href='" + item.link + "'>" + item.name + "</a><br/>" + item.description;
					}
					$("#facebook-feed").append(outputTemplate.format(body, pageURL, date));
				});
			
		},
		
		displayBlogFeed : function (result) {
				
			// Construct HTML
								
				$('#blog-feed').prepend('<h2><a href="http://gravitythinking.blogspot.com">READ OUR BLOG</a></h2>');
			
			// Status template
				
				var outputTemplate = "<h3><a target=\"_blank\" href=\"{0}\">{1}</a></h3><p>{2}<br /><small><a target=\"_blank\" href=\"http://gravitythinking.blogspot.com\">{3}</a></small></p>";
				var feed = result.feed;
				var entries = feed.entry || [];
								
			// Parse latest post into HTML
				
				$.each(entries, function (i, item) {
					var link = item.link[2].href;
					var title = item.title.$t;
					var content = $(item.content.$t).text().substr(0,100) + "...";
					var published = $.timeago(dateFormat(item.published.$t, "isoUtcDateTime"));	
					$("#blog-feed").append(outputTemplate.format(link, title, content, published));
				});
				
		},
		
		displayNewsBlogFeed : function (result) {
				
			// Construct HTML
							
				$('#news-blog-feed').prepend('<h2><a href="http://gravitythinkingnews.blogspot.com">SEE LATEST NEWS</a></h2>');
			
			// Status template
				
				var outputTemplate = "<h3><a target=\"_blank\" href=\"{0}\">{1}</a></h3><p>{2}<br /><small><a target=\"_blank\" href=\"http://gravitythinkingnews.blogspot.com\">{3}</a></small></p>";
				var feed = result.feed;
				var entries = feed.entry || [];
				
			// Parse latest post into HTML
				
				$.each(entries, function (i, item) {
					var link = item.link[4].href;
					var title = item.title.$t;
					var content = $(item.content.$t).text().substr(0,100) + "...";
					var published = $.timeago(dateFormat(item.published.$t, "isoUtcDateTime"));
					$("#news-blog-feed").append(outputTemplate.format(link, title, content, published));
				});
				
		},
		
		workNav : function() { // Set up Work Navigation
			
			// Set Work Navigation to active content
			
				$('#work > header').addClass('active');
				
			// Event: Project rolled over on home page
			
				Gravity.desktop.workNavRollovers();
				
			// Event: Project clicked on home pane
			
				Gravity.desktop.workNavClick();
			
		},
		
		workNavRollovers : function() {
			
				$('#work header a').hover(function(){
					
					$(this).find('div').fadeIn(300);
				
				}, function() {
					
					$(this).find('div').fadeOut(300);
				
				});
		},
		
		workNavClick : function() {
			
			$('#work > header a').click(function(e){
				
				// Prevent normal click behaviour

					e.preventDefault();
					
				// Get article id from link href to pass to next function
					
					var workItemID 	= $(this).attr('href');
				
				// Disable rollovers / clicks on workNav items to avoid confusion during animation
					
					$('#work > header a').unbind('mouseenter').unbind('click');
					
				// Swoosh!
				
					Gravity.desktop.swooshLeft(workItemID);
					
			});
			
		},
		
		homeClick : function() {
			
			$('#logo a').click(function(e){
				
				// Prevent normal click behaviour
				
					e.preventDefault();
				
				// Return to work nav pane if its not currently active
				
					if (!($('#work-nav').hasClass('active'))) {

						// Disable rollovers / clicks on workNav items to avoid confusion during animation
				
							$('.project-nav li').unbind('click');
					
						// Swoosh depending on link clicked
					
							Gravity.desktop.swooshRight('#work-nav');	// Back to home pane
				
						// Clear hash
				
							window.location.hash = '';
				
					}
			});
			
		},
		
		projectNavClick : function() {
			
			$('.project-nav li').click(function(e){

				// Prevent normal click behaviour
					
					e.preventDefault();
					
				// Get article id from link href to pass to next function
				
					var workItemID 	= $(this).find('a').attr('href');
					
				// Disable rollovers / clicks on workNav items to avoid confusion during animation
				
					$('.project-nav li').unbind('click');
					
				// Swoosh depending on link clicked
					
					if($(this).hasClass('back')) {
						
						Gravity.desktop.swooshRight(workItemID);	// Back to home pane
												
					} else {
						
						Gravity.desktop.swooshLeft(workItemID); // Next one
												
					}
			})
			
		},
		
		swooshLeft : function(workItemID) { // swoosh Work content left
				
			// Cache selectors
			
				var $swooshOutItems = $('#work .active .work-item-images li');
				
			// Count number of items to animate
			
				var counter = $swooshOutItems.length;
				
			// Remove current item
				
				$swooshOutItems.each(function(i){
					
					// Animate each nav item off the left of viewport	
					
						$(this).stop().delay(120 * i).animate({
							
							left : ['-5000px', 'swing']
							
						}, 750, function(){
							
							// Bring in new item on animation completion
							
								if (!--counter) {
									
									// Cache selectors
									
										var $swooshInItems = $(workItemID).find('.work-item-images li')
									
									// Set new active item
									
										$('#work .active').removeClass('active');
										
										$(workItemID).addClass('active');
									
									// Count images to allow for delay of content fadeIn
									
										var counter = $swooshInItems.length;
										
									// Animate work article content into viewport
									
										$swooshInItems.each(function(i){
											
											// Animate each project image into viewport
											
												$(this).stop().delay(120 * i).animate({
													
													left : ['0', 'swing']
													
												}, 750, function() {
													
													if (!--counter) $('.active .work-item-content').fadeIn('fast');
													
												});
												
										});
										
									
								}
	
						});
						
				});	
				
			// Fade out non-nav content
				
				$('.active .work-item-content').fadeOut('fast');
			
			// Re-enable navigation
			
				Gravity.desktop.projectNavClick();
			
		},
		
		swooshRight : function(workItemID) { // swoosh Work content right
			
			jQuery.fn.reverse = function() {
			    return this.pushStack(this.get().reverse(), arguments);
			};
			
			// Cache selectors
			
				var $swooshOutItems = $('#work .active .work-item-images li');
				var $swooshInItems = $(workItemID).find('.work-item-images li');
				
			// Count number of items to animate and set delay value
			
				var counter = $swooshOutItems.length;
				var delay = 120 * counter;
				
			// Remove current item
				
				$swooshOutItems.reverse().each(function(i){

					// Animate each nav item off the left of viewport	
					
						$(this).stop().delay(delay / i).animate({
							
							left : ['+5000px', 'swing']
							
						}, 750, function(){
								
								counter = counter--;
								
							// Bring in new item on animation completion
							
								if (!--counter) {
												
									// Set new active item
									
										$('#work .active').removeClass('active');
										
										$(workItemID).addClass('active');
									
									// Count number of items to animate and set delay value
									
										var counter = $swooshOutItems.length;
										var delay = 120 * counter;
										
									// Animate work article content into viewport
									
										$swooshInItems.reverse().each(function(i){
												
											// Animate each project image into viewport
											
												$(this).stop().delay(delay / i).animate({
													
													left : ['0', 'swing']
													
												}, 750, function() {
		
													
													if (!--counter) $('.active .work-item-content').fadeIn('fast');
													
												});
												
										});
									
								}
	
						});
						
				});	
				
			// Fade out non-nav content
				
				$('.active .work-item-content').fadeOut('fast');
			
			// Re-emable rollovers

				Gravity.desktop.workNavRollovers();

			// Re-enable navigation

				Gravity.desktop.workNavClick();

		},
		
		aboutNav : function () {
			
			// Inject navigation
			
				$('#insights > div').append('<div id="clients-link">View our clients</div>');
				
				$('#clients > div').append('<div id="insights-link">Back to Insights</div>');
				
			// Count number of items to animate

				
			
			// Transition to clients panel
			
				$('#clients-link').click(function() {
					
					Gravity.desktop.swooshAboutLeft($(this));
					
				});
				
				$('#insights-link').click(function() {
					
					Gravity.desktop.swooshAboutRight($(this));
					
				});
			
		},
		
		swooshAboutLeft : function($this) {
			
			var counter = $('#insights section').length;
			
			$this.fadeOut('fast', function(){
				
				$('#insights section').each(function(i){

					// Animate each nav item off the left of viewport	

						$(this).stop().delay(120 * i).animate({

							left : ['-5000px', 'swing']

						}, 750, function(){

							// Bring in new item on animation completion

								if (!--counter) {

									// Cache selectors

										var $swooshInItems = $('#clients section');

									// Count images to allow for delay of content fadeIn

										var counter = $swooshInItems.length;

									// Animate work article content into viewport

										$swooshInItems.each(function(i){

											// Animate each project image into viewport

												$(this).stop().delay(120 * i).animate({

													left : ['0', 'swing']

												}, 750, function() {

													if (!--counter) $('#insights-link').fadeIn('fast');

												});

										});


								}
								
						});
				
				});
			
			});
			
		},
		
		swooshAboutRight : function($this) {
			
			jQuery.fn.reverse = function() {
			    return this.pushStack(this.get().reverse(), arguments);
			};
			
			var counter = $('#clients section').length;
			var delay = 120 * counter;
			
			$this.fadeOut('fast', function(){
				
				$('#clients section').reverse().each(function(i){

					// Animate each nav item off the left of viewport	
						
						$(this).stop().delay(delay / i).animate({
							
							left : ['+5000px', 'swing']

						}, 750, function(){
							
								counter = counter--;
							
							// Bring in new item on animation completion
						
								if (!--counter) {
								
									// Count number of items to animate and set delay value
								
										var counter = $('#insights section').length;
										var delay = 120 * counter;
									
									// Animate work article content into viewport
								
										$('#insights section').reverse().each(function(i){
											
											// Animate each project image into viewport
										
												$(this).stop().delay(delay / i).animate({
												
													left : ['0', 'swing']
												
												}, 750, function() {
	
												
													if (!--counter) $('#clients-link').fadeIn('fast');
												
												});
											
										});
								
								}
						});
			
				});
			});
		},

		peopleInfo : function() {
			
			$('#people .photo img').hover(function(){ 
				
				// Reset other items
					
					$('#people .photo img').removeClass('photo-on');
					$('#people .profile').removeClass('profile-on');
					
				// Change the img state
				
					$(this).toggleClass('photo-on');
					$(this).parent().parent().find('.profile').toggleClass('profile-on');
				
			})	
			
		},
		
		footerDrawer : function() {
			
			// Use fixed position drawer for all but iOS devices
			
				var deviceAgent = navigator.userAgent.toLowerCase();
				var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
			
				if (!(agentID)) {

					// Inject button HTML

						$('#contact').prepend('<div id="button-holder">');
						
						$('#contact > div:first-child').prepend('<div id="contact-button">');
						
					// Event: Click button

						$('#contact').hover(function(){

							// Animate button and drawer
							if ($('#contact').hasClass('open')) {

								// Close drawer

									$('#contact').animate({
										bottom:['-130px', 'swing']
									},250, function() {
										$(this).removeClass('open');
									});

									$('#button-holder div').animate({
										bottom:['0px', 'swing']
									},250, function() {
										$(this).removeClass('open')
									});


							} else {

								// Open drawer

									$('#contact').animate({
										bottom:['0px', 'swing']
									},250, function() {
										$(this).addClass('open');
									});

									$('#button-holder div').animate({
										bottom:['130px', 'swing']
									},250, function() {
										$(this).addClass('open')
									});

							}	

						});
				
				}
			
		}
		
	};

// Initialise and go! :)

	Gravity.desktop.init();

