										/*
 * Macquarie MGL/AU Utilities JavaScript
 *
 * http://macquarie.com.au
 *
 * Copyright (c) 2010 - Macquarie Bank
 */
	
	
jQuery.namespace('jQuery.MacquarieUtils');	

try {
 document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}
	
var pageToolsEmailLink = "#Needs to be defined within a portal specific JS";
var rightToLeftOffset;
var ver = 0;
var defaultFontSize = 12;
var smallFontSize = parseFloat(defaultFontSize, 10) * 0.8;
var largeFontSize = parseFloat(defaultFontSize, 10) * 1.2;
var currentPage = 0;
var articlesPerPage = 100;
var paginationLimit = 8;
var startPage = 0;
var listItem = 0;
var numOfArticles = 0;
var numOfPages = 0;
var list = null;
var container = null;
var fontResizeObject = ".VC-fontResizeTool";
var defaultFont = ".defaultFont";
var largeFont = ".largeFont";
var smallFont = ".smallFont";
var pageBody = "#VC-pageBody";



$(document).ready(function () {
    jQuery.MacquarieUtils.initMenus("primaryMenu");
    jQuery.MacquarieUtils.initMenus("secondaryMenu");
    jQuery(function () {
        jQuery('ul.rollovermenu').superfish({
            delay: 0,
            animation: {
               opacity: '50',
                height: 'toggle'
            },
            speed: 'normal',
            autoArrows: true,
            dropShadows: false,
            disableHI: false
        });
    });	
	/* 
	initalise links to add icons at runtime
	*/
	
	// Add pdf icons to pdf links
	$("a[href$='.pdf']").addClass("pdf");
	// Add Word icons to word links (doc, rtf, txt)
	$("a[href$='.doc'], a[href$='.docx']").addClass("doc");
	// Add Excel icons to word links (doc, rtf, txt)
	$("a[href$='.xls'], a[href$='.xlsx']").addClass("excel");
	// Add txt icons to document links (doc, rtf, txt)
	$("a[href$='.txt'], a[href$='.rtf']").addClass("txt");
	// Add zip icons to Zip file links (zip, rar)
	$("a[href$='.zip'], a[href$='.rar']").addClass("zip"); 
	// Add email icons to email links
	$("a[href^='mailto:']").addClass("email");
	//Add external link icon to external links - 
//	$("a:not('#funds a, .footerLinks ul li a')").filter(function() {
	/*$("a").not("#funds a,#feature-container-wrap div.footerLinks ul li a").filter(function() {
		//Compare the anchor tag's host name with location's host name
	    return this.hostname && this.hostname !== location.hostname;
	  }).addClass("external");*/
	//You might also want to set the _target attribute to blank
	//$('a').filter(function() {
		//Compare the anchor tag's host name with location's host name
	//   return this.hostname && this.hostname !== location.hostname;
	$("a").removeClass('external');
	
	/* 
	color box plugin for lightboxes 
	*/
	$("a[rel='map']").colorbox({transition:"fade"});
	$("a[rel='chart']").colorbox({transition:"fade"});
	$("a[rel='gallery']").colorbox({slideshow:true, transition:"fade", slideshowAuto:false});
	/* 
	init various functions
	*/

    jQuery.MacquarieUtils.initResizeFontTool();
    jQuery.MacquarieUtils.initPortalNavMenu();
    jQuery.MacquarieUtils.initPageTools();
    jQuery.MacquarieUtils.initLinkElevents();
	jQuery.MacquarieUtils.formatTable();
	jQuery.MacquarieUtils.initSlideShow();
	jQuery.MacquarieUtils.initPopupLinks();
	accordionMenuClick.initMenu(); 
    initBreadcrumb();
    initTabs();
    initPagination();
    getYear();
    $('.VC-graphicSelect').selectbox({
        inputClass: 'selectbox'
    });
});
$(window).load(function () {
    applyTooltipEvents();
    applyTableSorterEvents();
    forceRedrawForIE();
});


