/*
	All site-specific scripts.
	Note that <html> innately gets a class of "no-js".
	Modernizr adds a "js" class.
*/


$(document).ready(function () {
  	if ( !( ($.browser.msie) && ($.browser.version=='6.0')) ) { var notIe6 = true; }

  	// force vertical scroll area
  	if (notIe6) { $('html').css('overflow-y', 'scroll'); }
  	
  	// Add in loader graphic
	$('#content').prepend('<img id="loader" src="' + getThemeUrl() + 'images/loader.gif" alt="*" />');
	$('#loader').hide();
  	
  	function enhanceContent () {
  		
		// Wrap reply heading in a link and add a class for JS control
		$('#reply-title').addClass('replyClosed');
		$('#reply-title').wrap('<a id="replyLink" href="#" />');
		
		// Expand / collapse reply form
		var moreLink = $('#replyLink');
		moreLink.click(function(evt){
			evt.stopPropagation();
			evt.preventDefault();
			var trigger = this;
			$('#commentform').slideToggle(function(){
				$('#reply-title').toggleClass('replyOpen').toggleClass('replyClosed');
			});  
		});
		$("#commentform").hide();
		
		if (notIe6) {
  			// Add in all social sharing buttons with JS, after Ajax load
  			// Makes a valid page and speeds things up. Not for IE6.
  			
  			// FB like
			$('#fblike').onefblike({appID:'196068930444761'});  
			
			// Gplus1
			$('#gplus').prepend('<g:plusone size="medium"></g:plusone>');
			
			// Twitter-follow
			$('#twitterFollow').prepend('<a href="http://twitter.com/jamesguest" class="twitter-follow-button">Follow @jamesguest</a><script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>');					
		
			// Tweet this
			(function(){
				var twitterWidgets = document.createElement('script');
				twitterWidgets.type = 'text/javascript';
				twitterWidgets.async = true;
				twitterWidgets.src = 'http://platform.twitter.com/widgets.js';
				document.getElementsByTagName('head')[0].appendChild(twitterWidgets);
			})();
		}
  	}
	
	function getThemeUrl() {
		var themeUrl = $('link[rel*="stylesheet"]').attr('href');
		var themeUrl = themeUrl.substring(0, themeUrl.lastIndexOf("/")) + "/";
		return themeUrl;
	}
	
	// function to find last bit of URL from string, to use as a hash
	function findHash(href) {
	
		// Remove trailing slash if existing
		if ( href.charAt(href.length-1) == '/' ) {
			href = href.substring(0, href.length-1)
		}
		
		var homeUrl = 'http://' + window.location.hostname + '/';
		var hashPart = href.substr(homeUrl.length);
		
		// Repalce / for _ in string - slash no good for CSS class
		var hashNoSlash = hashPart.replace(/\//gi, "_");
		hashNoSlash = hashNoSlash.substring(0, hashNoSlash.length);
		return hashNoSlash;
	}
	
	// Ajax load functions for all but IE6 (too slow)
	if (notIe6) {	
	
		function LoadContent (href) {
			
			// Position and display the loader graphic
			$('#loader').css('top', ($("html, body").scrollTop() + 350));
			$('#loader').show();
			
			// Set load href and animation props for specific links
			if ( href.lastIndexOf('+prev') != -1 ) {
				// Previous work
				href = href.substring(0, href.lastIndexOf('+prev'))
				var transition = 'fade';
			} else if ( href.lastIndexOf('+next') != -1 ) {
				// Next work
				href = href.substring(0, href.lastIndexOf('+next'))
				var transition = 'fade';
			} else {
				// Other pages
				var transition = 'slideDown';
				var startMap = {'marginTop': $(window).height() + $("html, body").scrollTop() + 500};
				var endMap = {'marginTop': 0};
			}
			
			// Find content to load
			var re = /#/g;
			for ( var hashCount = 0; re.exec(href); ++hashCount );
			if (hashCount > 0) {
				// If a hash exists, lose it
				// E.g. #more- or #comment- or #comments (Perhpas use in later phase)
				var newHref = href.substring(0,href.lastIndexOf('#'));
				var toLoad = newHref + ' #contentbox > *';
			} else {
				var toLoad = href + ' #contentbox > *';
			}
			
			// Load new content
			if ( transition == 'fade' ) {
				$('#contentbox').fadeTo('fast', 0.0, function() {
					setClasses(href);
					$('#contentbox').load(toLoad, function() {
						$('#loader').hide();
						$('#contentbox').fadeTo('fast', 1.0, function() {
							setupNav();
							enhanceContent();
						});
					});
				});
			} else {
				$('#contentbox').animate(startMap, 400, 'swing', function(){ 
					setClasses(href);
					$("html, body").animate({ scrollTop: 0 }, 100);
					$('#contentbox').empty().load(toLoad, function() {
						$('#loader').hide();
						$('#contentbox').animate(endMap, 700, 'swing', function() {
							setupNav();
							enhanceContent();
						});
					});
				});
			}
				
				
		} // Load content
		
		function setClasses (href) {
			// Set body class and nav classes to match new content
			
			var hash = window.location.hash;
			$('body').removeClass('archive category-work home')
			$('#menu-global li').removeClass('current_page_item');
			$('#menu-global li').removeClass('current-menu-item');
			$('#mycategoryorder-3 li').removeClass('current-cat');
			if ( hash.indexOf('latest_category_work') > -1 ) {
				var bodyClass = 'archive category-work';
				$('#mycategoryorder-3 a.link_latest_category_work').parent('li').addClass('current-cat');
				$('#menu-global a.link_latest').parent('li').addClass('current_page_item');
				$('#menu-global a.link_latest').parent('li').addClass('current-menu-item');
			} else if ( hash.substring(0,7) == 'latest_' ){	
				var bodyClass = hash.substring(hash.length);
				$('#menu-global a.link_latest').parent('li').addClass('current_page_item');
				$('#menu-global a.link_latest').parent('li').addClass('current-menu-item');
			} else if ( (hash.indexOf('latest_tag') > -1) || (hash.indexOf('latest_cat') > -1) ) {
				var bodyClass = 'archive';
				$('#mycategoryorder-3 a.link_' + hash.substring(1, hash.length)).parent('li').addClass('current-cat');
				$('#menu-global a.link_latest').parent('li').addClass('current_page_item');
				$('#menu-global a.link_latest').parent('li').addClass('current-menu-item');
			} else if ( hash.indexOf('latest') > -1 ) {
				var bodyClass = 'blog';
				$('#menu-global a.link_latest').parent('li').addClass('current_page_item');
				$('#menu-global a.link_latest').parent('li').addClass('current-menu-item');
			} else if ( hash.indexOf('about') > -1 ) {
				var bodyClass = 'page';
				$('#menu-global a.link_about').parent('li').addClass('current_page_item');
				$('#menu-global a.link_about').parent('li').addClass('current-menu-item');
			} else if ( hash.indexOf('contact') > -1 ) {
				var bodyClass = 'page';
				$('#menu-global a.link_contact').parent('li').addClass('current_page_item');
				$('#menu-global a.link_contact').parent('li').addClass('current-menu-item');
			} else if ( (href == '/') || (hash == '') ){
				var bodyClass = 'home';
				$('#menu-global a.link_home').parent('li').addClass('current_page_item');
				$('#menu-global a.link_home').parent('li').addClass('current-menu-item');
			} 
			$('body').addClass(bodyClass)
		}
		
		function setupNav () {
			// Attach class to nav links based on href location
			$('*').find('a').each(function(i) {
				var href = $(this).attr('href');
				var homeUrl = 'http://' + window.location.hostname + '/';
				var className = $(this).attr('class');

				if ( href == homeUrl ) {
					// Home page links
					$(this).addClass('link_home');
				} else {
					// all other links
					$(this).addClass('link_' + findHash(href));
				}
			});
			
			// Remove existing click events
			$('*').find('a').unbind('click');
			
			// Change hash on click to force hashChange event
			$('*').find('a').click(function(evt){
				evt.stopPropagation();
				evt.preventDefault();
				var href = $(this).attr('href');
				
				// check URL is within site, else go there instead
				var homeUrl = 'http://' + window.location.hostname + '/';
				if ( href.substr(0,homeUrl.length) != homeUrl ) {
					window.location.href = href;
					return;
				}
				
				// Set new location/hash
				var currentHref = window.location.href;
				var path = currentHref.substring(homeUrl.length,currentHref.length);
				if ( (path.length > 0) && (path.charAt(0) != '#') ) {
					// Deep linked page, break out and set hash
					window.location.href = homeUrl + '#' + findHash(href);
				} else {
					if ( findHash(href).indexOf('latest_category_work') != -1 ) {
						if ( $(this).text().indexOf('Newer') != -1 ) {
							// newer work link
							window.location.hash = '#' + findHash(href) + '+prev';
						} else if ( $(this).text().indexOf('Older') != -1 ) {
							// older work link
							window.location.hash = '#' + findHash(href) + '+next';
						} else {
							// all other work links
							window.location.hash = '#' + findHash(href);
						}
					} else {
						// All other page links
						window.location.hash = '#' + findHash(href);
					}
				}
			});
		}	
		
		// Load the Ajax page on refresh (if there is a hash)
		function load () {
			
			// exit if no hash (entering on deep page)
			if ( window.location.href.indexOf("#") == -1 ) {
				return;
			}
			
			var hash = window.location.hash;
			
			// exit if 'contact form' ajax hash
			if ( hash == '#wpcf7-f1-p9-o1' ) {
				return;
			}
			
			// exit if hash is a WP comment marker
			if (hash.lastIndexOf('#comment-') != -1) {
				return;
			}
			
			// Derive href from hash
			var hashReplace = hash.replace(/_/gi, "/");
			hashReplace = hashReplace.substring(1, hashReplace.length);
			
			if (window.location.hash == '') {
				// No exitsing hash
				var href = '/';
			} else if (hashReplace.indexOf('#') != -1) {
				// An href with an 'on page anchor' hash
				var href = '/' + hashReplace;
			} else {
				var href = '/' + hashReplace + '/';
			}
			
			// IE6 reports double slash, fix:
			if (href == "//") {
				href = "/";
			}
			
			LoadContent(href);
		}
		
		// Load on hash change (browser back button)
		$(window).hashchange( function(){
			load ();
		})
		
	  	load ();
		setupNav();
		
	} // If !IE6
	
	enhanceContent();
});







