// JavaScript Document

// Global variables
var rightToLeftOffset;

/* jQuery functions to initialize after the DOM is loaded  */
/* but before the page has finished rendering. */
/* $(document).ready() occurs as soon as the DOM is loaded */
$(document).ready(function() {
    	
    if ($("#VC-articleList").length>0) {
			initArticleListPagination();
	}
	
	if ($(".VC-articlepagination").length>0) {
			initNewsArticlePagination();
	}
	

	/* Call setup functions */
	stripeTable();
		
	/* Get the year for the footer */
	getYear();
	
	/* ************************************************** */
	/*                                                    */
	/*  Portal Navigation                                 */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-09-24 */
	/* Requires jquery-1.3.2.js */

	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");
		});
	
	/* ************************************************** */
	/*                                                    */
	/*  Tabs                                              */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-09-24 */
	/* Requires jquery-1.3.2.js and jquery-ui-1.7.2.core+tabs.min.js */
	
	/* Only one module is allowed per page*/
	$("#tab-module").tabs();
	

	
	/* End Tabs*/


	/* ************************************************** */
	/*                                                    */
	/*  Breadcrumb                                        */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-12-02 */
	/* Requires jquery-1.3.2.js and jquery.tooltip-1.3.js */
	
	/* Configuration */
	var breadcrumbStartSlicing = 2; //Transforms an element into ellipsis only after breadcrumbStartSlicingth element
	var breadcrumbEndSlicing = 1; //Does not transforms the last breadcrumbEndSlicing'th elements into ellipsis
	var maxBreadcrumbMaxSize = 120; //If total text size is bigger than ellipsedText the ellipsation of elements is iterated to the following available element
	/* End Configuration */
	
	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();	
	}
	/* End Breadcrumb */


	/* ************************************************** */
	/*                                                    */
	/*  Font resize                                       */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-11-27 */
	/* Requires jquery-1.3.2.js */
	
	/* Configuration*/
	var defaultFontSize = 12;
	var largeFontSize = parseFloat(defaultFontSize, 10) * 1.2;
	var smallFontSize = parseFloat(defaultFontSize, 10) * 0.8;
	/* End Configuration*/
	
	$(".VC-fontResizeTool").css("display","block");
	  
	// Default Font Size
	$(".defaultFont").click(function(){
	resizeFontsFunction(defaultFontSize);
	$.cookie("VCFontResizerSelection", "" + defaultFontSize);
	return false;
	});
	
	// Large Font Size
	$(".largeFont").click(function(){
	resizeFontsFunction(largeFontSize);
	$.cookie("VCFontResizerSelection", "" + largeFontSize);
	return false;
	});
	
	// Extra Large Font Size
	$(".smallFont").click(function(){
	resizeFontsFunction(smallFontSize);
	$.cookie("VCFontResizerSelection", "" + smallFontSize);
	return false;
	});
	
	function resizeFontsFunction(fontDimension){
	$("#VC-pageBody, #VC-breadcrumbs").css('font-size', fontDimension);
	
	// Do not resize:
	$("#VC-pageBody .ui-tabs-nav").css('font-size', defaultFontSize);
	$("#VC-pageBody .noFontResize").css('font-size', defaultFontSize);
	 
	// Change the background
	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");
	}
	}
	
	var currentVCFontSize = $.cookie("VCFontResizerSelection");
	if (currentVCFontSize) {
	  resizeFontsFunction(parseFloat(currentVCFontSize));
	}
	/* End of Font resize*/

	
	/* ************************************************** */
	/*                                                    */
	/*  Portal header for IE                              */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-11-27 */
	/* Requires jquery-1.3.2.js */
	
	var ver = getInternetExplorerVersion();
    // IE 6 and below
	if ( ver < 7.0 && ver > 0 ) {


		var header = null;
        $(".rollovermenu li").hover(function(){
          
		  var dropdown = $(this).children("ul");
		  header = $(this).children("a.header");
		  
		  header.css("background-color","#eae9e9");
		  header.css("color","#000");
		  // Check for last dropdown
		  if ( dropdown.hasClass("rightToLeft") ){
			dropdown.css("left", rightToLeftOffset);
		  }
          else{
		    dropdown.css("left","0");	
		  }
        }, function(){

		  dropdown = $(this).children("ul");
		  header = $(this).children("a.header");

          header.css("background-color","transparent");
		  // Check for current dropdown
		  if(header.hasClass("current")){
		  	header.css("color","#000");
			header.css("background-color","#fff");
		  }
		  else{
		  	header.css("color","#fff");
		  }
		  dropdown.css("left","-9999px");
        });
	}
	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'});		
	}

	
	/* ************************************************** */
	/*                                                    */
	/*  Page tools string                                 */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-11-16  */
		
	$(".VC-pagetools").html('<img class="tooltip printPage" src="http://www.macquarieatlasroads.com/img/print.gif" alt="Printer icon" title="Print this page"/>');	
	/* End - Page tools string                            */
	
		
	/* ************************************************** */
	/*                                                    */
	/*  Thickbox initialization                           */
	/*                                                    */
	/* ************************************************** */
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
	/* End - Thickbox initialization                      */

	/* ************************************************** */
	/*                                                    */
	/* Ddsmoothmenu initialisation                        */
	/*                                                    */
	/* ************************************************** */
	 ddsmoothmenu.init({      
          mainmenuid: "VC-siteWideHeaderRight", //menu DIV id
          orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
          classname: 'VC-siteWideHeaderRight', //class added to menu's outer DIV
          //customtheme: ["#1c5a80", "#18374a"],
          contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
      });
	/* End - ddsmoothmenu initialization                  */


	/* ************************************************** */
	/*                                                    */
	/* Add Icons                                          */
	/*                                                    */
	/* ************************************************** */
	$(".documentLink").prepend("<span class='documentLinkIcon'> </span>");
	$(".externalLink").append("<span class='externalLinkIcon'> </span>");
	
});
/* End of $(document).ready() */