/*

NEWS FUNCTIONS FOR XML GENERATED ARTICLES


jQuery.MacquarieUtils.initNewsLinks = function () {
	var $tabContainer = $("div.VC-tabModule");
	if ($tabContainer.length >0) {
		var $hasLink = $tabContainer.find("div a.news-article");
		if ($hasLink.length >0 ) {
			$hasLink.bind("click",function () { 
				jQuery.MacquarieUtils.clickNewsLinks($(this).attr('rel'));
				return false;
			});
		}
	}
};
  

this is used to process the new 


jQuery.MacquarieUtils.clickNewsLinks = function (objCallerval) { 
        var strLocation = window.location.href; //get the location
		var locationArray = [];
		 locationArray = parseURL(strLocation); //send the location to the parser
		var getURL = locationArray.protocol + "://" + locationArray.host + objCallerval; //build the url
		 $.ajax({
			   type: "GET",
			   url: getURL,
			   dataType: "xml",
			   success: function( xml ) {
					return	$(xml).find('article').each(function(){
							var title = $(this).find('articletitle').text();
							var date = $(this).find('date').text();
							var content = $(this).find('content').text();
						    var attachments = $(this).find('attachments').text();
							var contact = $(this).find('contact').text();
					
							$('.VC-tabModule > div')
							 .filter(":not('.tabs-hide')")
							.html(title)
							.append(date)
							.append(content)
							.append(attachments)
							.append(contact);
						});
					},
					
					error: function( xml ){ 
alert("Unable to access the article. Please check the following:" + '\n' + "1. The target url in the rel attribute." + '\n' + "2. The publish path of the file.");
					}
			 });
	
}

*/
/*
accordion menu plugin

use:


$(document).ready(function(){
	$('#faq').accordionMenu({
		defaultTagHidden: "dd",
		triggerElement: "dt",
		hasShowAll: true,
		controllerElement: "controls"
	});

});

Parameters:

defaultTagHidden: the default tag on which we should hide initially.
triggerElement: this is the lement that triggers the hide and show of content.
hasShowAll: does this have a show all element to show all of the items at once.
controllerElement: this is the container that holds the show all / hide all


*/
(function($){
    $.fn.extend({
        accordionMenu: function(options) {
            var defaults = {
                defaultTagHidden: "dd", //default tag for hiding
               triggerElement: "dt" , //trigger element to trigger the hide
			   hasShowAll: false, //has a control to show all 
			   controllerElement: "controls" //give the element for controlling a name
            };
			//etend and use the options here 
            var options = $.extend(defaults, options);
			/* bind the values to each variable  */
			var objTriggerElement =  options.triggerElement; 
			var objHideElement =  options.defaultTagHidden;
			var boolhasShowAll =  options.hasShowAll;
			var $objcontrollerElement = $('#' + options.controllerElement);
			
            return this.each(function() {
				$(objHideElement).hide(); //hide the elements
				$(objTriggerElement).click(function(){ //bind the click event to it 
				 $(this).next().slideToggle();
			   });
				if ( boolhasShowAll ) { //if it has a controller then check for it
					if ($objcontrollerElement.length > 0) { //see if its actually there
						if ($objcontrollerElement.children()) { //check to see if it has child elements
							$objcontrollerElement.children().eq(0).click(function(){ //bind the click function
								$(objHideElement).show(); //show it
						   }); 
							$objcontrollerElement.children().eq(1).click(function(){ //bind the click function
								$(objHideElement).hide(); //hide it
						   }); 
							//some error checking	
						} else {
							alert("The controller has no children.");		
						}
					} else {
						alert("there is no controller html defined.");	
					}
				}
            });
        }
    });
})(jQuery);



jQuery.MacquarieUtils.initPopupLinks = function () {
	if ($('.winCloser').length >0) {
		 $('.winCloser').click(function () { 
				$(this).winCloser();
				return false;
		 });
	}
};



/*

purpose: Use this function for closing popup windows and redirecting the browser to a new URL.

Use: 

 <a href="http://www.google.com" class="winCloser">test link</a>

*/

jQuery.fn.extend({
  winCloser: function( ) {	  
  
		var newWinLocation = false;
		var hrefStr = $(this).attr('href'); //get the value of the href inside the string
		//check that this is a valid URL. An invalida one will not work.
		//var rExpression = new RegExp("^((http:\/\/www\.)|(www\.)|(http:\/\/))[a-zA-Z0-9._-]+\.[a-zA-Z.]{2,5}$"); 
		var testResult = null;	
		var strLocation = window.location.href; //get the location
		var locationArray = [];
		
		locationArray = parseURL(strLocation); //send the location to the parser
		
	 try
	  {
		newWinLocation = hrefStr !== null || newWinLocation !== " " ? true : false; //check that the string is not equal to null
	    //testResult = rExpression.exec(hrefStr); //check against the expression that we have
		var getURL = locationArray.protocol + "://" + locationArray.host + newWinLocation; //build the url  
		if ( newWinLocation ) { // if we have a result
			window.opener.location = hrefStr; // get the page that opened the window to redirect to the location described in the href of the link
			window.self.close();
		} else { throw "err";}
	  }
	catch(err)
	  { 
		alert("Unable to validate the url. Please check the following:" + '\n' + "1. The target url in the href attribute.");
	  }
  }
});



/*

for primary and secondary menus
*/


jQuery.MacquarieUtils.initMenus = function (menuType) {
	
    var $primaryMenu = jQuery('div#VC-navigation');
    var $secondaryMenu = jQuery('div#VC-siteWideHeaderRight');
    switch (menuType) {
    case "primaryMenu":
        $primaryMenu.show();
        $primaryMenu.find('ul:first').attr('class', 'rollovermenu');
        break;
    case "secondaryMenu":
        $secondaryMenu.show();
        $secondaryMenu.find('ul:first').attr('class', 'rollovermenu');
        break;
    }
};

/*
Banner slideshow for homepage

*/
jQuery.MacquarieUtils.initSlideShow = function () {
var $herobanner = $('#herobanner');	
	if ( $herobanner.length >0 ) {
		 $('#herobanner').before('<div id="banner-caption"></div><div id="nav">').cycle({
					fx:'fade',
					speed:900,
					timeout:6000,
					pager: '#nav'
		 });
	}
};

/*

to stripe the alternate rows on the tables
*/


jQuery.MacquarieUtils.formatTable = function () {
   $("#VC-mainContent table tbody tr:even").addClass("alt"); //original alternate class
    var tables = $("#VC-mainContent table");
    tables.each(function () {
        $("tr td:first-child", this).addClass("firstCol");
        $("tr th:first-child", this).addClass("firstCol");
    });
};
/* 
for the print icons on the pages

*/
jQuery.MacquarieUtils.initPageTools = function () {
    $(".VC-pagetools").html('<a class="printPage" title="print this page" href="#"><span>print</span></a>')
}




