/*
 * DUET utilities JavaScript
 *
 * http://www.duet.net.au
 *
 * Copyright (c) 2011 - DUET Group
 */
 
 jQuery.namespace('jQuery.MacquarieUtils');
 
 
var pageToolsEmailLink = "#Needs to be defined within a portal specific JS";
var rightToLeftOffset;
var ver = getInternetExplorerVersion();
var defaultFontSize = 12;
var smallFontSize = parseFloat(defaultFontSize, 10) * 0.8;
var largeFontSize = parseFloat(defaultFontSize, 10) * 1.2;
var currentPage = 0;
var articlesPerPage = 10;
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.changeWidthMacBrowsers();	//this changes the width for mac specifc browsers					
							
	initPortalNavMenu();						
	//call the initialise menu funtion
 	jQuery.MacquarieUtils.initMenus("secondaryMenu");

	jQuery(function(){
			jQuery('ul.rollovermenu').superfish({
				delay: 0,
				animation: {
					opacity: '50',
					height: 'toggle'
				},
				speed: 'normal',
				autoArrows: false,
				dropShadows: false,
				disableHI: true
			});
		});			
							
    $.initProfiles();
    //initPortalNavMenu();
    //setupDropdownForIE();
    initBreadcrumb();
    initTabs();
    initPagination();
    jQuery.MacquarieUtils.initResizeFontTool();
    initPageTools();
    formatTable();
    topTabSpacerRemover();
    initGeneralStyles();
    getYear();
    $('.VC-graphicSelect').selectbox({
        inputClass: 'selectbox'
    });
    expandCollapseParagraphs();
    $("textarea").html($.trim($("textarea").html()))
});

/* this function is to address the problem in MAC browsers due toi the width of elements */


jQuery.MacquarieUtils.changeWidthMacBrowsers = function () {
 var $menuObject = jQuery('div#VC-navigation');
	if ($.browser.mac()) {
		if ($.browser.safari()) {
			jQuery('div#VC-navigation').css({'width' : '749px','left' : '246px'});		
		}
		if ($.browser.firefox()) {
			jQuery('div#VC-navigation').css({'width' : '746px','left' : '244px'});
		}	
    }
};



jQuery.MacquarieUtils.initMenus = function (menuType) {
	var $primaryMenu = jQuery('div#VC-siteWideHeaderRight');
	var $secondaryMenu = jQuery('div#VC-navigation'); 
  switch(menuType)
	{
	case "primaryMenu":
	  $secondaryMenu.show();
	  $secondaryMenu.find('ul:first').attr('class','rollovermenu');	  	
	  break;
	case "secondaryMenu":
	  $secondaryMenu.show();
	  $secondaryMenu.find('ul:first').attr('class','rollovermenu');	
	  break;
	
	}
};


$(window).load(function () {
    applyLinkEvents();
    applyTooltipEvents();
    applyTableSorterEvents();
   // initDdSmoothMenu();
    forceRedrawForIE();
});

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 initGeneralStyles() {
    $(".documentLink").prepend("<span class='documentLinkIcon'> </span>");
    $(".externalLink").append("<span class='externalLinkIcon'> </span>");
    $(".linkList li").prepend("<span class='linkListIcon'> </span>");
}

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 initPageTools() {
   $(".VC-pagetools").html('<a class="printPage" title="print this page" href="#"><span>print</span></a>');
}

function initPagination() {
    if ($("#VC-articleList").length > 0) {
        initArticleListPagination();
    }
    if ($(".VC-articlepagination").length > 0) {
        initNewsArticlePagination();
    }
}



/*
Function for accordion menu on profile pages.

1. gives accordion functionality to last div inside each row
2. creates an element for the user to click in order to show all elements at once.
*/