/* jQuery functions to initialize after the page has loaded. */
/* $(window).load event occurs after all objects called by   */
/* the HTML (including <iframe> content) have downloaded.    */
$(window).load(function(){

	/* ************************************************** */
	/*                                                    */
	/*  Documents and External Links. Open in new window  */
	/*                                                    */
	/* ************************************************** */
	/* Created 2009-12-16 */
	/* Requires jquery-1.3.2.js */

	$('.documentLink').click(function($e){
		$e.preventDefault();
		window.open(this.href);
	});

	$('.externalLink').click(function($e){
		$e.preventDefault();
		window.open(this.href);
	});
	
	
	/* ************************************************** */
	/*                                                    */
	/*  Tooltips                                          */
	/*                                                    */
	/* ************************************************** */
	/* Created 2009-09-24 */
	/* Requires jquery-1.3.2.js and jquery.tooltip-1.3.js  */
	
	$(".tooltip").tooltip({
	  track: true,
	  delay: 500,
	  showURL: false,
	  showBody: " - ",
	  fade: 250
	});

	/* End Tooltips*/

	
	/* ************************************************** */
	/*                                                    */
	/*  Table sorter                                      */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-10-1 */
	/* Requires jquery-1.3.2.js and jquery.tablesorter.js */
	$(".productComparison").tablesorter();
	/* End sorter script*/


	/* ************************************************** */
	/*                                                    */
	/*  Page Tools                                        */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-10-1 */
	/* Requires jquery-1.3.2.js */
	
	$(".printPage").click(function(){
	  window.print();
	  return false;
	});
	/* End Page Tools*/


	/* ************************************************** */
	/*                                                    */
	/*  Keyboard Tab for Primary Navigation               */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-10-1 */
	/* Requires jquery-1.3.2.js */
	
		
    /* Close all the portal navigation dropdown menus when the header link or a sub-header link lose focus*/
	$(".rollovermenu a").blur(function(){
		var portalNavHeaders = $(".rollovermenu a.header");
		portalNavHeaders.each(function(){
		  $(this).css( {'background-color' : 'transparent', color : '#fff'} );
		  if ($(this).hasClass('overview') ){
		  	$(this).css("color", "#000");
		  }
          $(this).next("ul").css("left","");
	    });
	});

	/* Open the portal navigation dropdown menus when the header link or a sub-header link have focus */
	$(".rollovermenu a").focus(function(){
		var elFocus = $(this);
		
		/* Add open class to identify the open dropdown menu */
		if (elFocus.hasClass("header")){ /* Header link has focus */
			elFocus.addClass("open");
		}
		else { /* sub-header link has focus */
			elFocus.closest("ul").prev("a").addClass("open");
		}
		
		var portalNavHeaders = $(".rollovermenu a.header");
		portalNavHeaders.each(function(){
			if ($(this).hasClass("open") ){
			  /* Change the background */
			  $(this).css( {'background-color' : '#eae9e9', color : '#000'} );
			  /* Move the sub-header links into view */
			  if ( $(this).next("ul").hasClass("rightToLeft") ){ /* Last header link */
			  	$(this).next("ul").css("left", rightToLeftOffset);
			  }
	          else{
			  	$(this).next("ul").css("left", "0");
			  }
	        }
	    });
		
		/* Remove the open class so it wont remain open when another dropdown menu is opened */
		if (elFocus.hasClass("header")){
			elFocus.removeClass("open");
		}
		else {
			elFocus.closest("ul").prev("a").removeClass("open");
		}
	});

	
	/* ************************************************** */
	/*                                                    */
	/*  Expanded and Collapsed content                    */
	/*                                                    */
	/* ************************************************** */
	/* Updated 2009-10-1 */
	/* Requires jquery-1.3.2.js and jquery.tooltip-1.3.js */
	
	var expandedImage = "../img/collapse.gif";
	var collapsedImage = "../img/expand.gif";
	var expandText = "Expand - Click here to expand";
	var collapseText = "Collapse - Click here to collapse";
	var slideFunction = true;
	
	/*Image precaching*/
	var images = [collapsedImage, expandedImage];
	jQuery.each(images, function(i){
	  images[i] = new Image();
	  images[i].src = this;
	});
	/*End image precaching*/
	
	$(".expandcollapse").prepend("<img align='right' class='csMenuImage' src='" + collapsedImage + "' >");
	$(".contactUs .actionButton img").tooltip({
	  track: true,
	  delay: 0,
	  showURL: false,
	  showBody: " - ",
	  fade: 250
	});
	var cssObj = {
	  'cursor': 'pointer',
	  'padding-top': '3px'
	};
	$(".expandcollapse .csMenuImage").css(cssObj);
	if (/safari/.test(navigator.userAgent.toLowerCase()) && !/chrome/.test(navigator.userAgent.toLowerCase())) {
			slideFunction = false;
		}
	$(".expandcollapse .csMenuImage").attr("title", collapseText);
	if (slideFunction) {
			$(".expandcollapse .csMenuImage").tooltip({
				track: true,
				delay: 0,
				showURL: false,
				showBody: " - ",
				fade: 250
			});
		} else {
			$(".expandcollapse .csMenuImage").tooltip({
				track: true,
				delay: 0,
				showURL: false,
				showBody: " - "
			});
		}
	$(".csMenuImage").click(function(event){
	  event.preventDefault();
	  if ($(this).attr("src").indexOf(expandedImage) == -1) {
	    collapseElement($(this));
	  } else {
	    expandElement($(this));
	  }
	});
	
	function collapseElement(el){
	  el.attr({
	    src: expandedImage,
	    title: "Expand",
	    alt: "Expand menu"
	  });
	  el.attr("title", expandText);
	  if (slideFunction) {
	    el.tooltip({
	      track: true,
	      delay: 500,
	      showURL: false,
	      showBody: " - ",
	      fade: 250
	    });
	    el.parent("div").next("div").slideUp("50");
	  } else {
	    el.tooltip({
	      track: true,
	      delay: 500,
	      showURL: false,
	      showBody: " - "
	    });
	    el.parent("div").next("div").hide();
	  }
	}
	
	function expandElement(el){
	  el.attr({
	    src: collapsedImage,
	    title: "Close",
	    alt: "Close menu"
	  });
	  el.attr("title", collapseText);
	  if (slideFunction) {
	    el.tooltip({
	      track: true,
	      delay: 500,
	      showURL: false,
	      showBody: " - ",
	      fade: 250
	    });
	    el.parent("div").next("div").slideDown("50");
	  } else {
	    el.tooltip({
	      track: true,
	      delay: 500,
	      showURL: false,
	      showBody: " - "
	    });
	    el.parent("div").next("div").show();
	  }
	}
	/* End Expanded and Collapsed content */		

	

});
/* End of $(window).load() */