jQuery.MacquarieUtils.initPortalNavMenu = function () {
    $("ul.rollovermenu li:has(> a.current)").addClass("current-item");
    var navMenu = $(".rollovermenu li");
    navMenu.hover(function () {
        header = $(this);
        if (header.hasClass("current-item")) {
            header.removeClass("current-item").addClass("current-hover")
        } else {
            header.addClass("hover")
        }
    }, function () {
        header = $(this);
        if (header.hasClass("current-hover")) {
            header.removeClass("current-hover").addClass("current-item")
        } else {
            header.removeClass("hover")
        }
    });
    navMenu.first().attr("id", "first");
    navMenu.last().attr("id", "last")
}

/*
to store the selected font size inside a cookie


*/

jQuery.MacquarieUtils.initResizeFontTool = function () {
    $(".VC-fontResizeTool").css("display", "block");
    $(".defaultFont").click(function () {
        jQuery.MacquarieUtils.resizeFontsFunction(defaultFontSize);
        $.cookie("VCFontResizerSelection", "" + defaultFontSize, {
            expires: 7
        });
        return false
    });
    $(".largeFont").click(function () {
        jQuery.MacquarieUtils.resizeFontsFunction(largeFontSize);
        $.cookie("VCFontResizerSelection", "" + largeFontSize, {
            expires: 7
        });
        return false
    });
    $(".smallFont").click(function () {
        jQuery.MacquarieUtils.resizeFontsFunction(smallFontSize);
        $.cookie("VCFontResizerSelection", "" + smallFontSize, {
            expires: 7
        });
        return false
    });
    var currentVCFontSize = $.cookie("VCFontResizerSelection");
    if (currentVCFontSize) {
        jQuery.MacquarieUtils.resizeFontsFunction(parseFloat(currentVCFontSize))
    }
};

/*
to adjust the font size and highlight the selected font

*/


jQuery.MacquarieUtils.resizeFontsFunction = function (fontDimension) {
    $("#VC-pageBody, #VC-breadcrumbs").css('font-size', fontDimension);
    $("#VC-pageBody .ui-tabs-nav, .VC-noResize").css('font-size', defaultFontSize);
    $("#VC-pageBody .loginButton.noFontResize").css('font-size', "14px");
    if (fontDimension == smallFontSize) {
        $("#VC-fontResizeTool a.smallFont").css("background-position", "0 -23px");
        $("#VC-fontResizeTool a.defaultFont").css("background-position", "-18px 0");
        $("#VC-fontResizeTool a.largeFont").css("background-position", "-36px 0")
    } else if (fontDimension == defaultFontSize) {
        $("#VC-fontResizeTool a.smallFont").css("background-position", "0 0");
        $("#VC-fontResizeTool a.defaultFont").css("background-position", "-18px -23px");
        $("#VC-fontResizeTool a.largeFont").css("background-position", "-36px 0")
    } else if (fontDimension == largeFontSize) {
        $("#VC-fontResizeTool a.smallFont").css("background-position", "0 0");
        $("#VC-fontResizeTool a.defaultFont").css("background-position", "-18px 0");
        $("#VC-fontResizeTool a.largeFont").css("background-position", "-36px -23px")
    }
};

/*
to apply page level events

*/

jQuery.MacquarieUtils.initLinkElevents = function () {
  
        $(".printPage").click(function ($e) {
            $e.preventDefault();
            window.print();
            return false
        });
		
		
        $('a.popup').bind('click', function (e) {
            popwindow(e)
        });

       function popwindow(e) {
            e.preventDefault();
			 var href = null;
			 href = $(e.target).attr('href'); //get the href attribute from the link	 
			 // if it's undefined then it's because there is (possibly) an image inside the anchor. 
			 //This will call it to return undefined as the image itself does not have an attribute 'href'
			 //In turn the parent object the (anchor) will need to be targeted 
				if ($(e.target).attr('href').length == 0)  {  
					href =	$(e.target).parent().attr('href'); //target the parent
				 } else if ( $(e.target).attr('href').length >0) {
					href = $(e.target).attr('href'); //target the element
				 }
            Wpercent = 65;
            Hpercent = 80;
            wW = parseInt((screen.width * Wpercent) / 100) + 'px';
            wH = parseInt((screen.height * Hpercent) / 100) + 'px';
window.open(href, "popup", "menubar=1,resizable=1,toolbar=no,status=no,directories=no,scrollbars=1,location=no,menubar=no,top=0,left=200px,width=" + wW + ",height=" + wH + "");
		return false;
        }
};

/*
for the profiles accordion

*/

jQuery.MacquarieUtils.initProfiles = function () {
    if (jQuery('dl.profiles').length > 0) {
        var $parentElement = $("dl.profiles");
        var $targetElement = $("dl.profiles dd a");
		
		if (this.eventType == "click") {
			$targetElement.bind("click", function (e) {
				e.preventDefault();
				if (null != $(this).prev()) {
					jQuery.MacquarieUtils.slideElement($(this).prev());
				}
			});
		} else if (this.eventType == "hover") {
			$targetElement.bind("click", function (e) {
				e.preventDefault();
			});
			$targetElement.hover(function () {
				if (null != $(this).prev()) {
					jQuery.MacquarieUtils.slideElement($(this).prev());
				}
			}, function () {});
		}
		
		
        if ($parentElement.prev().find("a").length == 0) {
            $parentElement.before('<p class=\"showHideProfiles\"><a href=\"#\">show all profiles</a></p>');
        }
        var $anchorElement = $parentElement.prev().find("a");
        var $currElemState = "";
        $anchorElement.bind("click", function (event) {
            event.preventDefault();
            if ($anchorElement.hasClass("isSelected")) {
                $currElemState = ":visible";
            } else if (!$anchorElement.hasClass("isSelected")) {
                $currElemState = ":hidden";
            }
            $targetElement.prev($currElemState).animate({
					left: '+=50',
					height: 'toggle'
				}, 1000, function () {});
			
				if ($anchorElement.hasClass('isSelected')) {
				$anchorElement.removeClass("isSelected").text("show all profiles").css({backgroundPosition: '.5em -54px'})
				.end();
				$targetElement.css({backgroundPosition: '0 0'})
				} else {
				$anchorElement.addClass("isSelected").text("hide all profiles").css({backgroundPosition: '0 -162px'})
					.end(); 
				$targetElement.css({backgroundPosition: '0 -125px'})
            }
			
        })
    }
};