(function () {
    $.initProfiles = function () {
        if (jQuery('dl.profiles').length > 0) { //check if there is an object
			var $parentElement = $("dl.profiles");
            var $targetElement = $("dl.profiles dd a");
            $targetElement.bind("click", function (e) { //disable the click event
                e.preventDefault();
            });
			
			///hover state 
            $targetElement.hover(
            function () {
                if (null != $(this).prev()) { //check if we have a previous item 
                    var $objDiv = $(this).prev(); // get the div 
                    var boolIsHidden = $(this).prev().is(':hidden'); //ceheck if it's hidden
                    if (boolIsHidden) {
                        if ($(".selected").length > 0) { //check if we have any items with the selected  class on it
                            $(".selected").slideUp("normal") //slide up 
                            .removeClass("selected") //remove the class
                            .next().css({
                                backgroundPosition: '0 0'
                            }); //set the background position
                        }
                        $objDiv.slideDown("normal") //slide down
                        .addClass("selected"); //add the class 
                        $(this).css({
                            backgroundPosition: '0 -125px'
                        }); //backgorund position to be set 
                    }
                }
            }, function () {
                //do nothing
            });
			
			if ($parentElement.prev().find("a").length == 0) { //check if the element exists and if not then create it
				$parentElement.before('<p class=\"showHideProfiles\"><a href=\"#\">show all profiles</a></p>');
			}
		
		var $anchorElement = $parentElement.prev().find("a"); // find the element so we can bind the event to it
		var $currElemState = "";
			$anchorElement.bind("click", function(event){//bind a click event
			event.preventDefault();
			
			//used to override the toggle to combat the hover event opening individual layers.
			//checks to see iof the anchor has a class of isSelected and then hides it accordingly.
			
				if ($anchorElement.hasClass("isSelected")) {
					$currElemState = ":visible";
				} else if (!$anchorElement.hasClass("isSelected")) {
					$currElemState = ":hidden";
				}
					
				 $targetElement
				 .prev($currElemState)//target the element 
				   .animate({ // animate it
					opacity: 100,
					left: '+=50',
					height: 'toggle'
				  }, 1000, function() {
					//end animation 	
				  });
			   
				// toggle the class attribute	
				if ($anchorElement.hasClass('isSelected')) { //check if the element is selected
					$anchorElement 
					  .removeClass("isSelected") //remove the class that we put
					    .text("show all profiles") //change the inner text
					     .css({backgroundPosition: '.5em -54px'}) //and the bg postion
					 .end()//finish and target the achor elements with the arrow indicating that profile is shown
					   $targetElement.css({
                            backgroundPosition: '0 0'
                        }); //backgorund position to be set 0 
					   
				} else { // target the selected item and then change the inner text and bg postion just like above
					$anchorElement
					  .addClass("isSelected")
						.text("hide all profiles")
						   .css({backgroundPosition: '0 -162px'})
					 .end()
					   $targetElement.css({
							backgroundPosition: '0 -125px'
						}); //backgorund position to be set 					   
				}
    		});
	     }
    }
})(jQuery);



function initPortalNavMenu() {
      $("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");

/*
    navMenu.each(function () {
        var width = $(this).width() + 40;
        $(this).children("ul").children("li").css("width", width + "px");
        var height = parseInt($(this).children("ul").height(), 10);
        height += parseInt($(this).children("ul").css("padding-top"), 10) + parseInt($(this).children("ul").css("padding-bottom"), 10);
        leftHeight = height + 28;
        var dds = "<div class='ddsLeft' style='height:" + leftHeight + "px'></div> <div class='ddsRight' style='height:" + height + "px; left:" + width + "px'></div>";
        if ($(this).children("ul").hasClass("rightToLeft")) {
            dds = "<div class='ddsLeft' style='height:" + height + "px'></div> <div class='ddsRight' style='height:" + leftHeight + "px; left:" + width + "px'></div>";
        }
        $(this).children("ul").append(dds + "<div class='ddsLeftCorner' style='top:" + height + "px;'></div> <div class='ddsBottom' style='width:" + width + "px; top:" + height + "px'></div><div class='ddsRightCorner' style='left:" + width + "px; top:" + height + "px;'></div>");
    });
    var lastDropDown = $(".rollovermenu li ul.rightToLeft");
    var parentListItem = lastDropDown.parent("li");
    rightToLeftOffset = getRightToLeftOffset(parentListItem);
    parentListItem.hover(function () {
        lastDropDown.css("left", rightToLeftOffset);
    }, function () {
        lastDropDown.css("left", "-9999px");
    });
	
	*/
}

