/* ########################################################################### *
/* ***** DOCUMENT INFO  ****************************************************** *
/* ########################################################################### *
 * ##### NAME:  masala_global.js
 * ##### VERSION: v1.0 (Masala Magic)
/* ########################################################################### *

/* ########################################################################### *
/* ***** INDEX *************************************************************** *
/* ########################################################################### *
/* ##### INITIALISATION
/* #####
/* ##### FUNCTIONALITY:
/* ##### Check all checkboxes
/* ##### Tooltip
/* ##### Popup window
/* ##### Modal window
/* ##### Smooth anchor scroll
/* ##### Debug
/* #####
/* ##### PRESENTATION
/* ##### Expando Collapso
/* ##### Table alternate rows
/* ##### IE6 tweaks
/* ##### PNG fix
/* ##### Iframe resize
/* ########################################################################### */

var debugOutput = false;

/* ########################################################################### *
/* ##### INITIALISATION
/* ########################################################################### */

$(document).ready(masala_init_globalFunctionality);
$(document).ready(masala_init_globalPresentation);

function masala_init_globalFunctionality()
{
	// Tabs
	masala_init_tabs();
	
	// Tooltips
	masala_tooltip();
	
	// Popup window
	masala_popup_window();
	
	// Modal window
	masala_init_modalWindow();

	// Forms
	masala_forms_checkAllCheckboxes();	

	// Forms: Select on click
	masala_init_forms_selectOnClick();
	
	// Accessibility: Font Size Buttons
	masala_accessibilityFontSize();	
	
	// Enable smooth anchor scrolling
	masala_init_anchorSmoothScroll();
	
	// Support insert target="_blank" on class="externalLink" anchors
	masala_init_externalLinkTarget();
}

function masala_init_globalPresentation()
{
	// Expando Collapso
	masala_init_expandoCollapso();

	// Homepage Random Images
	masala_randomImage();	
	
	// Table alternate rows & highlight rows
	masala_init_tableRows();

	// Internet Explorer specific tweaks
	masala_ieTweaks();
	
	// PNG fix
	masala_pngfix();
	
	// Buttons
	masala_forms_buttons();
	
}





/* ########################################################################### *
/* ##### FUNCTIONALITY
/* ########################################################################### */


/* ##### FORMS */

// Check all checkboxes
// Note: This only supports 1 check all button.
// DESC: Mark all checkable checkboxes with class .masala_forms_checkableWithAll, mark the 'click to check all' checkbox with .masala_forms_checkAllCheckboxes
function masala_forms_checkAllCheckboxes()
{
	$('.masala_forms_checkAllCheckboxes').click(function()
	{
		var checkedStatus = this.checked;
		$('.masala_forms_checkableWithAll').each(function()
		{
			this.checked = checkedStatus;
		});
	});
}


// Select contents of input on click
function masala_init_forms_selectOnClick()
{
	if ($(".masala_forms_selectOnClick").length > 0)
	{
		// When the element has focus, set its value to the following
		var SEARCH_TEXT_ON = "";	
		
		// Setup the value of the element to it's title attribute
		$(".masala_forms_selectOnClick").each(function() 
			{
				$(this).val($(this).attr("title"));
			});
		
		// Handle this element's focus event
		$(".masala_forms_selectOnClick").focus(function()
		{
			// Get the value from the elements title
			var searchTextOff = $(this).attr("title");
			
			// If the current value of the element is the same as the title attribute then set it to the ON value.
			if ($(this).val() == searchTextOff)
			{
				$(this).val(SEARCH_TEXT_ON);
			}
		});
		
		// Handle this element's blur event
		$(".masala_forms_selectOnClick").blur(function()
		{
			// Get the value from the elements title
			var searchTextOff = $(this).attr("title");
			
			// If the value of the element is empty set it to the default value (taken from the element title)
			if ($(this).val() == "")
			{
				$(this).val(searchTextOff); 
			}
		});	
	}
}


/* Form buttons (including rounded buttons with background image) */

function masala_forms_buttons()
{
	// If browser is not IE6 (or less)
	if ($.browser.msie == false || ($.browser.msie && $.browser.version > 6)) 
	{
		// Get the buttons that should be effected
		var nodes = $("button.button,a.button");
		for (var i = 0; i < nodes.length; i++)
		{
			// If this is a primary action button
			if ($(nodes[i]).hasClass("primary"))
			{
				$(nodes[i]).addClass("button_curve_primary");
				$(nodes[i]).after("<div class='buttonEnd_primary'></div>");
				$(nodes[i]).hover(buttonHoverOver_primary, buttonHoverOut_primary);
			} else {
				$(nodes[i]).addClass("button_curve"); 
				$(nodes[i]).after("<div class='buttonEnd'></div>");         
				$(nodes[i]).hover(buttonHoverOver, buttonHoverOut);
			}
		}
	}
}
 