jQuery.MacquarieUtils.slideElement = function ($objTarget) {
if (null != $objTarget) {
	var boolIsHidden = $objTarget.is(':hidden');
		if (boolIsHidden) {
			if ($(".selected").length > 0) {
				$(".selected").slideUp("normal").removeClass("selected").next().css({
					backgroundPosition: '0 0'
				});
			}
			$objTarget.animate({ left: '+=50',height: 'toggle'}, 1000, function () {}).addClass("selected");
			$objTarget.next().css({
				backgroundPosition: '0 -125px'
			});

		}	
   }
};

/*
These two objects will initialise the menu for hover of click

*/

//make the menu click only
var profilesClick = {
    "eventType": "click", 
    "initProfile" : jQuery.MacquarieUtils.initProfiles
};

//make the menu on hover only
var profilesHover = {
    "eventType": "hover", 
    "initProfile" : jQuery.MacquarieUtils.initProfiles
};

/*
for the tool tips. The is initialised in the assetmap.js file. 

*/
jQuery.MacquarieUtils.initTooltips = function (MenuDiv, MapDiv) {
    var $menuDiv = $("#" + MenuDiv);
    var mapDiv = $("#" + MapDiv);
    var toolTipContent = null;
    var assetURL = null;
    var $menuUl = null;
	var assetLinkText = null;
    if ($menuDiv.length > 0) {
        if ($menuDiv.find("ul").length > 0) {
            $menuUl = $menuDiv.find("ul");
            $menuUl.find('li a[href]').each(function (index, hrefValue) {
				assetLinkText = $(this).text();									  
                if ($(mapDiv).length > 0) {
                    $(mapDiv).find("ul").append("<li></li>");
                    $(mapDiv).find("li:eq(" + index + ")").each(function () {
                        toolTipContent = jQuery.MacquarieUtils.GenerateContent(hrefValue,assetLinkText);
                        assetURL = jQuery.MacquarieUtils.returnLastPartOfString(hrefValue,"/");
                        $(this).addClass(assetURL).append("<a href=" + hrefValue + "><span>" + assetURL + "</span></a>").find("a").qtip({
                        content: toolTipContent,
                            show: {
                                when: 'mouseover',
                                solo: true
                           },
						    hide: {
                                when: 'inactive',
                                delay: 3000
                            },
                            style: {
                                width: 260,
                                padding: 0,
                                background: '#ffffff',
                                color: 'black',
                                textAlign: 'left',
                                border: {
                                    width: 7,
                                    radius: 8,
                                    color: '#fff'
                                },
                                tip: 'leftMiddle'
                            },
                            position: {
                                adjust: {
                                    x: 10,
                                    y: -80
                                }
                            }
                        });

						//this is the trigger for the menu on the left side of the page.
                        //$menuUl.find("li:eq(" + index + ") a[href]").bind("mouseover", function () {
                         //   $(mapDiv).find("ul li a:eq(" + index + ")").trigger('mouseover');
                            //return false;
                        //})
                    })
                }
            })
        } else {
			$(mapDiv).append("<div style=\"position:absolute;top:172px;color:#ff3300;\"><strong>There is a missing ul on the left side which is preventing the map from being rendered.</strong></div>");	
		}
		
    }
};
/*
Used to close the tooltip

*/
jQuery.MacquarieUtils.closeToolTip = function () {
	$('.qtip').hide();
};

/*

Injects the content for the tool tip

*/

jQuery.MacquarieUtils.GenerateContent = function (srcVal,strAssetLinkText) {
    var returnContentStructure = null;
    var contentTitle = jQuery.MacquarieUtils.returnLastPartOfString(srcVal,"/");
	var stringAssetName = jQuery.MacquarieUtils.replaceCharacter(contentTitle,"-");
    returnContentStructure = "<div><span class=\"tooltip-title\">" + strAssetLinkText + "&nbsp;<a href=\"#\" class=\"tooltip-close\" title=\"close this window\" onclick=\"jQuery.MacquarieUtils.closeToolTip(); return false;\"><span>&nbsp;</span></a></span><p class=" + contentTitle + ">&nbsp;</p><p><a href="+ srcVal +" class=\"tooltip-link\" title=\"more information about " + strAssetLinkText + "\">more information</a></p></div>";
    return returnContentStructure
};
/*
replace the hypens inside the tooltip as the content is build from the href channel on the page

can also be used to replace any character in a string

Example usage:

strText: "this,is,a,string" //the string you want to modify

charToReplace: "," //the character you would like to replace

returns: this is a string // the output of the function


*/
jQuery.MacquarieUtils.replaceCharacter = function (strText,charToReplace) {
	var strReplaceAll = strText;
	var intIndexOfMatch = strReplaceAll.indexOf( charToReplace );
		while (intIndexOfMatch != -1){
			strReplaceAll = strReplaceAll.replace( charToReplace, " ");
			intIndexOfMatch = strReplaceAll.indexOf( charToReplace );
		}
 		return strReplaceAll;
};

