// General v1.0
// Andrew Pettican (June 2011)
//
// Changelog:
// v1.0 - 13/06/2011 - Initial build
//////////////////////////////////////////////////////////////////

// ---------------------------------------------------------------
// Parameters
// ---------------------------------------------------------------

// ---------------------------------------------------------------
// Parameters End
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// Global Vars, Do not change anything below this line!
// ---------------------------------------------------------------

var gs_mouseX = 0;	// The current mouse position (x-coordinate)
var gs_mouseY = 0;	// The current mouse position (y-coordinate)
var gs_scrollX = 0;	// The last scroll position when the mouse was moved (x-coordinate)
var gs_scrollY = 0;	// The last scroll position when the mouse was moved (y-coordinate)

// ---------------------------------------------------------------
// Global Vars End, Do not change anything above this line!
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// Functions Start
// ---------------------------------------------------------------

/**
 * Toggles the suffix on the given filename.
 * If the suffix is found, it will be removed, if it is not found
 * it will be added.
 */
function toggle_filename_suffix(source, suffix)
{
	// Find where the file extension index
	var file_extension_index = source.lastIndexOf('.');
	if(file_extension_index > 0)
	{
		// Determine the filename and extension of the current src
		var filename = source.substr(0, file_extension_index);
		var file_extension = source.substr(file_extension_index);
		
		// Do the last 3 chars of the filename == suffix?
		if(filename.length > suffix.length && filename.substr(filename.length-3) === suffix)
		{
			// Remove suffix
			filename = filename.substr(0, filename.length-suffix.length);
		}
		else
		{
			// Add suffix
			filename += suffix;
		}
		
		source = filename + file_extension;
	}
	
	return source;
}


/**
 * Determines if the specified subnav should remain active based on the current mouse position
 * mouseX			- Current mouse x-coordinate
 * mouseY			- Current mouse y-coordinate
 * node				- The node to test against
 * outerDimensions	- Should outer dimensions be calculated (i.e. include the node's padding/border)
 * margin			- If outer dimensions are used, should the margin also be included?
 */
function is_mouseover(mouseX, mouseY, $node, outerDimensions, margin)
{
	// outerDimensions/margin default to true
	outerDimensions = (typeof(outerDimensions) === "boolean" ? outerDimensions : true);
	margin = (typeof(outerDimensions) === "boolean" ? margin : true);
	
	var answer = false;
	if($node !== null && $node.length === 1)
	{
		// Calculate the boundaries that the mouse must stay within.
		var nodeTopCoord = $node.offset().top;
		var nodeLeftCoord = $node.offset().left;
		var nodeBottomCoord = nodeTopCoord + (outerDimensions ? $node.outerHeight(margin) : $node.height());
		var nodeRightCoord = nodeLeftCoord + (outerDimensions ? $node.outerWidth(margin) : $node.width());
		
		// Is the mouse within these bounds?
		answer = (mouseY >= nodeTopCoord && mouseX >= nodeLeftCoord && mouseY <= nodeBottomCoord && mouseX <= nodeRightCoord);
		//alert("("+mouseX +"x"+ mouseY+")" + nodeTopCoord + ", " + nodeRightCoord + ", " + nodeBottomCoord + ", " + nodeLeftCoord + " = " + answer);
	}
	
	return answer;
}


/**
 * Function that preloads a defined list of images (arguments for the function).
 * Thanks: http://ppolyzos.com/2010/05/preload-images-with-jquery/
 */
jQuery.preloadImages = function()
{  
  //Loop through the images
  for(var i = 0; i<arguments.length; i++)
  {
  	jQuery("<img>").attr("src", arguments[i]);
  }
}
 
// ---------------------------------------------------------------
// Functions End
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// JS Events
// ---------------------------------------------------------------