function buttonHoverOver()
{
	$(this).addClass("button_hover");
	$(this).next("div").addClass("buttonEnd_hover");
}
 
function buttonHoverOut()
{
	$(this).removeClass("button_hover");
	$(this).next("div").removeClass("buttonEnd_hover");
}
 
function buttonHoverOver_primary()
{
	$(this).addClass("button_primary_hover");
	$(this).next("div").addClass("buttonEnd_primary_hover");
}
 
function buttonHoverOut_primary()
{
	$(this).removeClass("button_primary_hover");
	$(this).next("div").removeClass("buttonEnd_primary_hover");
}



/* ########################################################################### *
/* ##### TOOLTIPS
/* ########################################################################### */

function masala_tooltip()
{
	$('.link_info').tooltip({
		track: true,
		delay: 0,
		showURL: false,
		fixPNG: true,
		//showBody: " - ",
		extraClass: "pretty",
		top: -24,
		left: 6
	});
}


/* ########################################################################### *
/* ##### TABS
/* ########################################################################### */

function masala_init_tabs()
{
	if ($('.masala_tabs').length > 0) 
	{		
		// Initialise the tabs
		$('.masala_tabs').tabs();
		
		// Check if there is an active tab, and select it
		$('.masala_tabs > div').each(function() 
			{
				if ($(this).hasClass("active"))
				{
					$('.masala_tabs > ul').tabs('select', '#' + $(this).attr("id"));
				}
			});
	}
}


/* ########################################################################### *
/* ##### POPUP WINDOW
/* ########################################################################### */

function masala_popup_window() 
{
	$('.popUp').click(function (e) {
		e.preventDefault();
		var targetHref = $(this).attr('href');
		window.open(targetHref,"_blank","height=640,width=700,toolbar=no,menubar=no,location=no,scrollbars=yes,status=no");
		// Return false to prevent the link click navigation occuring.
		return false;
	});
}



/* ########################################################################### *
/* ##### MODAL WINDOWS
/* ########################################################################### */

// Generic modal window
function masala_init_modalWindow()
{
	var modalHtml = '<div><a href="#" title="Close" class="modalCloseX modalClose"><span class="icon"></span></a><div class="content"><h1 class="title">test</h1></div></div>';
	
	$('.masala_modalWindow').click(function (e) 
	{
		e.preventDefault();

		$('modalHtml').modal({
				overlayId: 'modalOverlay',
				containerId: 'modalContainer',
				onOpen: modal.open,
				onShow: modal.show,
				onClose: modal.close
		});

	});
	
}

var modal = {
	message: null,
	open: function (dialog) {
		dialog.overlay.show(1, function () {
			dialog.container.fadeIn(500, function () {
				dialog.data.fadeIn(500, function () {
				});
			});
		});
	},
	show: function (dialog) {
	},
	close: function (dialog) {
		dialog.container.fadeOut(500, function () {
			dialog.overlay.fadeOut(500, function () {
				$.modal.close();
			});
		});
	}
};

// Modal window
function masala_launchModalWindow(title, windowWidth, callBack)
{
	
	alert("this is masala_launchModalWindow");
	var modalHtml = '<div style="display:none"><a href="#" title="Close" class="modalCloseX modalClose"><span class="icon"></span></a><div class="content form-container"><h1 class="title"></h1><div class="loading" style="display:none"></div><div class="message" style="display:none"></div><div id="contentContainer"><p><strong>Sorry, you require the <a href="http://www.adobe.com/go/getflash">Adobe Flash</a> player to view this content.</strong></p></div></div></div>';

	var modal = {
		message: null,
		open: function (dialog) {
			dialog.overlay.fadeIn(500, function () {
				
				// Set the width of the window
				$(dialog.container).width(windowWidth);

				// Set the title of the window
				$(dialog.container).find('h1.title').html(title);

				dialog.container.show();
				dialog.content.show();																	 
			
				// Execute the callBack function
				if (typeof callBack == "function")
				{
					// execute callBack function
					callBack();
				}
				$(dialog.container).find('#buttClose').focus();
				
			});
		},
		close: function (dialog) {
			$("#contentContainer").hide();
			
			dialog.content.hide();
			dialog.container.hide();
			dialog.overlay.fadeOut(500, function () 
				{
					$.modal.remove(dialog);
				});
		
		}
	};
	
	// create a modal dialog with the data
	$(modalHtml).modal({
		close: true,
		overlay: 70,
		overlayId: 'modalOverlay',
		containerId: 'modalContainer',
		iframeId: 'modalIframe',
		onOpen: modal.open,
		onClose: modal.close
	});

}