/*
split any string 

Example usage:

strToSplit: "http://localhost/mpt/Portfolio/Hydro+Power/Dryden.htm" //the string you want to modify

charToReplace: "/" //the character you would like to replace

charToSplitWith: "/" 

returns an array: 

localhost
mpt
Portfolio
Hydro+Power
Dryden.htm

*/

jQuery.MacquarieUtils.splitTheString =  function(strToSplit,charToFind,charToSplitWith) {
	var strSnippets = [], strSplit;
    var slicedChars = strToSplit.slice(strToSplit.indexOf(charToFind) + 1).split(charToSplitWith);
		for(var i = 0; i < slicedChars.length; i++)
		{
			strSplit = slicedChars[i].split(charToSplitWith);
			strSnippets.push(strSplit[0]);
			strSnippets[strSplit[0]] = strSplit[1];
		}
		return strSnippets;
}

/*

displayMenu :

Allows the multiple level links to be remembered by comapring the current url location with the anchor. 
When there is a match then closest ul element is shown, this goes for parent and child elements.

*/

jQuery.MacquarieUtils.displayMenu =  function() {
   var $parentElement = $("#csMenu"); //parent div
        var $targetElement = $parentElement.find("a"); //find the anchors
		var numberOfChildren = $parentElement.find('ul:first').children("*").has('ul').length; //determine if the location has any children
		var strLocation = window.location.href;
		var arrPaths = [];
		var locationText = new String();
	    var pathLoc =   new String();
		if (null != $parentElement && numberOfChildren >0) { //check the for the child element
		 locationArray = parseURL(strLocation); //send the location to the parser
		   arrPaths = locationArray.segments; //get the url segments from the parser
		   for (var k = 0; k < arrPaths.length; k++) { 
				pathLoc = pathLoc + arrPaths[k] + "/";	//build an array of the paths with slashes   
		   }										
		 locationText = pathLoc.substr(0,pathLoc.length -1); //remove the last slash
			$parentElement.find('a').each(function () {//find each of the a tags								
				if ( $(this).attr('href').toLowerCase() != null && locationText.toLowerCase() != null) {									
					if ($(this).attr('href').toLowerCase() == "/" + locationText.toLowerCase()) {
						if ($(this).next('ul').length > 0) { //check if the current link has a ul underneath it
							$(this).next('ul').slideDown('normal');	//if it does then show it 
						}
						
						if ($(this).parents('ul').length > 0) { //find if the link has any parent ul's 
							$(this).parents('ul').slideDown('normal'); 	//if there is a parent element
						}
					}
				}
    	   });			
	 }
}

/*

parseURL: 

a useful utility 

*/

function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}


/*
These two objects will initialise the menu for hover of click
*/

//make the menu click only
var accordionMenuClick = {
    "eventType": "click", 
    "initMenu" : jQuery.MacquarieUtils.displayMenu
};
//make the menu on hover only
var accordionMenuHover = {
    "eventType": "hover", 
    "initMenu" : jQuery.MacquarieUtils.displayMenu
};

/*
start original content

*/

function initArticleListPagination() {
    list = $(".VC-articleList li");
    listItem = 0;
    numOfArticles = list.length;
    numOfPages = Math.ceil(numOfArticles / articlesPerPage) - 1;
    var paginationDiv = "<div id='VC-pagination' class='VC-pagination'></div>";
    $("#VC-mainContent").append(paginationDiv);
    container = $("#VC-pagination");
    renderList();
    generatePagination();
}

function initBreadcrumb() {
    var breadcrumbStartSlicing = 2;
    var breadcrumbEndSlicing = 1;
    var maxBreadcrumbMaxSize = 110;
    var isFirstElement = true;
    var $elements = $(".VC-breadcrumbs a,.VC-breadcrumbs .breadcrumbLabel");
    var bc_removed_text = 0;
    var bc_initial_length = $elements.totalTextLength();
    var startElement = 0;
    while (bc_initial_length - bc_removed_text > maxBreadcrumbMaxSize && breadcrumbStartSlicing < $elements.length && $elements.length > breadcrumbStartSlicing + breadcrumbEndSlicing && breadcrumbStartSlicing < 30) {
        var $selectedElements = $elements.slice(breadcrumbStartSlicing, $elements.length - breadcrumbEndSlicing);
        if (isFirstElement) {
            isFirstElement = false;
            startElement = breadcrumbStartSlicing;
        }
        bc_removed_text += $selectedElements.eq(0).html().length;
        breadcrumbStartSlicing++;
    }
    if (!isFirstElement) {
        $elements.slice(breadcrumbStartSlicing - 1, breadcrumbStartSlicing).textEllipsis("...");
        $elements.slice(breadcrumbStartSlicing - 1, breadcrumbStartSlicing).tooltip({
            track: true,
            delay: 500,
            showURL: false,
            showBody: " - ",
            fade: 250
        });
        $elements.slice(startElement, breadcrumbStartSlicing - 1).next("span").remove();
        $elements.slice(startElement, breadcrumbStartSlicing - 1).remove();
    }
}
function initNewsArticlePagination() {
    var paginatedArticles = $(".VC-articlepagination .VC-articlePage");
    numOfPages = paginatedArticles.length - 1;
    if (paginatedArticles.length > 0) {
        paginatedArticles.slice(1).hide();
        var paginationDiv = "<div id='VC-pagination' class='VC-pagination'></div>";
        $("#VC-mainContent").append(paginationDiv);
        navigateNewsArticlePagination();
    }
}
function initPagination() {
    if ($("#VC-articleList").length > 0) {
        initArticleListPagination();
    }
    if ($(".VC-articlepagination").length > 0) {
        initNewsArticlePagination();
    }
}

