// General v1.0
// Andrew Pettican (November 2010)
//
// Changelog:
// v1.0 - 12/11/2010 - Initial build
//////////////////////////////////////////////////////////////////

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

var gs_porfolio_grid_col_dir = "assets/filemanager/portfolio/logos_grid/colour/";
var gs_porfolio_grid_gry_dir = "assets/filemanager/portfolio/logos_grid/grey/";

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



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

$(document).ready(function()
{
	// For msDropdown (aka dd)
	// See: http://www.marghoobsuleman.com/jquery-image-dropdown
	//////////////////////////////////////////////////////////////
	$('.masthead_controls form.frm_masthead select').msDropDown({iWidthOverride:108});
	$('.masthead_controls_fr form.frm_masthead select').msDropDown({iWidthOverride:153});
	$('form.frm_side_nav select').msDropDown({iWidthOverride:140});
	$('select#frm_register_prefix').msDropDown({iWidthOverride:126});
	$('select#frm_register_enquiry_origin').msDropDown({iWidthOverride:126});
	
	
	// For language change redirect
	//////////////////////////////////////////////////////////////
	$('form#frm_masthead select#frm_masthead_language').change(function()
	{
		// Double check that the form actually changed
		// This shouldn't be necessary and may be caused because of msDropdown
		var frm_masthead_debug = "";
		var form_changed = false;
		var $select_orig_input = $('form#frm_masthead input#frm_masthead_language_original');
		if($select_orig_input.length > 0)
		{
			frm_masthead_debug += "'" + $(this).val() + "' : '" + $select_orig_input.val() + "'\n";
			form_changed = ($select_orig_input.val() != $(this).val())
		}
		frm_masthead_debug += "form_changed? : '" + form_changed + "'\n\n\n";
		
		//alert(frm_masthead_debug);
		if(form_changed)
		{
			$('form#frm_masthead').attr("action", $(this).val()).submit();
		}
	});
	
	
	// For side nav form change
	// i.e. when sector/location options are changed on the team page
	//////////////////////////////////////////////////////////////
	$('form#frm_side_nav select').change(function()
	{
		// Double check that the form actually changed
		// This shouldn't be necessary and may be caused because of msDropdown
		var frm_side_nav_debug = "";
		var form_changed = false;
		$('form#frm_side_nav select').each(function()
		{
			var select_id = $(this).attr('id');
			var select_orig_id = select_id+"_original";
			frm_side_nav_debug += "'" + select_id + "' : '" + select_orig_id + "'\n";
			var $select_orig_input = $('form#frm_side_nav input#'+select_orig_id)
			if(select_id != "" && $select_orig_input.length > 0)
			{
				frm_side_nav_debug += "'" + $(this).val() + "' : '" + $select_orig_input.val() + "'\n";
				form_changed = form_changed || ($select_orig_input.val() != $(this).val())
			}
			frm_side_nav_debug += "form_changed? : '" + form_changed + "'\n\n\n";
		});
		
		//alert(frm_side_nav_debug);
		if(form_changed)
		{
			$('form#frm_side_nav').submit();
		}
	});
	
	
	// On search field focus
	//////////////////////////////////////////////////////////////
	$('#frm_search_field').focus(function()
	{
		// Clear the field if it has a default class
		if($(this).hasClass("default"))
		{
			$(this).removeClass("default").val("");
		}
	});
	
	
	// Toggle Portfolio grid images
	//////////////////////////////////////////////////////////////
	$('.portfolio_grid ul.portfolio_entries li a').hover(
		function()
		{
			var $portfolio_img = $(this).children('img').eq(0);
			var old_img_src = $portfolio_img.attr('src');
			var new_img_src = old_img_src.replace(gs_porfolio_grid_gry_dir, gs_porfolio_grid_col_dir);
			$portfolio_img.attr('src', new_img_src);
		},
		function()
		{
			var $portfolio_img = $(this).children('img').eq(0);
			var old_img_src = $portfolio_img.attr('src');
			var new_img_src = old_img_src.replace(gs_porfolio_grid_col_dir, gs_porfolio_grid_gry_dir);
			$portfolio_img.attr('src', new_img_src);
		}
	);
	
	
	// A bookmark/print link was clicked
	//////////////////////////////////////////////////////////////
	$('li.widget_bookmark a').click(function()
	{
		bookmark_page();
		return false;
	});
	$('li.widget_print a').click(function()
	{
		print_page();
		return false;
	});
	
	
	// Create a popup window
	//////////////////////////////////////////////////////////////
	$('a[rel=popup]').each(function()
	{
		// Update titles
		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]");
		}
		
		// Perform the popup when clicked
		$(this).bind("click", function()
		{
			// Default window attributes
			var window_width = 400;
			var window_height = 400;
			var window_resizable = 0;
			var window_status = 1;
			var scrollbars_status = 0;
			var d = new Date();
			var window_name = 'popup_'+d.getTime();
			
			// Determine window attributes
			// These should be attached to the "rev" attribute of the <a> tag in the format:
			// width=300; height=300; status=1; resizable=0; name=blahblah
			var window_attributes = $(this).attr("rev").split(";");
			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 alway 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;
							}
						}
						
						// 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+"";
			//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]");
		}
	});
	
	
	// Blur all anchors?
	//////////////////////////////////////////////////////////////
	$("#masthead h1 a").bind("focus click", function(e)
	{
		this.blur();
	});
	$("a").bind("focus click", function(e)
	{
		//this.blur();
	});
	
	
	// 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'));
		}
	);
});

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