$(document).ready(function()
{
	// Preload certain images
	// Thanks: http://ppolyzos.com/2010/05/preload-images-with-jquery/
	//////////////////////////////////////////////////////////////
	/*
	$.preloadImages(
		"assets/images/layout/cbox_bg.png", 
		"assets/images/layout/cbox_loading.gif", 
		"assets/images/layout/cbox_loading_bg.png", 
		"assets/images/layout/nav_item_bg_l_active.png", 
		"assets/images/layout/nav_item_bg_r_active.png", 
		"assets/images/layout/popup_nav-hover.gif", 
		"assets/images/layout/table_arrow_hl.gif", 
		"assets/images/layout/table_arrow_hl-asc.gif", 
		"assets/images/layout/table_arrow_hl-desc.gif"
	);
	*/
	
	
	// Keep track of the mouse position
	//////////////////////////////////////////////////////////////
	$(document).mousemove(function(event) {
		gs_mouseX = event.pageX;
		gs_mouseY = event.pageY;
		gs_scrollX = $(window).scrollLeft();
		gs_scrollY = $(window).scrollTop();
//		$('#mouse').html(gs_mouseX+"x"+gs_mouseY+" . "+gs_scrollX+"x"+gs_scrollY);
	});
	
	
	// Blur all anchors
	//////////////////////////////////////////////////////////////
	/*
	$("a").bind("focus click", function(e)
	{
		this.blur();
	});
	*/
	
	
	// Create a popup window
	//////////////////////////////////////////////////////////////
	$('a[data-link-mode^="popup"]').each(function()
	{
		// Update titles
		var old_title = $(this).attr("title");
		old_title = typeof(old_title) == "undefined" ? "" : old_title;
		if(old_title !== "")
		{
			$(this).attr("title", old_title+" [Opens in new window]");
		}
		else
		{
			$(this).attr("title", "[Opens in new window]");
		}
		
		// Perform the popup when clicked
		$(this).bind("click", function()
		{
			// Default window attributes
			// See http://www.javascript-coder.com/window-popup/javascript-window-open.phtml for a full list of attributes
			var window_width = 400;
			var window_height = 400;
			var window_resizable = 0;
			var window_status = 1;
			var scrollbars_status = 0;
			var toolbar_status = 0;
			var location_status = 0;
			var menubar_status = 0;
			var directories_status = 0;
			var d = new Date();
			var window_name = 'popup_'+d.getTime();
			
			// Determine window attributes
			// These should be attached to the "rel" attribute of the <a> tag in the format:
			// width=300; height=300; status=1; resizable=0; name=blahblah
			var window_attributes = $(this).attr("data-link-mode").split(";");
			var i=0;
			for(i=0; i<window_attributes.length; i++)
			{
				if(window_attributes.hasOwnProperty(i))
				{
					var attrib_parts = window_attributes[i].split("=", 2);
					if(attrib_parts.length === 2)
					{
						// Determine what the value of this attribute is.
						// NB: attributes should always be an integer
						var attribute_key = jQuery.trim(attrib_parts[0]);
						var attribute_value_str = jQuery.trim(attrib_parts[1]);
						var attribute_value = parseInt(attribute_value_str, 10);
						if(!isNaN(attribute_value))
						{
							if(attribute_key === "width" && attribute_value >= 100)
							{
								window_width = attribute_value;
							}
							else if(attribute_key === "height" && attribute_value >= 100)
							{
								window_height = attribute_value;
							}
							else if(attribute_key === "resizable" && attribute_value >= 0)
							{
								window_resizable = attribute_value;
							}
							else if(attribute_key === "status" && attribute_value >= 0)
							{
								window_status = attribute_value;
							}
							else if(attribute_key === "scrollbars" && attribute_value >= 0)
							{
								scrollbars_status = attribute_value;
							}
							else if(attribute_key === "toolbar" && attribute_value >= 0)
							{
								toolbar_status = attribute_value;
							}
							else if(attribute_key === "location" && attribute_value >= 0)
							{
								location_status = attribute_value;
							}
							else if(attribute_key === "menubar" && attribute_value >= 0)
							{
								menubar_status = attribute_value;
							}
							else if(attribute_key === "directories" && attribute_value >= 0)
							{
								directories_status = attribute_value;
							}
						}
						
						// For handling string attributes
						if(attribute_key === "name" && attribute_value_str !== "")
						{
							window_name = attribute_value_str;
						}
					}
				}
			}
			
			var output_attributes = "width="+window_width+", height="+window_height+", resizable="+window_resizable+", status="+window_status+", scrollbars="+scrollbars_status+", toolbar="+toolbar_status+", location="+location+", menubar="+menubar_status+", directories="+directories_status;
			//alert(output_attributes +'\n'+ window_name);
			
			window.open(this.href,window_name,output_attributes);
			return false;
		});
	});
	
	
	// Load the page in a new window
	//////////////////////////////////////////////////////////////
	$('a[rel=external], a.external_link').each(function()
	{
		// Set target and update titles
		$(this).attr("target", "_blank");
		var old_title = $(this).attr("title");
		if(old_title !== "")
		{
			$(this).attr("title", old_title+" [Opens in new window]");
		}
		else
		{
			$(this).attr("title", "[Opens in new window]");
		}
	});
	
	
	// Toggle the src attribute on certain objects to add/remove '_hl'
	//////////////////////////////////////////////////////////////
	$('.toggle_hl').hover(
		function()
		{
			$(this).attr('src', toggle_filename_suffix($(this).attr('src'), '_hl'));
		},
		function()
		{
			$(this).attr('src', toggle_filename_suffix($(this).attr('src'), '_hl'));
		}
	);
	
	
	// topnav support
	//////////////////////////////////////////////////////////////
	// A tiny delay to apply before checking the mouse position. This is necessary because mouseout events will fire exactly on the point that the mouse leaves, even if it is still over the target)
	var gs_topnav_mouse_delay = 100;
	
	// The delay to apply before deactivating a navigation item, if the mouse re-enters the navigation within this period the deactivation will be cancelled
	var gs_topnav_close_delay = 500;
	var gs_topnav_close_timer = null;
	
	// Touch support?
	if(Modernizr.touch)
	{
		// Touch device, enable first items under each subnav
		$('ul#topnav_list li.first').css('display', 'block');
		
		// Detect clicks on <a>'s within the root nav <li>'s
		// NB: these will never follow their href
		$('ul#topnav_list > li > a').click(function()
		{
			// Find the parent li at the root of the list
			var $parent_li_root = $(this).parents('li:last');
			
			// Should we activate or deactivate it?
			if($parent_li_root.hasClass('active'))
			{
				// Set this parent li as active
				$parent_li_root.removeClass('active');
			}
			else
			{
				// Clear all active elements
				$('ul#topnav_list > li.active').removeClass('active');
				
				// Set this parent li as active
				$parent_li_root.addClass('active');
			}
			return false;
		});
	}
	else
	{
		// Standard browser
		
		// Detect hovers on <a>'s within the nav <li>'s
		$('ul#topnav_list li a').hover(
			function()
			{
				// Cancel nav timer
				if(gs_topnav_close_timer !== null)
				{
					//$('#debug').html($('#debug').html()+'<br />close timer cleared!');
					clearTimeout(gs_topnav_close_timer);
					gs_topnav_close_timer = null;
				}
				
				// Find the parent li at the root of the list
				var $parent_li_root = $(this).parents('li:last');
				
				// Clear all active elements
				$('ul#topnav_list > li.active').removeClass('active');
				
				// Set this parent li as active
				$parent_li_root.addClass('active');
			},
			function()
			{
				// Find the parent li and its child ul at the root of the list
				var $parent_li_root = $(this).parents('li:last');
				var $parent_li_children = $parent_li_root.find('ul:first');
				
				// Set this parent li as inactive (only if the mouse has left it and its children completely)
				if($parent_li_children.length === 1)
				{
					setTimeout(function()
					{
						if(!is_mouseover(gs_mouseX, gs_mouseY, $parent_li_root) && !is_mouseover(gs_mouseX, gs_mouseY, $parent_li_children))
						{
							//$('#debug').html($('#debug').html()+'<br />close timer activated');
							if(gs_topnav_close_timer !== null)
							{
								clearTimeout(gs_topnav_close_timer);
							}
							gs_topnav_close_timer = setTimeout(function()
							{
								$parent_li_root.removeClass('active');
								gs_topnav_close_timer = null;
							}, gs_topnav_close_delay);
						}
						else
						{
							//$('#debug').html($('#debug').html()+'<br />close not allowed - '+is_mouseover(gs_mouseX, gs_mouseY, $parent_li_root)+', '+is_mouseover(gs_mouseX, gs_mouseY, $parent_li_children));
						}
					}, gs_topnav_mouse_delay);
				}
			}
		);
	}
});

// ---------------------------------------------------------------
// JS Events End
// ---------------------------------------------------------------