/* use of the tabs with an extra height on IFRAMES*/
function initTabs() {
	
	var pageURL = window.location.href;		 
    var strObj = new String(pageURL); 
	var strPosition = strObj.lastIndexOf("/"); 
	var strURL = strObj.slice(0, strPosition);
	var strTarget = null;
	var $tabHref = null;
	var $tabModule = $(".VC-tabModule");
	var strFileName = " ";
	var strIframeName = " ";
	var iframeHeight = "";
	var boolHeadingExists = 0;
	var pageArray = [];
	pageArray = parseURL(pageURL); //send the location to the parser
	
	// This code wraps the tab anchor elements' text in a span so that we can get the spans' text and create it as a h2 heading
	// so that when a tabbed page is printed it prints semantically-correct headings at the correct level in the document
	
	if ($tabModule.length >0) { //check that the tabs exist
		// if they do, add a span into the actual tab. Why?
		//$(".VC-tabModule ul li a").wrapInner(document.createElement("span"));
		$tabModule.find("ul li a").wrapInner(document.createElement("span"));
		//loop through the spans to get the text so we can have a h2 heading with the same content when printing
		$tabModule.find('ul li a span').each(function (index) { 
			$tabHref = $(this); // get the inner text
			//get the text and then add the h2 into the DOM			
			boolHeadingExists = $(".VC-tabModule").find('div:eq(' + index + '):has(h2)').length;
			if (!boolHeadingExists) {
				$(".VC-tabModule").find('div:eq(' + index + ')').prepend("<h2>" + $tabHref.text() + "</h2>"); 
			}
	});
		
	$tabModule.tabs(); //init the tabs
	 
	 //This code takes the current iframe src and stores it in a cookie.
	 //It then creates a URL string (newStrHref) based on the cookie value.
	 //Once this has finished, it appends the newStrHref value to the tab anchor's href attribute, then binds a click event to it.
	 
	try {
	 
		var $currentIframeObj = $(".VC-tabModule").children(':not(ul)').find('iframe'); //find the iframes 
		if ($currentIframeObj.length >0) {
			$currentIframeObj.each(function(index) { //loop through each iframe
				$iframeSrc = $currentIframeObj.get(index);	//get the iframe by index
				var currentFrameLocation = $.cookie('iframeLocation'); //get the frame's location
				var currentFrameArray =  parseURL(currentFrameLocation); //parse the iframeLocation URL
							
				if ( currentFrameLocation === null ) {
					//if the iframeLocation cookie does not exist then set one with the current iframe src ...
					$.cookie("iframeLocation", $iframeSrc.src, { expires: 1 });		// and set it to expire after one day
				}
					//But if the iframeLocation cookie does exist ...
				else if ( currentFrameLocation ) {
					if (pageArray.segments[2] !== "mqa") {
						// do nothing
					}
					else {
						var pageCompany = pageArray.file.replace("-news","").replace(".htm","");
						var iframeCompany = currentFrameArray.segments[1]; //find which company the cookie is set to
						//Check if the iframeLocation is set correctly for the page 
						if ( iframeCompany !== pageCompany ) { //Check if the iframe's company is the same as the page's 
								var iframeHref = $.cookie("iframeLocation").replace(currentFrameArray.segments[1],pageCompany);
								$.cookie("iframeLocation", iframeHref, { expires: 1 }); // If the iframe's company isn't the same as the page's, change the cookie
						}
					}
				}
				strIframeName = $iframeSrc.id; //get the iframe's id which should be in the form "year-2010"
				strFileName = $iframeSrc.id.replace("year-","");//remove the "year-" part of the id to get just the number 
				
				if (strFileName === "" || typeof strFileName === "undefined") { //check to see if we have a value. If not, exit the method.
					return false;
				}
				
				//build the tab anchor's href string including the #hash for the div name and year
				//note: MIIF requires special treatment
				if (pageArray.segments[1] !== "miif") {
					var newStrHref = $.cookie("iframeLocation").substring(0, ($.cookie("iframeLocation").length)-8) + strFileName + ".htm" + "#GDtabs-0-" + index; 
				} else {
					var newStrHref = $.cookie("iframeLocation").substring(0, ($.cookie("iframeLocation").length)-8) + strFileName + ".htm" + "#GDtabs-1-" + index; 
				}
			//find the tabs' anchor hrefs by index
				$tabModule.find("ul li a:eq(" + index + ")") //find the anchor's element by index
					 .attr("href",newStrHref) //change the anchor's href to the new href string 
					 .attr("title","Click to view the index of "+strFileName + " news releases") //give it a title attribute
					 .bind("click", function(e){	//bind a click function to it
						var yearText = "";
						var spanText = $(this).children("span").text();

						if (spanText.length === 2) {
							yearText = "20" +spanText;
						}
						else {
							yearText = spanText;
						}
				
						var strYearText = "year-"+  yearText; //get the year out of the span's text (that is, the tab's label)			
					
					//check if there is an iframe with an id that matches the tab
					
						if ($tabModule.find("iframe[id='" +strYearText+ "']").length >0) {  
							//if there is, change the iframe's src to be the same as the anchor's href
							$tabModule.find("iframe[id='" +strYearText+ "']").attr("src",$(e.target).parent().attr('href')); 
								//if not then we need to inform the user what has happened.
						} else if ($tabModule.find("iframe[id='" +strYearText+ "']").length === 0 ||
								typeof $tabModule.find("iframe[id='" +strYearText+ "']") === null) {
									$tabModule.append("<p class=\"error\">Sorry, an internal error has occured while rendering the iframe</p>");
						}
				});			
			});
		}
	}
	catch(e) {
		$tabModule.append("<p class=\"error\">" + e +"</p>");  
	}
}
	
}