/* JavaScript Functions */

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;
};

/* ************************************************** */
/*                                                    */
/*  Round Corners                                     */
/*                                                    */
/* ************************************************** */
/* Updated 2009-10-16 */
/* Requires jquery-1.3.2.js */

/* Adds round corners to any element with class roundCorners */
function roundCorners(topColour, bottomColour){
  $(".roundCorners").not(".rcApplied").each(function(){
    
	// Mark div as having round corner already applied
    $(this).addClass("rcApplied");
    
	// If the top and bottom colours are not given use the background colour
    if (topColour === null) {
      topColour = $(this).css("background-color");
    }
    
	if (bottomColour === null) {
      bottomColour = $(this).css("background-color");
    }
    
	// Calculate a unique class name for the top and bottom round corners, based on the colour.
    // Remove all non alphanumeric characters and whitespaces
    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, '');
    
	// apply the round corners
    $(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>");
    
	// apply the colour
    $("." + topClassname).css("background-color", topColour);
    $("." + bottomClassname).css("background-color", bottomColour);
  });
}
/* End Round Corners */


/* ************************************************** */
/*                                                    */
/* Stripe Table                                      */
/*                                                    */
/* ************************************************** */
/* Updated 2009-26-10 */
/* Requires jquery-1.3.2.js */