// Modal windows that get HTML page for content via Ajax
function masala_init_ajaxModalWindow(htmlUrl)
{
	$('.ajaxModalWindow').click(function (e) 
	{
		e.preventDefault();
		
		// load the page content via ajax
		$.get(htmlUrl, function(data)
		{
			// create a modal dialog with the data
			$(data).modal({
				close: true,
				overlay: 70,
				overlayId: 'modalOverlay',
				containerId: 'modalContainer',
				iframeId: 'modalIframe',
				onOpen: modal.open,
				onClose: modal.close
			});
		});
	});
	
	var modal = {
		message: null,
		open: function (dialog) {
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.content.fadeIn(200, function () {
						$('#modalContainer #buttClose').focus();
					});
				});
			});
		},
		close: function (dialog) {
			dialog.content.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.remove(dialog);
					});
				});
			});
		}
	};
}


/* ##### ACCESSIBILITY */

// Font Size Buttons
function masala_accessibilityFontSize()
{
	if ($(".fontSize").length > 0)
	{
		$(".fontSize").html('<a href="#" class="increase" alt="Increase font size" title="Increase font size"><span class="increaseIcon"></span></a><a href="#" class="decrease" alt="Decrease font size" title="Decrease font size"><span class="decreaseIcon"></span></a>');
		$(".fontSize .increase").click($.FontSizer.IncreaseSize);
		$(".fontSize .decrease").click($.FontSizer.DecreaseSize);
	
		var options = { min: 80, max: 130};
		$.FontSizer.Init(options);
	}
}



/* ##### PAGE ANCHORS SMOOTH SCROLL */

function masala_init_anchorSmoothScroll()
{
	// If this is IE6, do not smooth scroll (doesn't play nicely)
	if (!((jQuery.browser.msie) && (parseInt(jQuery.browser.version) == 6)))
	{
		var nodes = $('a[href*=#]');
		for(var i = 0; i < nodes.length; i++) 
		{
			if ($(nodes[i]).attr("href") != "#")
			{
				$(nodes[i]).click(function() 
				{
					if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
					&& location.hostname == this.hostname) {
						var $target = $(this.hash);
						$target = $target.length && $target
						|| $('[name=' + this.hash.slice(1) +']');
						if ($target.length) {
						var targetOffset = $target.offset().top;
						$('html,body')
						.animate({scrollTop: targetOffset}, 1000);
						 return false;
						}
					}
				});
			}
		}
	}
}


// Target blank new windows
function masala_init_externalLinkTarget()
{
	// Add attribute target="_blank" to all anchor elements with class="externalLink"
	$("a.externalLink").attr("target", "_blank");
}

/* ########################################################################### *
/* ##### JQUERY & OTHER UTILITIES
/* ########################################################################### */

// Supply a query string and parse it into a key value pairs

jQuery.query = function(s) 
{
		var r = {};
		if (s) {
				var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
				q = q.replace(/\&$/, ''); // remove the trailing &
				jQuery.each(q.split('&'), function() {
						var splitted = this.split('=');
						var key = splitted[0];
						var val = splitted[1];
						// convert numbers
						if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
						// convert booleans
						if (val == 'true') val = true;
						if (val == 'false') val = false;
						// ignore empty values
						if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
				});
		}
		return r;
};

function debug(message)
{
	if (debugOutput)
	{
		$("body").append("<p><strong>DEBUG OUTPUT:</strong> " + message + "</p>");
	}
}

/* ########################################################################### *
/* ##### PRESENTATION
/* ########################################################################### */


/* ##### Expando Collapso ##### */