function applyTableSorterEvents() {
    $(".productComparison").tablesorter();
}

function applyTooltipEvents() {
    $(".tooltip").tooltip({
        track: true,
        delay: 500,
        showURL: false,
        showBody: " - ",
        fade: 250
    });
}

function bindPaginationEvents(fnToInvoke) {
    $("#VC-pagination a.firstPage").bind("click", function (e) {
        currentPage = 0;
        listItem = 0;
        renderList();
        fnToInvoke();
    });
    $("#VC-pagination a.previousPage").bind("click", function (e) {
        currentPage -= 1;
        listItem = currentPage * articlesPerPage;
        renderList();
        fnToInvoke();
    });
    $("#VC-pagination a.nextPage").bind("click", function (e) {
        currentPage += 1;
        renderList();
        fnToInvoke();
    });
    $("#VC-pagination a.lastPage").bind("click", function (e) {
        currentPage = numOfPages;
        listItem = (currentPage * articlesPerPage);
        renderList();
        fnToInvoke();
    });
    $("#VC-pagination a.pageLink").bind("click", function (e) {
        currentPage = parseInt($(this).text(), 10) - 1;
        listItem = (currentPage * articlesPerPage);
        renderList();
        fnToInvoke();
    });
    $("#VC-pagination select").change(function () {
        $('html, body').animate({
            scrollTop: '0px'
        }, 0);
        currentPage = 0;
        listItem = 0;
        articlesPerPage = $(this).val();
        numOfPages = Math.ceil(numOfArticles / articlesPerPage) - 1;
        renderList();
        fnToInvoke();
    });
}

function forceRedrawForIE() {
    if (ver < 8.0 && ver > 0) {
        $(".VC-tabModule").addClass("forceRedraw");
    }
}
function generatePagination() {
    if (currentPage <= Math.ceil(paginationLimit / 2)) {
        startPage = 0;
    } else {
        startPage = currentPage - Math.ceil(paginationLimit / 2);
    }
    container.empty();
    var html = "";
    var className = "";
    if (startPage >= 0 && startPage <= numOfPages) {
       // html = "<div>";
        if (currentPage > 0) {
            html += "<a class='arrows firstPage' href='#VC-header' title='Click here to go to the first page'>\<\<</a>";
            html += "<a class='arrows previousPage' href='#VC-header' title='Click here to go to the previous page'>\< previous</a>";
        }
        for (i = startPage; i < startPage + paginationLimit; i++) {
            var page = i + 1;
           /// html += "<a class='pageLink page" + i.toString() + "' href='#VC-header'>" + page + "</a>";
            if (i == currentPage) {
                className = ".page" + currentPage.toString();
            }
            if (i == numOfPages) {
                break;
            }
        }
        if (currentPage < numOfPages) {
            html += "<a class='arrows nextPage' href='#VC-header' title='Click here to go to the next page'>next \></a>";
            html += "<a class='arrows lastPage' href='#VC-header' title='Click here to go to the last page'>\>\></a>";
        }
        html += "</div>";
        //html += "<select><option value='10'>10 </option><option value='30'>30 </option><option value='50'>50 </option></select>";
       // container.append(html);
        $(className).addClass("current");
        $("#VC-pagination select").val(articlesPerPage);
    }
    bindPaginationEvents(generatePagination);
}

function navigateNewsArticlePagination() {
    if (currentPage <= Math.ceil(paginationLimit / 2)) {
        startPage = 0;
    } else {
        startPage = currentPage - Math.ceil(paginationLimit / 2);
    }
    var paginatedArticles = $(".VC-articlepagination .VC-articlePage");
    container = $("#VC-pagination");
    var html = "<div>";
    var className = "";
    container.empty();
    paginatedArticles.hide();
    paginatedArticles.slice(currentPage, currentPage + 1).show();
    if (currentPage > 0) {
        html += "<a class='arrows firstPage' href='#VC-header' title='Click here to go to the first page'>\<\<</a>";
        html += "<a class='arrows previousPage' href='#VC-header' title='Click here to go to the previous page'>\< previous</a>";
    }
    for (i = startPage; i < startPage + paginationLimit; i++) {
        var page = i + 1;
        html += "<a class='pageLink page" + i.toString() + "' href='#VC-header'>" + page + "</a>";
        if (i == currentPage) {
            className = ".page" + currentPage.toString();
        }
        if (i == paginatedArticles.length - 1) {
            break;
        }
    }
    if (currentPage < paginatedArticles.length - 1) {
        html += "<a class='arrows nextPage' href='#VC-header' title='Click here to go to the next page'>next \></a>";
        html += "<a class='arrows lastPage' href='#VC-header' title='Click here to go to the last page'>\>\></a>";
    }
    html += "</div>";
    container.append(html);
    $(className).addClass("current");
    $(".pagePaginationCount").html("|  Page " + (Number(currentPage + 1)) + " of " + paginatedArticles.length);
    bindPaginationEvents(navigateNewsArticlePagination);
}

function renderList() {
    if (list) {
        list.css("display", "none");
        for (i = 1; i <= articlesPerPage; i++) {
            list.eq(listItem).css("display", "list-item");
            listItem++;
        }
    }
}
function getYear() {
    var d = new Date();
    $(".year").text(d.getFullYear() + " ");
}