/* Applies stripes to the odd table row */
/* Does not applies stripes tables with a class noStripes  */
function stripeTable(){
  
  var el = $("#VC-mainContent table").not(".noStripes");
  
  el.each(function(){
	$("tr:odd", this).removeClass("even").addClass("odd");
	$("tr:even", this).removeClass("odd").addClass("even");
  });
}
/* End Stripe Table */


/* ************************************************** */
/*                                                    */
/*  Setup Lightbox                                    */
/*                                                    */
/* ************************************************** */
/* Updated 2009-26-10 */
/* Requires jquery-1.3.2.js */

function setupLightbox(){

  var lightboxes = $(".VC-modalLightbox");

  lightboxes.each(function(){

    // Check if the lightbox setup has been applied already
    if (!$(this).hasClass("setupApplied")) {

      // Add the round corners class
      $(this).addClass("roundCorners setupApplied");

      // Add the Lightbox body div    
      $(this).wrapInner($("<div class='modalBody'></div>"));

      // Add the Lightbox header, close button and decoration banner    
      $(this).prepend("<div class='modalHeader'><div class='modalLogo'></div><a class='modalCloseBt' href='#'></a></div><div class='modalDecorBanner'></div>");

      // Add the close event to the close button
      $(".modalCloseBt").click(tb_remove);

      // Add the roundCorners 
      roundCorners('#2D2D2D', '#ffffff');

      // Set the #TB_ajaxContent height to 100% so the  
      // lightbox will grow with the content of the box 
      $("#TB_ajaxContent").css("height", "100%");
    }
  });
}
/* End Lightbox */


/* ************************************************** */
/*                                                    */
/*  Setup Login Lightbox                              */
/*                                                    */
/* ************************************************** */
/* Updated 2009-26-10 */
/* Requires jquery-1.3.2.js */