function masala_init_expandoCollapso()
{
	// Constant vars
	var EXPANDED_CLASSNAME = "expando";
	var COLLAPSED_CLASSNAME = "collapso";
	var CLICK_ELEM = "h2";

	// Fire expand / collapse variants
	if ($(".masala_expandoCollapso_triggerWithAltAsTargetId").length > 0)
	{
		masala_expandoCollapso_triggerWithAltAsTargetId();
	}

	// Setup all expando collapsos
	$(".masala_expandoCollapso").each(function()
		{
			// Handle lists	
			if ($(this).is("ul") || $(this).is("ol"))
			{
				// Store expando collapso block
				var parentBlockElement = this;
				
				// Collapse all <li> elements
				$(this).find('li').addClass(COLLAPSED_CLASSNAME);
				
				// Check if on of the <li> elements is set to be expanded / visible
				if ($(this).find('li.' + EXPANDED_CLASSNAME).length > 0)
				{
					expandedItem = $(this).find('li.' + EXPANDED_CLASSNAME);
					$(expandedItem).removeClass(COLLAPSED_CLASSNAME);
					$(expandedItem).addClass(EXPANDED_CLASSNAME);
				}
				
				// Create links
				$(parentBlockElement).find('li.collapso').each(function()
					{
						$(this).find('.masala_expandoCollapso_trigger').each(function() 
						{
							$(this).html('<a href="#">' + $(this).html() + '<span class="icon"></span></a>');
							$(this).find("a").click(function() 
								{
									var currentListElement = $(this).parents("li:first");
									var isExpanded = false;
									
									if ($(currentListElement).hasClass(EXPANDED_CLASSNAME))
									{
										// It is currently expanded
										isExpanded = true;
									}
	
									// Collapse all
									$(parentBlockElement).find("li").removeClass(EXPANDED_CLASSNAME);
									$(parentBlockElement).find("li").addClass(COLLAPSED_CLASSNAME);		
	
									if (isExpanded)
									{
										// I expanded, therefore I collapse
										$(currentListElement).removeClass(EXPANDED_CLASSNAME);
										$(currentListElement).addClass(COLLAPSED_CLASSNAME);
									}
									else
									{
										// I collapsed, therefore I expand
										$(currentListElement).removeClass(COLLAPSED_CLASSNAME);
										$(currentListElement).addClass(EXPANDED_CLASSNAME);
									}
									
									$(this).blur();
									return false;
									
								});
						});					 
					});				
			}
		});
	
	return false;
}

function masala_expandoCollapso_triggerWithAltAsTargetId()
{
	// Setup each instance of 
	$(".masala_expandoCollapso_triggerWithAltAsTargetId").each(function()
		{
			var trigger = $(this);
			var targetID = ($(trigger).attr("alt"));
			var target = $("#" + targetID);
			debug("CALL: masala_expandoCollapso_triggerWithAltAsTargetId PURPOSE: Setup element type '" + $(this)[0].nodeName + "' as trigger for expand / collapse of element with ID '" + targetID + "'.");
			
			// Hide target and remove .hidden class
			$(target).hide().removeClass("hidden");
			
			// Add .link_collapsed to trigger
			$(trigger).addClass("link_collapsed");
			
			// Wire trigger events
			$(trigger).click(function() 
				{
					if ($(this).hasClass("link_expanded"))
					{
						// Collapse trigger & target
						$(this).removeClass("link_expanded").addClass("link_collapsed");
						$(target).fadeOut();
					}
					else
					{
						// Expand trigger & target
						$(this).removeClass("link_collapsed").addClass("link_expanded");
						$(target).fadeIn();
					}
					
					return false;
				});
		
		});
}


/* ##### PNG FIX */

function masala_pngfix()
{
	$('img[src*=png]').parent().pngFix(); 
}



/* ##### HOMEPAGE RANDOM IMAGE */

function masala_randomImage()
{
	/*
		Setup the path and number of images that you want to display below. 
		Add the integer (between and including MAX_NUM and MIN_NUM set below
		to the end of the graphic file, between the prefix and suffix path strings.
		An image will then be selected and inserted at random. This is random and
		doesn't currently support remembering history for the users browser (ie. cookies).
	*/
	var MAX_NUM = 2;
	var MIN_NUM = 1;
	var URL_PATH_PREFIX = 'media/images/img_randomPhoto_';
	var URL_PATH_SUFFIX = '.jpg';
	var IMG_WIDTH = "216";
	var IMG_HEIGHT = "209";
	var IMG_ALT = "";	
	
	if ($('#randomImage').length > 0)
	{		
		var HTML_STRING = '<img src="" width="' + IMG_WIDTH + '" height="' + IMG_HEIGHT + '" alt="' + IMG_ALT + '" />';
		var randomNumber = Math.floor(Math.random( ) * MAX_NUM - MIN_NUM + 1) + MIN_NUM;
		var randomImagePath = URL_PATH_PREFIX + randomNumber + URL_PATH_SUFFIX;
		
		$('#randomImage').html(HTML_STRING);
		$('#randomImage img').attr("src", randomImagePath);
	}
}