function getRightToLeftOffset(el) {
    var dropdown = el.children("ul");
    var offset = el.width() - dropdown.width();
    return offset < 0 ? offset : 0;
}
$.fn.extend({
    tablesorter: function () {
        $(this).tablesorterOriginal({
            textExtraction: function (node) {
                var resultingText = jQuery.trim($.string(node.innerHTML).stripTags().str).toUpperCase();
                if (resultingText != "") {
                    return resultingText;
                } else {
                    return node.innerHTML;
                }
            },
            sortList: [
                [0, 0]
            ]
        });
        $(this).bind("sortEnd", function () {
            var ascSort = "th.headerSortUp";
            var descSort = "th.headerSortDown";
            var table = this;
            $(table).find("td").removeClass("firstCol");
            $(table).find(ascSort).add($(table).find(descSort)).each(function () {
                $(table).find("td:nth-child(" + ($("thead th").index(this) + 1) + ")").addClass("firstCol");
            });
        });
        $(".titleField").addClass("firstCol").removeClass("titleField")
    }
});
var formValidationUtils = {
    insertCaptcha: function () {
        document.write('<table class="noFormat"><tr><td class="rightAlign">&nbsp;</td><td><div class="VC-CaptchaContainer"><img id="captchaImage" src="/vgn-ext-templating/Captcha" alt="Captcha image" /><div class="VC-captchaInput">Type the word<span class="mandatory">*</span><br/><input type="text" id="captchaID" name="captchaID" class="mediumInputSize" /></div><div class="VC-CaptchaButtons"><a href="javascript:void(formValidationUtils.refreshCaptcha(\'captchaImage\'));" class="VC-refreshCaptcha"><ins>New&nbsp;challenge</ins></a><br/><a href="javascript:void(formValidationUtils.captchaHelp());" class="VC-elpCaptcha"><ins>Help</ins></a></div></div></td></tr></table>')
    }, captchaHelp: function () {
        alert("-Please enter the word you see in the box.\n Doing so helps prevent automated programs from abusing this service. \n-If you are not sure what the word is, click the 'New challenge' link.");
    }, ajaxValidateCaptcha: function (formId, captchaImageId, captchaId, callBackFn) {
        var captchaValidationUrl = "/vgn-ext-templating/FormAction?captchaCheck=" + escape($("#" + captchaId).val());
        try {
            $.ajax({
                url: captchaValidationUrl,
                context: document,
                success: function (data) {
                    if (data != "1") {
                        formValidationUtils.refreshCaptcha(captchaImageId);
                        if (callBackFn) {
                            callBackFn();
                        }
                        return false;
                    } else {
                        document.getElementById(formId).submit();
                    }
                }
            });
        } catch (err) {
            txt = "Error on this page.\n\n";
            txt += "Error description: " + err.description + "\n\n";
            alert(txt);
            return false;
        }
        return false
    },
    refreshCaptcha: function (captchaImageId) {
        var numRand = Math.floor(Math.random() * 100000);
        var newImage = "/vgn-ext-templating/Captcha?random=" + numRand;
        $("#" + captchaImageId).attr("src", newImage);
    }
}
function om_calculator(calculatorName) {
    var s = s_gi(s_account);
    s.linkTrackVars = 'prop5,eVar5,events';
    s.linkTrackEvents = 'event5';
    s.events = 'event5';
    s.prop5 = s.eVar5 = calculatorName;
    if (s.pageName && !s.eVar15) s.eVar15 = s.pageName;
    s.tl(this, 'o', calculatorName);
}

function om_promo(promotionName) {
    var s = s_gi(s_account);
    s.linkTrackVars = 'prop5,eVar5,events';
    s.linkTrackEvents = 'event5';
    s.events = 'event5';
    s.prop5 = s.eVar5 = promotionName;
    if (s.pageName && !s.eVar15) s.eVar15 = s.pageName;
    s.tl(this, 'o', promotionName);
}

function om_download(downloadName) {
    var s = s_gi(s_account);
    s.linkTrackVars = 'eVar14,events';
    s.linkTrackEvents = 'event7';
    s.events = 'event7';
    s.eVar14 = downloadName;
    if (s.pageName && !s.eVar15) s.eVar15 = s.pageName;
    s.tl(this, 'd', downloadName);
}
jQuery.fn.textEllipsis = function (text) {
    return this.each(function () {
        this.title = this.innerHTML;
        this.innerHTML = text;
    });
};
jQuery.fn.totalTextLength = function () {
    var totalLength = 0;
    this.each(function () {
        totalLength += this.innerHTML.length;
    });
    return totalLength;
};


/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

jQuery.cookie = function (key, value, options) {
    if (arguments.length > 1 && (value === null || typeof value !== "object ")) {
        options = jQuery.extend({}, options);
        if (value === null) {
            options.expires = -1
        }
        if (typeof options.expires === 'number') {
            var days = options.expires,
                t = options.expires = new Date();
            t.setDate(t.getDate() + days)
        }
        return (document.cookie = [encodeURIComponent(key), '=', options.raw ? String(value) : encodeURIComponent(String(value)),
        options.expires ? '; expires=' + options.expires.toUTCString() : '',
        options.path ? '; path=' + options.path : '',
        options.domain ? '; domain=' + options.domain : '',
        options.secure ? '; secure' : ''].join(''))
    }
    options = value || {};
    var result, decode = options.raw ?
    function (s) {
        return s
    } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null
};

jQuery.MacquarieUtils.returnLastPartOfString = function (strVal,charTofind) {
    var strObj = new String(strVal); 
	uSpos = strObj.lastIndexOf(charTofind); 
	sStr = strObj.slice(0, uSpos); 
	nStr = strObj.slice(uSpos + 1, strObj.length);
	return nStr;
};

