/*jslint devel: true, plusplus: true, white: true, maxlen: 120, maxerr: 10, indent: 4 */
/*globals document, window, jQuery, SWFAddress, setTimeout */

var TAHP = window.TAHP || { };

TAHP.AjaxLinks = (function (module) {
	"use strict";
	
	// Public
	
	module.linkClick = function(e) {
		var $href = jQuery(e.currentTarget).attr('href'),
			regex = /^(((http(s?)|mailto):\/\/)|(#))/;
			
		// If link is not external, page anchor or mailto...
		if (!regex.test($href)) {
			// ...Set SWFAddress page value to href attribute of link clicked
			SWFAddress.setValue(jQuery(this).attr('href'));
			
			// Hide mainContent area before swapping new content in
			jQuery('#mainContent').animate({ opacity: 0 }, 200, function() {
				// Make AJAX call to retrieve page contents of linked page
				jQuery.get(SWFAddress.getValue().substr(1), null, function(data) {
					// Update the current page with the new content
					module.updatePageContent(data);
				});
			});
			
			// Prevent default link behaviour
			return false;
		}
	};
	module.updatePageContent = function(data) {
		// Filter out the unnecessary markup from response XML to leave only main content
		var $newContent = jQuery(data).children('#mainContent').html(),
			pageName = SWFAddress.getValue().split('/'),
			newHeight,
			$mainContent = jQuery('#mainContent'),
			$ajaxStaging;
			
		// Stuff new content into an off-screen DOM element to calculate height
		$ajaxStaging = $mainContent.clone().attr('id', 'ajaxStaging').css('height', 'auto').insertAfter($mainContent);
		$ajaxStaging.html($newContent);
		newHeight = $ajaxStaging.css('height');
		$ajaxStaging.remove();
	
		// Swap old content for new content in mainContent div, then slide to new height and fade back in
		$mainContent.html($newContent);
		$mainContent.animate({height: newHeight}, 300, function() {
			// Set height to 'auto' just in case it miscalculated (DOM race condition)
			$(this).height('auto');
			$(this).animate({opacity: 1}, 200);
		});
				
		// Change 'selected' nav link in menu
		jQuery('#navInner a span').removeClass('selected');
		pageName = pageName[pageName.length - 1].split('.')[0];
		switch(pageName) {
			case 'index':
				jQuery('#navHome span').addClass('selected');
				break;
			case 'contact':
				jQuery('#navContact span').addClass('selected');
				break;
			default:
				jQuery('#navPortfolio span').addClass('selected');
				TAHP.PortfolioLinks.init();
				break;
		}
	};
	
	return module;
} (TAHP.AjaxLinks || {}));