/* ##### TABLE ALTERNATE ROWS */

function masala_init_tableRows()
{
	$('.masala_highlightRows').children('tbody').children('tr').mouseover(function(){$(this).addClass('over');}).mouseout(function() {$(this).removeClass('over');});
	$('.masala_tableAltRows').children('tbody').children('tr:odd').removeClass('alt');
	$('.masala_tableAltRows').children('tbody').children('tr:even').addClass('alt');
	$('.masala_tableAltRows').children('tbody').children('tr').removeClass('last');
	$('.masala_tableAltRows tr:first-child').addClass('first');	
	$('.masala_tableAltRows tr:last-child').addClass('last');
}



/* ##### IE6 TWEAKS */

// Enable functionality if the user's browser is IE
function masala_ieTweaks()
{
	// If browser is IE6
	if ((jQuery.browser.msie)&&(parseInt(jQuery.browser.version)==6)) 
	{
		masala_input_padding();
		masala_lists();
	}
	
	// If browser is IE7
	if ((jQuery.browser.msie)&&(parseInt(jQuery.browser.version)==7)) 
	{
		masala_lists();
	}	
}

// Adds a class to checkbox and radio buttons if IE
function masala_input_padding()
{
	$('input[type=checkbox],input[type=radio]').addClass('nopad');
}

// Adds .first and .last classes to simulate :first :last pseudo classes on list items.
function masala_lists()
{
	$('ul li:first-child').addClass("first");
	$('ul li:last-child').addClass("last");
}




/* ##### IFRAME RESIZE */
/* 
	 NOTE: The iframeLoaded() function is called on the iframe onLoad event.
*/

function iframeLoaded()
{
	var applicationIframe = this.parent.document.getElementById("applicationIframe");
	var siteletIframe = this.parent.document.getElementById("siteletIframe");

	if (applicationIframe != null)
	{
		resizeIframe(applicationIframe);
	}
	
	if (siteletIframe != null)
	{
		resizeIframe(siteletIframe);
	}

	var IFRAME_WRAPPER_ELEMENT_ID = "contentWrapper";
	var NAV_COLUMN_ELEMENT_ID = "rightColumn";
	
	// Sets the iframe wrapper element to have a height greater than the nav column.
	var leftcol = $(NAV_COLUMN_ELEMENT_ID);
	if (leftcol != null)
	{
		var outer = $(IFRAME_WRAPPER_ELEMENT_ID);
		if (outer != null && leftcol.offsetHeight > outer.offsetHeight)
		{
			outer.style.height = leftcol.offsetHeight + 50 + "px";
		}
	}
	
	return true;
};

function resizeIframe(iframeRef)
{
	iframeRef.style.height = "auto";
	iframeRef.style.overflow = "hidden";
	pageDimensions = getPageDimensions(iframeRef.contentWindow);
	iframeRef.style.height = pageDimensions[1] + "px";
	return true;
};

function getPageDimensions(windowRef)
{
	var body = windowRef.document.getElementsByTagName("body")[0];
	var bodyOffsetWidth = 0;
	var bodyOffsetHeight = 0;
	var bodyScrollWidth = 0;
	var bodyScrollHeight = 0;
	var pageDimensions = [0, 0];

	if (typeof windowRef.document.documentElement != "undefined" && typeof document.documentElement.scrollWidth != "undefined")
	{
		pageDimensions[0] = windowRef.document.documentElement.scrollWidth;
		pageDimensions[1] = windowRef.document.documentElement.scrollHeight;
	}

	bodyOffsetWidth = body.offsetWidth;
	bodyOffsetHeight = body.offsetHeight;
	bodyScrollWidth = body.scrollWidth;
	bodyScrollHeight = body.scrollHeight;

	if (bodyOffsetWidth > pageDimensions[0])
	{
		pageDimensions[0] = bodyOffsetWidth;
	}

	if (bodyOffsetHeight > pageDimensions[1])
	{
		pageDimensions[1] = bodyOffsetHeight;
	}

	if (bodyScrollWidth > pageDimensions[0])
	{
		pageDimensions[0] = bodyScrollWidth;
	}

	if (bodyScrollHeight > pageDimensions[1])
	{
		pageDimensions[1] = bodyScrollHeight;
	}

	return pageDimensions;
}





/* FIN */