// ---------------------------------------------------------------
// 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;
}


/**
 * Calculates the width/height of an object.
 * node			- The node to measure the width/height
 * horizontal	- Flag indicating if we should measure width or height (true = width, false = height).
 * padding		- Flag indicating if we should include any padding in the width/height
 * margin		- Flag indicating if we should include any margins in the width/height
 * borders		- Flag indicating if we should include any borders in the width/height
 * 
 * Note: By default this function will calculate the width, including all padding/margins/borders.
 */
function calc_full_width_height(node, horizontal, padding, margin, borders) {
	// horizontal defaults to true.
	if (typeof(horizontal) == "undefined") { horizontal = true; }
	
	// padding/margin/borders default to true
	if (typeof(padding) == "undefined") { padding = true; }
	if (typeof(margin) == "undefined") { margin = true; }
	if (typeof(borders) == "undefined") { borders = true; }
	
	// Are we measuring vertically (default) or horizontally
	var dimensionA = "top";
	var dimensionB = "bottom";
	if(horizontal) {
		dimensionA = "left";
		dimensionB = "right";
	}
	
	var result = 0;
	if(node !== null) {
		var dimensionA_padding = (padding) ? parseInt($(node).css("padding-" + dimensionA), 10) : 0;
		var dimensionB_padding = (padding) ? parseInt($(node).css("padding-" + dimensionB), 10) : 0;
		var dimensionA_margin = (margin) ? parseInt($(node).css("margin-" + dimensionA), 10) : 0;
		var dimensionB_margin = (margin) ? parseInt($(node).css("margin-" + dimensionB), 10) : 0;
		var dimensionA_border = (borders) ? parseInt($(node).css("border-" + dimensionA + "-width"), 10) : 0;
		var dimensionB_border = (borders) ? parseInt($(node).css("border-" + dimensionB + "-width"), 10) : 0;
		var objsize = (horizontal) ? $(node).width() : $(node).height();
		
		// Add it all up
		if(!isNaN(dimensionA_padding)) { result += dimensionA_padding; }
		if(!isNaN(dimensionB_padding)) { result += dimensionB_padding; }
		if(!isNaN(dimensionA_margin)) { result += dimensionA_margin; }
		if(!isNaN(dimensionB_margin)) { result += dimensionB_margin; }
		if(!isNaN(dimensionA_border)) { result += dimensionA_border; }
		if(!isNaN(dimensionB_border)) { result += dimensionB_border; }
		if(!isNaN(objsize)) { result += objsize; }
	}
	
	return result;
}


/**
 * Determines if the specified subnav should remain active based on the current mouse position
 * mouseX	- Current mouse x-coordinate
 * mouseY	- Current mouse y-coordinate
 * id		- The node to test against
 */
function is_mouseover(mouseX, mouseY, node, padding, margin, borders) {
	// padding/margin/borders default to true
	if (typeof(padding) == "undefined") { padding = true; }
	if (typeof(margin) == "undefined") { margin = true; }
	if (typeof(borders) == "undefined") { borders = true; }
	
	var answer = false;
	
	if(node !== null) {
		// Calculate the boundaries that the mouse must stay within.
		var nodeTopCoord = $(node).offset().top;
		var nodeLeftCoord = $(node).offset().left;
		var nodeBottomCoord = nodeTopCoord + calc_full_width_height(node, false, padding, margin, borders);
		var nodeRightCoord = nodeLeftCoord + calc_full_width_height(node, true, padding, margin, borders);
		
		// Is the mouse within these bounds?
		answer = (mouseY >= nodeTopCoord && mouseX >= nodeLeftCoord && mouseY <= nodeBottomCoord && mouseX <= nodeRightCoord);
	}
	
	return answer;
}


/**
 * Bookmarks the current page
 */
function bookmark_page()
{
	// Get page attributes
	var title = document.title; 
	var url = window.location.href;
	
	// Firefox
	if(window.sidebar) {
		window.sidebar.addPanel(title, url,'');
	}
	
	// Opera
	else if(window.opera) { 
		var a = document.createElement("A");
		a.rel = "sidebar";
		a.target = "_search";
		a.title = title;
		a.href = url;
		a.click();
	}
	
	// IE
	else if(document.all) {
		window.external.AddFavorite(url, title);
	}
	
	// Others (Chrome/Safari/etc)
	else {
		alert('This function is not supported in your web browser. Please press Ctrl-D/Command-D to bookmark this page.');
	}
}


/**
 * Prints the current page
 */
function print_page()
{
	window.print();
}

// ---------------------------------------------------------------
// Functions End
// ---------------------------------------------------------------