jQuery.MacquarieUtils.initResizeFontTool = function () {
    $(".VC-fontResizeTool").css("display", "block");
    $(".defaultFont").click(function () {
        jQuery.MacquarieUtils.resizeFontsFunction(defaultFontSize);
        $.cookie("VCFontResizerSelection", "" + defaultFontSize, {
           // path: '/mgl/au',
            expires: 7
        });
        return false;
    });
    $(".largeFont").click(function () {
       jQuery.MacquarieUtils.resizeFontsFunction(largeFontSize);
        $.cookie("VCFontResizerSelection", "" + largeFontSize, {
         //   path: '/mgl/au',
            expires: 7
        });
        return false;
    });
    $(".smallFont").click(function () {
        jQuery.MacquarieUtils.resizeFontsFunction(smallFontSize);
        $.cookie("VCFontResizerSelection", "" + smallFontSize, {
         //   path: '/mgl/au',
            expires: 7
        });
        return false;
    });
    var currentVCFontSize = $.cookie("VCFontResizerSelection");
    if (currentVCFontSize) {
        jQuery.MacquarieUtils.resizeFontsFunction(parseFloat(currentVCFontSize));
    }
};


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", "0px -23px");
        $("#VC-fontResizeTool a.defaultFont").css("background-position", "-18px 0px");
        $("#VC-fontResizeTool a.largeFont").css("background-position", "-36px 0px");
    } else if (fontDimension == defaultFontSize) {
        $("#VC-fontResizeTool a.smallFont").css("background-position", "0px 0px");
        $("#VC-fontResizeTool a.defaultFont").css("background-position", "-18px -23px");
        $("#VC-fontResizeTool a.largeFont").css("background-position", "-36px 0px");
    } else if (fontDimension == largeFontSize) {
        $("#VC-fontResizeTool a.smallFont").css("background-position", "0px 0px");
        $("#VC-fontResizeTool a.defaultFont").css("background-position", "-18px 0px");
        $("#VC-fontResizeTool a.largeFont").css("background-position", "-36px -23px");
    }
};

jQuery.MacquarieUtils.initPageTools = function () {
    $(".VC-pagetools").html('<a class="printPage" href="#" title="Print this page">print</a>');
};

jQuery.MacquarieUtils.initLinkElevents = function () {

    function applyLinkEvents() {
        $('.documentLink').click(function ($e) {
            $e.preventDefault();
            openNewWindow(this.href);
        });
        $('.externalLink').click(function ($e) {
            $e.preventDefault();
            window.open(this.href);
        });
        $(".printPage").click(function ($e) {
            $e.preventDefault();
            window.print();
            return false;
        });
        $('.openNewWindow').click(function ($e) {
            $e.preventDefault();
            openNewWindow(this.href);
        });

    }
};	 




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 $iframeSrc = "";
	 
	  if ($tabModule.length >0) { //check the tabs for there existence
		// 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 == 0) {
				$(".VC-tabModule").find('div:eq(' + index + ')').prepend("<h2>" + $tabHref.text() + "</h2>"); 
			}
		});
		
	 $tabModule.tabs(); //init the tabs
	 
	 //the following code takes the current iframe src and stores it in a cookie. It then creates a path based on the cookie value. Once this has finished then it appends this calue to the anchor href attribute, then bind a click evenet 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 frame by index
				if ( $.cookie("iframeLocation") == null ) { //if we don't have a cookie then set one with the current iframe src
					$.cookie("iframeLocation", $iframeSrc.src, { expires: 1 });		//set it to expire after one day
				} else {
					//do nothing
				}
				strIframeName = $iframeSrc.id;//get the name
				strFileName = $iframeSrc.id.replace("year-","");//remove the year
				//build the href string including the #hash for the div name & year etc
				var newStrHref = $.cookie("iframeLocation").substring(0, ($.cookie("iframeLocation").length)-8) + strFileName + ".htm" + "#GDtabs-0-" + index; 
			//find the anchor href tag by index
			 $tabModule.find("ul li a:eq(" + index + ")") //find the element by index
			  .attr("href",newStrHref) //change the attribute
			   .attr("title","Click to view the index of "+strFileName + " news releases") //give it a title tag
			    .removeClass("external")
				 .bind("click", function(e){	//bind a click function to it
					var strYearText = "year-"+  $(this).children("span").text(); //get the actual year out of the span tag
						if ($tabModule.find("iframe[id='" +strYearText+ "']").length >0) { //check if we have an iframe named 
						//if we do then change the src to be the same  as the href for the anschor
						 	$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("<div style=\"color:red;\">an internal error has occured while rendering the iframe</div>");
				        }
			});			
		});
      }
	}
	  catch(e) {
		$tabModule.append("<div style=\"color:red;\">" + e +"</div>");  
	}
 }
	
}