function setupLoginLightbox(){

  // Set color for the adviser list background
  $("#VC-loginLightbox .adviser li").mouseover(function(){
    $(this).css("background-color", "#003366");
  });
  
  // Set color for the business list background
  $("#VC-loginLightbox .business li").mouseover(function(){
    $(this).css("background-color", "#666633");
  });
  
  // Set color for the corporate list background
  $("#VC-loginLightbox .corporate li").mouseover(function(){
    $(this).css("background-color", "#333333");
  });
  
  // Return the background colour to default
  $("#VC-loginLightbox li").mouseout(function(){
    $(this).css("background-color", "#5B5B5B");
  });
  
  // Add Tooltip
  $("#VC-loginLightbox a").tooltip({
    track: true,
    delay: 500,
    showURL: false,
    fade: 250
  });
}
/* End Setup Login Lightbox */


/* ************************************************** */
/*                                                    */
/*  Setup Sitewide Login Lightbox                     */
/*                                                    */
/* ************************************************** */
/* Updated 2009-26-10 */
/* Requires jquery-1.3.2.js */

/* Sets up the login lightbox */
function setupSwLoginLightbox(){
  
  // Hide the Application Links     
  var appsList = $(".appsList");
  appsList.hide();
  
  // Toggle between the Application Links
  $(".appsLink").click(function(){
    var all = $(".appsList");
    var selected = $(this).next();
    
	// Run on all browsers bar IE6    
    var ver = getInternetExplorerVersion();
    if ( ver < 7.0 && ver > 0 ) {
		// Do nothing if IE 6 or less
	}
	else{   
		// Get the height of the opening div 
	    $(this).next().css('display', 'block');
	    var openingDivHeight = $(this).next().height();
	    $(this).next().hide();
	    
		// Get the height of the closing div
	    var closingDivHeight = all.filter('.selected').height();
	    // First time there is no Div to close
		if (null == closingDivHeight) {
		  closingDivHeight = 0;
		  // Change the #TB_window top for IE 7+ 
		  if( ver <= 7.0 ){
		  	$("#TB_window").css("top", $(window).height() / 2);
		  }
	    }
	   
	    // Calculate the height we need to move the lightbox in-order to keep it centred
	    var offsetHeight = (closingDivHeight - openingDivHeight) / 2;
	    
		// Chrome and Safari return a % for top, This must be converted to px
	    if ($("#TB_window").css("top") == "50%") {
	      $("#TB_window").css("top", $(window).height() / 2);
	    }
	    
		// Move the lightbox into the centre
	    $("#TB_window").animate({
	      "top": "+=" + offsetHeight
	    }, "slow");
	
    }

    all.removeClass('selected');
    $(selected).addClass('selected');
    all.filter(':not(.selected)').slideUp("slow");
    $(selected).slideDown("slow");
    return false;
  });
}
/*  End Setup Sitewide Login Lightbox */


/* ************************************************** */
/*                                                    */
/*  Article List Pagination                           */
/*                                                    */
/* ************************************************** */
/* Updated 2009-09-24 */
/* Requires jquery-1.3.2.js */

/* This function Generates the pagination */

/* variables */
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;

function renderList(){
  // Hide all the list
  if (list) {
    list.css("display", "none");
    // Show only the required list items
    for (i = 1; i <= articlesPerPage; i++) {
      list.eq(listItem).css("display", "list-item");
      listItem++;
    }
  }
}

function generatePagination(){
  // Dont start moving the pagination until the currentPage 
  // is greater than half the pagination limit
  if (currentPage <= Math.ceil(paginationLimit / 2)) {
    startPage = 0;
  } else {
    startPage = currentPage - Math.ceil(paginationLimit / 2);
  }

  container.empty();

  var html = "";
  var className = "";

  // Generate the pagination
  if (startPage >= 0 && startPage <= numOfPages) {
    html = "<div>";

    // Add the previous arrows
    if (currentPage > 0) {
      // First page
      html += "<a class='arrows firstPage' href='#VC-header' title='Click here to go to the first page'>\<\<</a>";
      // Previous page
      html += "<a class='arrows previousPage' href='#VC-header' title='Click here to go to the previous page'>\< previous</a>";
    }

    // Generate the page numbers
    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) {
        // Record the current page class
        className = ".page" + currentPage.toString();
      }
      if (i == numOfPages) {
        break;
      }
    }

    // Add the next arrows 
    if (currentPage < numOfPages) {
      // Next page
      html += "<a class='arrows nextPage' href='#VC-header' title='Click here to go to the next page'>next \></a>";
      // Last page
      html += "<a class='arrows lastPage' href='#VC-header' title='Click here to go to the last page'>\>\></a>";
    }
    html += "</div>";

    // Add dropdown menu
    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);
  }
  blindPaginationEvents(generatePagination);
}

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 blindPaginationEvents(fnToInvoke){
  // Bind the events to the First Page arrows
  $("#VC-pagination a.firstPage").bind("click", function(e){
    // Reset variables
    currentPage = 0;
    listItem = 0;
    renderList();
    fnToInvoke();
  });

  // Bind the events to the Previous Page arrow
  $("#VC-pagination a.previousPage").bind("click", function(e){
    // Reset variables
    currentPage -= 1;
    listItem = currentPage * articlesPerPage;
    renderList();
    fnToInvoke();
  });

  // Bind the events to the Next Page arrow
  $("#VC-pagination a.nextPage").bind("click", function(e){
    // Reset variables
    currentPage += 1;
    renderList();
    fnToInvoke();
  });

  // Bind the events to the Last Page arrows
  $("#VC-pagination a.lastPage").bind("click", function(e){
    // Reset variables
    currentPage = numOfPages;
    listItem = (currentPage * articlesPerPage);
    renderList();
    fnToInvoke();
  });

  // Bind the events to the Page Numbers
  $("#VC-pagination a.pageLink").bind("click", function(e){
    // Reset variables
    currentPage = parseInt($(this).text()) - 1;
    listItem = (currentPage * articlesPerPage);
    renderList();
    fnToInvoke();
  });

  // Bind the events to the Dropdown
  $("#VC-pagination select").change(function(){
    // Return view Back to Top
    $('html, body').animate({
      scrollTop: '0'
    }, 0);
    // Reset variables
    currentPage = 0;
    listItem = 0;
    articlesPerPage = $(this).val();
    numOfPages = Math.ceil(numOfArticles / articlesPerPage) - 1;
    renderList();
    fnToInvoke();
  });
}

// Add Tooltip
/*  $("#VC-pagination a").tooltip({
 track: true,
 delay: 500,
 showURL: false,
 fade: 250
 });*/
/* End of Article List Pagination */


/* ************************************************** */
/*                                                    */
/*  Get Year, format YYYY                             */
/*                                                    */
/* ************************************************** */
function getYear(){
	var d=new Date();
	$(".year").text(d.getFullYear() + " ");
}

/* ************************************************** */
/*                                                    */
/*  Calculate Last Drop-down offset                   */
/*                                                    */
/* ************************************************** */
/*** @param {Object} el Is the parent element containing the drop-down */
function getRightToLeftOffset(el){

  var dropdown = el.children("ul");
  // -1 is for the li boarder
  var offset = el.width() - dropdown.width() - 1;   

  return  offset < 0 ? offset : 0;
}


/* ************************************************** */
/*                                                    */
/*  Cookies                                           */
/*                                                    */
/* ************************************************** */
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 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
 *
 */
/**
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options){
  if (typeof value != 'undefined') { // name and value given, set cookie

    options = options ||
    {};
    if (value === null) {
      value = '';
      options.expires = -1;
    }
    var expires = '';
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
      var date;
      if (typeof options.expires == 'number') {
        date = new Date();
        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
      } else {
        date = options.expires;
      }
      expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
    }
    // CAUTION: Needed to parenthesize options.path and options.domain
    // in the following expressions, otherwise they evaluate to undefined
    // in the packed version for some reason...
    var path = options.path ? '; path=' + (options.path) : '';
    var domain = options.domain ? '; domain=' + (options.domain) : '';
    var secure = options.secure ? '; secure' : '';
    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } else { // only name given, get cookie

    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
};
/* End of Cookies */


/* ************************************************** */
/*                                                    */
/*  Get Internet Explorer Version                     */
/*                                                    */
/* ************************************************** */
/* Updated 2009-11-04 */

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  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;
}
/* End - Get Internet Explorer Version                */