/*

function initTabs() {
    $(".VC-tabModule ul li a").wrapInner(document.createElement("span"));
	$('div.VC-tabModule ul li a span').each(function(index) { //get each span
		var $tabText = $(this).text(); //get its inner text
		 $(this).parents(".VC-tabModule") //find the parent elemet
			.find('div:eq(' + index + ')') //the the corresponding div by index
			 .find("h3:first") // get the first h3 inside the div
			  .before("<h2>" + $tabText + "</h2>"); //insert the inner text from the corresponding anchor
	});				
	
    $(".VC-tabModule").tabs();
		
    $(".researchInsights ul li a").wrapInner(document.createElement("span"));
    $(".researchInsights").tabs();

    if (ver < 8.0 && ver > 0) {
        $(".tabs-nav").css("display", "inline-block");
        $(".tabs-nav .tabs-disabled").css({
            'position': 'relative',
            'filter': 'alpha(opacity=40)'
        });
        $(".tabs-nav .tabs-disabled a span").css({
            'height': '23px',
            'min-height': '23px'
        });
    }
	

}

*/
				  
function calculateIframeBodyHeight(iframeElement) {
	  var doc = null;
	  var newHeight = 0;
	  if (iframeElement.contentDocument) { // mozilla
		doc = iframeElement.contentDocument; 
	  } else if (iframeElement.contentWindow) { //ie
		doc = iframeElement.contentWindow.document;
	  } else {
		//error
		return null;
	  }
	  
		if (doc.body.offsetHeight >0) {
			 newHeight = doc.body.offsetHeight + 200 +"px";
			 doc.body.style.height = newHeight;
		  return doc.body;
		}
 }




function applyLinkEvents() {
    $('.documentLink').click(function ($e) {
        $e.preventDefault();
        openNewWindow(this.href);
    });
    $('.externalLink').click(function ($e) {
        $e.preventDefault();
        window.open(this.href);
    });
    $(".printPage").click(function () {
        window.print();
        return false;
    });
    $('.openNewWindow').click(function ($e) {
        $e.preventDefault();
        openNewWindow(this.href);
    });


    $(".rollovermenu a").blur(function () {
        var portalNavHeaders = $(".rollovermenu a.header");
        portalNavHeaders.each(function () {
            $(this).next("ul").css("left", "-9999px");
        });
    });
    $(".rollovermenu li a").focus(function () {
        var elFocus = $(this);
        if (elFocus.hasClass("header")) {
            elFocus.addClass("open");
        } else {
            elFocus.closest("ul").prev("a").addClass("open");
        }
        var portalNavHeaders = $(".rollovermenu a.header");
        portalNavHeaders.each(function () {
            if ($(this).hasClass("open")) {
                if ($(this).next("ul").hasClass("rightToLeft")) {
                    $(this).next("ul").css("left", rightToLeftOffset);
                } else {
                    $(this).next("ul").css("left", "0");
                }
            }
        });
        if (elFocus.hasClass("header")) {
            elFocus.removeClass("open");
        } else {
            elFocus.closest("ul").prev("a").removeClass("open");
        }
    });
	
}

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 formatTable() {
    $(".VC-subChannelSummary").addClass("noFormat stripe");
    stripeTable();
    var tables = $("#VC-mainContent table").not(".noFormat");
    tables.each(function () {
        $("tr td:first-child", this).addClass("firstCol");
        $("tr th:first-child", this).addClass("firstCol");
    });
}

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 resizeFontsFunction(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", "0px -23px");
        $("#VC-fontResizeTool a.defaultFont").css("background-position", "-18px 0px");
        $("#VC-fontResizeTool a.largeFont").css("background-position", "-36px 0px");
    } else if (fontDimension == defaultFontSize) {
        $("#VC-fontResizeTool a.smallFont").css("background-position", "0px 0px");
        $("#VC-fontResizeTool a.defaultFont").css("background-position", "-18px -23px");
        $("#VC-fontResizeTool a.largeFont").css("background-position", "-36px 0px");
    } else if (fontDimension == largeFontSize) {
        $("#VC-fontResizeTool a.smallFont").css("background-position", "0px 0px");
        $("#VC-fontResizeTool a.defaultFont").css("background-position", "-18px 0px");
        $("#VC-fontResizeTool a.largeFont").css("background-position", "-36px -23px");
    }
}