/* ************************************************** */
/*                                                    */
/*  IE 6 hack                                         */
/*                                                    */
/* ************************************************** */
/* Updated 2009-10-07 */

/* Cache background images to stop IE Image flicker */
(function(){ /*Use Object Detection to detect IE6*/
  var m = document.uniqueID /*IE*/ && document.compatMode /*>=IE6*/ && !window.XMLHttpRequest /*<=IE6*/ && document.execCommand;
  try {
    if (!!m) {
      m("BackgroundImageCache", false, true); /* = IE6 only */
    }
  } catch (oh) {
  }
  
})();
/* IE 6 hack */


/* ************************************************** */
/*                                                    */
/*  News Article/Press release pagination             */
/*                                                    */
/* ************************************************** */
/* Updated 2009-11-20 */

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 navigateNewsArticlePagination(){
	var paginatedArticles = $(".VC-articlepagination .VC-articlePage");
		container = $("#VC-pagination");	
		var html = "<div>";
		
		container.empty();
		
		// Change the page		
		paginatedArticles.hide();
		paginatedArticles.slice(currentPage,currentPage+1).show();
		
		// Add the previous arrows		
		if (currentPage > 0) {
		  // First page
		  html += "<a class='arrows firstPage' href='#VC-header' title='Click here to go to the first page'>\<\<</a>";
	
		  // Previous page
		  html += "<a class='arrows previousPage' href='#VC-header' title='Click here to go to the previous page'>\< previous</a>";
		}
		
		// Add the next arrows 
		if (currentPage < paginatedArticles.length-1) {
		  // Next page
		  html += "<a class='arrows nextPage' href='#VC-header' title='Click here to go to the next page'>next \></a>";
	
		  // Last page
		  html += "<a class='arrows lastPage' href='#VC-header' title='Click here to go to the last page'>\>\></a>";
		}
		
		html += "</div>";
		
		container.append(html);
		
		$(".pagePaginationCount").html("|  Page " + (Number(currentPage+1)) + " of " + paginatedArticles.length);
				
		blindPaginationEvents(navigateNewsArticlePagination);
}
/* End - News Article/Press release pagination  */

/* ************************************************** */
/*                                                    */
/*  Omniture JS - Addons                              */
/*                                                    */
/* ************************************************** */
/* Updated 2009-12-04 */

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; 
	s.tl(this,'o',calculatorName);	
}

function om_download(downloadName){
	var s=s_gi(s_account); 
	s.linkTrackVars='eVar14,events'; 
	s.linkTrackEvents='event7'; 
	s.events='event7'; 
	s.eVar14=downloadName; 
	s.tl(this,'d',downloadName);	
}
	
	
/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>  <a href='#'>Next ></a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>  <a href='#'>< Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='utilities_cs.js' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
						setupLightbox();
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
						setupLightbox();
					}
				}else{
					// Only include the html in the #VC-modalLightbox div
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()) + " #VC-modalLightbox",function(){//to do a post change this load method
						setupLightbox();
						setupLoginLightbox();
						
						// Setup the sitewide login only if the swLogin=true parameter is in the url
						if (url.indexOf("swLogin=true") != -1 ){
						  setupSwLoginLightbox();
						}
						
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() { 
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

/* image gallery */
$(document).ready(function() {
	var links = $("a");
	for (var i=0; i<links.length; i++) {
		var linkurl = links[i].getAttribute("href");
		var currenturl = window.location.href;
		if(currenturl.indexOf(linkurl) != -1) {
			links[i].className = "here";
		}
	}
/* Add pdf icons to pdf links
	$("a[href$='.pdf']").addClass("pdf");
 
	// Add txt icons to document links (doc, rtf, txt)
	$("a[href$='.doc'], a[href$='.txt'], a[href$='.rft']").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').filter(function() {
		//Compare the anchor tag's host name with location's host name
	    return this.hostname && this.hostname !== location.hostname;
	  }).addClass("ext");
	//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;
	  }).addClass("external").attr("target", "_blank");
	*/
});