*/

function roundCorners(topColour, bottomColour) {
    $(".roundCorners").not(".rcApplied").each(function () {
        $(this).addClass("rcApplied");
        if (topColour === null) {
            topColour = $(this).css("background-color");
        }
        if (bottomColour === null) {
            bottomColour = $(this).css("background-color");
        }
        var topClassname = "rc" + topColour.replace(/[^a-zA-Z 0-9]+/g, '');
        topClassname = topClassname.replace(/ /g, '');
        var bottomClassname = "rc" + bottomColour.replace(/[^a-zA-Z 0-9]+/g, '');
        bottomClassname = bottomClassname.replace(/ /g, '');
        $(this).before("<b class=\"rc1 " + topClassname + "\"></b><b class=\"rc2 " + topClassname + "\"></b><b class=\"rc3 " + topClassname + "\"></b><b class=\"rc4 " + topClassname + "\"></b>");
        $(this).after("<b class=\"rc4 " + bottomClassname + "\"></b><b class=\"rc3 " + bottomClassname + "\"></b><b class=\"rc2 " + bottomClassname + "\"></b><b class=\"rc1 " + bottomClassname + "\"></b>");
        $("." + topClassname).css("background-color", topColour);
        $("." + bottomClassname).css("background-color", bottomColour);
    });
}

function stripeTable() {
    $("#VC-mainContent table tbody tr:even").addClass("alt");
}

function topTabSpacerRemover() {
    $(".VC-links li .selected").parent("li").prev("li").removeClass("spacer");
    $(".VC-links li a").mouseover(function (event) {
        $(this).parent("li").prev("li.spacer").addClass("spacerRepacement");
        $(this).parent("li").prev("li.spacer").removeClass("spacer");
    });
    $(".VC-links li a").mouseleave(function (event) {
        $(this).parent("li").prev("li.spacerRepacement").addClass("spacer");
    });
}

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;
}



jQuery.cookie = function (key, value, options) {
	
    // key and value given, set cookie...
    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() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    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;
};



function getInternetExplorerVersion() {
    var rv = -1;
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) !== null) {
            rv = parseFloat(RegExp.$1);
        }
    }
    return rv;
}(

function () {
    var m = document.uniqueID && document.compatMode && !window.XMLHttpRequest && document.execCommand;
    try {
        if ( !! m) {
            m("BackgroundImageCache", false, true);
        }
    } catch (oh) {}
})();

function expandCollapseParagraphs() {
    $(".VC-expandCollapse").hide();
    $(".VC-expandCollapse").prev("h4").wrap('<a href="" class="VC-expandCollapseButton" />');
    $(".VC-expandCollapseButton").prepend('<ins>&nbsp;</ins>');
    $(".VC-expandCollapseButton").wrap('<div class="VC-expandCollapseButtonWrapper" />');
    $(".VC-expandCollapseButtonWrapper").prev("h3").addClass("VC-expandCollapseTitle");
    $(".VC-expandCollapseButton").click(function (event) {
        event.preventDefault();
        if ($(this).hasClass("VC-expandCollapseButtonExpanded")) {
            $(this).removeClass("VC-expandCollapseButtonExpanded");
            $(this).parent("div").next(".VC-expandCollapse").hide();
        } else {
            $(this).addClass("VC-expandCollapseButtonExpanded");
            $(this).parent("div").next(".VC-expandCollapse").slideDown('slow');
        }
    })
}

function openpopup(theAtag, optionalParameters) {
    if (!optionalParameters) {
        optionalParameters = "width=800,height=700,scrollbars=yes,toolbar=no,status=yes,directories=no";
    }
    currentLink = theAtag.href;
    window.open(currentLink, 'Popup', optionalParameters);
}

function openNewWindow(currentLink) {
    if (currentLink !== null || currentLink !== 'undefined') {
        window.open(currentLink, '_blank');
    }
} /* Macquarie extensions and utilities */
$.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("This will need to provide some sort of help text");
    }, 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);
    }
} /* Tracking related extensions */

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;
};
if (s && s.pageName && !s.eVar15) {
    s.eVar15 = s.pageName;
}

/*

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('/')
    };
}


