/**
 * FIX IE6 IMAGE FLICKER PROBLEM
 *
 */
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}


$(document).ready(Init);

function Init()
{
	// External links
	ExternalLinks();

	// PDF links
	PDFMediaLinks();

	// Print-friendly
	PrintFriendly();

	// Text resizing
	TextResize();

	// Question / response teaser
	QuestionResponseTeaser();

	// Choose your country
	ChooseYourCountry();

	// News/events/careers listing
	NewsEventsCareersListing();

	// Search tips
	SearchTips();

	//Js added for Advisor page
	AdvisorContentPanels();
	$('div.AdvisorContentPanel[@id="AdvisorContentPanel-tab2"]').hide();
	// Photo & AV gallery
	//PhotoAVGallery();

	// Tertiary links (country pages)
	$('#tertiary').show();

	// Primary headers when shown with banner.
	if($('#banner').size() > 0 && $('#banner iframe').size() < 1)
	{
		$('#content-body h1:first').prependTo('#banner');
	}

	// Fix hover issue when primary nav. item is in lit state
	$('#primary li a.lit').hover(
		function() {
			$(this).children('table').children('tbody').children('tr').children('td').children('ul').show();
		},
		function() {
			$(this).children('table').children('tbody').children('tr').children('td').children('ul').hide();
		}
	);

	$('a[@rel="popup"]').click(OpenWindow);

	//invert floatee
	// invertFloatee();
	//Build link for Language Toggle
	LanguageToggle();
}


/*
PDF media links
*/
function PDFMediaLinks()
{
	$("a[@rel='pdf']").each(function(i){
		$('<img alt="PDF" height="14" width="12" src="/static/global/images/icons/pdf.gif" style="vertical-align:bottom;" />').insertAfter(this);
	});
}



/*
External links
*/
function ExternalLinks()
{
	$("a[@rel='external']").each(function(i){
		$(this).click(function(e){
			return confirm("Do you want to visit this third-party Web site?");
		});
	});
}

function PrintFriendly()
{
	// Display the printer button.
	$("#print-page").show();

	function _langStrings(tag)
	{
		var lang_en = {
			printpage : 'Print',
			closepage : 'Close'
		};

		var lang_fr = {
			printpage : 'Imprimer',
			closepage : 'Fermer'
		};

		return ($('#wrapper').attr('class') == 'en') ? lang_en[tag] : lang_fr[tag] ;
	}

	$("#print-page a").click(function(e){
		

		var header = document.getElementById("header").innerHTML;
		var breadcrumb = document.getElementById("breadcrumb").innerHTML;
	  	var content_vlue =  document.getElementById("content").innerHTML;
		var footer =  document.getElementById("footer").innerHTML;
   
    
	  	var docprint=window.open('', 'PrintFriendly', 'location=0,directories=0,status=0,scrollbars=1,resizable=1,width=800,height=600');

		docprint.document.open();
		docprint.document.write('<html><head><title>'+ document.title +'</title>');
		docprint.document.write('<link rel="stylesheet" href="/static/plan/Stylesheets/plan_content_overwrite.css" type="text/css" />');
		docprint.document.write('<link rel="stylesheet" href="/static/plan/Stylesheets/plan_override.css" type="text/css" />');
		docprint.document.write('<link rel="stylesheet" href="/static/global/styles/print.css" type="text/css" media="screen" />');
		docprint.document.write('<link rel="stylesheet" href="/static/global/styles/print_hidenav.css" type="text/css" media="print" />');
		docprint.document.write('<link rel="stylesheet" href="/static/global/styles/print.css" type="text/css" media="print" />');
		docprint.document.write('</head><body>');
		docprint.document.write('<style type="text/css">#left {display: none} body ul {list-style-type:none}</style>');
		
		docprint.document.write('</head><body><div class="en" id="wrapper">');
		docprint.document.write('<div id="header">'+header+'</div>');
		docprint.document.write('<div id="breadcrumb">'+breadcrumb+'</div>');
		docprint.document.write(content_vlue);
		
		if(document.getElementById("content-sidebar")!= null)
		{
    			var content_side = document.getElementById("content-sidebar").innerHTML;
    			docprint.document.write(content_side);
   		}

		docprint.document.write('<div id="printpagenav" style="position:absolute;top:160px;right:0;padding:10px;">');
		docprint.document.write('<a href="javascript:self.print();" id="printpage">' + _langStrings('printpage') + '</a>');
		docprint.document.write('&#160;|&#160;');
		docprint.document.write('<a href="javascript:self.close();" id="closepage">' + _langStrings('closepage') + '</a>');
		docprint.document.write('</div>');
		docprint.document.write('</div>');
		docprint.document.write('</body></html>');
		docprint.document.close();
		docprint.focus();

		return false;

	});
}

/*
Text resizing
*/
function TextResize()
{
	// Display the three text size buttons.
	$("#text-small").show();
	$("#text-medium").show();
	$("#text-large").show();

	// Small
	$("#text-small a").click(function(e){
		setActiveStyleSheet("small");
		return false;
	});

	// Medium
	$("#text-medium a").click(function(e){
		setActiveStyleSheet("medium");
		return false;
	});

	// Large
	$("#text-large a").click(function(e){
		setActiveStyleSheet("large");
		return false;
	});
}



/*
Question / response teaser
*/
function QuestionResponseTeaser()
{
	$("div.feature div.question-response-teaser").each(function(i){

		var oldSelectedIndex = 0;
		var curSelectedIndex = 0;

		// Display information box based on the selected index.
		$("select", this).change(function(e){
			curSelectedIndex = this.selectedIndex;

			if(curSelectedIndex != oldSelectedIndex)
			{
				$(this).parent().parent().children("div.response:eq("+ oldSelectedIndex + ")").queue(function(){
					$(this).hide();
					$(this).parent().children("div.response:eq(" + curSelectedIndex + ")").show();
					$(this).dequeue();
				});

				oldSelectedIndex = curSelectedIndex;
			}
		});

	});
}



/*
Rotating billbords
*/
var Billboards = {
	numBillboards : 0,
	currBillboard : 0,
	nextBillboard : 0,
	delay : 6,	// seconds
	mode : 'rotate',	// rotate | random

	init : function(mode) {
		var obj = this;

		this.numBillboards = $('#billboard img').size();
		this.mode = (mode == 'random') ? 'random' : 'rotate';

		switch(this.mode)
		{
			case 'random':
				this.randomBillboard();
				break;

			case 'rotate':
				$('#billboard img:gt(0)').css({opacity: 0});
				setTimeout(function(){obj.rotateBillboard();}, this.delay * 1000);
				break;
		}
	},

	rotateBillboard : function() {
		var obj = this;

		this.nextBillboard = this.currBillboard + 1;

		// If current banner is last in list, we need to fade in the first
		// banner in the list.
		if(this.nextBillboard >= this.numBillboards)
		{
			this.nextBillboard = 0;
		}

		// Fade current banner out, next banner in.
		$('#billboard img:eq(' + this.nextBillboard + ')').animate({opacity: 1}, 3000).css({zIndex: 10});
		$('#billboard img:eq(' + this.currBillboard + ')').animate({opacity: 0}, 3000).css({zIndex: 5});

		this.currBillboard++;

		// At last banner, re-loop through list.
		if(this.currBillboard >= this.numBillboards)
		{
			this.currBillboard = 0;
		}

		setTimeout(function(){obj.rotateBillboard();}, this.delay * 1000);
	},

	randomBillboard : function() {
		var randomBillboardID = Math.floor(Math.random() * this.numBillboards);
		$('#billboard img:eq(' + randomBillboardID + ')').css({zIndex: 10});
	}
};



/*
Rotating banners
*/
function RotatingBanners()
{
	$("#banner div.banner-content:first").hide();

	var numBanners = $("#banner div.banner-content").size();
	var rdmBanner = Math.floor(Math.random() * numBanners);

	$("#banner div.banner-content:eq(" + rdmBanner + ")").show();
}



/*
Choose your country
*/
function ChooseYourCountry()
{
	$("#choose-country").hover(
		function(){
			if($("#choose-country-content:visible").size() < 1)
			{
				$("#choose-country-content").show();
				/*
				Hide the <select> menu (if applicable) in the first feature box on the
				right-hand column to fix the annoying IE6 bug where the dropdown is
				visible.
				*/
				$('#content-sidebar div.feature:first select').css('visibility', 'hidden');
			}
		},
		function() {
			$("#choose-country-content").hide();
			$('#content-sidebar div.feature:first select').css('visibility', 'visible');
		}
	);

	$("#choose-country-content").hover(
		function() {
			$("#choose-country-content").show();
			$('#content-sidebar div.feature:first select').css('visibility', 'hidden');
		},
		function(){
			$("#choose-country-content").hide();
			$('#content-sidebar div.feature:first select').css('visibility', 'visible');
		}
	);
}

/*
Open a new window.
*/
function OpenWindow()
{
	var newWin = window.open($(this).attr('href'), 'SLF', 'height=600,width=800,resizable=yes,scrollbars=yes,status=no');

	return false;
}

/*
News/events/careers listing

For each listing of news, events or careers, ensure that the last list item
receives a class of "last" to remove the background gradient and dotted line.
*/
function NewsEventsCareersListing()
{
	$("dl.news-listing").each(function(i){
		$("dd:last", this).addClass("last");
	});
}


/*
Inverts the editing option of the Vignette floatee
*/

function invertFloatee(){
	var divContent = document.getElementById("floatline2");
	var aTag = divContent.getElementsByTagName("a");
	aTag[0].onclick = function() {
		var urlString = window.location.href;
		if(urlString.indexOf("editflag=on") > 0){
			var temp = aTag[0].href;
			temp = temp.replace("editflag=on","editflag=off");
			aTag[0].href = temp;
		}else if(urlString.indexOf("editflag=off") > 0){
			var temp = aTag[0].href;
			temp = temp.replace("editflag=off","editflag=on");
			aTag[0].href = temp;
		}else{
			aTag[0].href = aTag[0].href+"&editflag=on";
		}
		return true;
	}
}




/**
 * Popup Overlay
 *
 * Grabs URL within anchor tag and loads the page, filtering out all
 * content except what has been provided as an anchor target.
 *
 * i.e. <a href="popuppage.html#targetID"> ... </a>
 *
 */
var PopupOverlay = {
	offsetToTop : 0,
	offsetOfElement : 0,
	popupID : '',
	status : false,

	init: function(id) {
		var obj = this;

		$('<div id="overlay"></div>').appendTo('body');
		$('#overlay').css({
			height: $(document).height() + 'px',
			width: $(window).width() + 'px'
		});

		this.popupID = (id !== '') ? id : 'PopupDefault';

		//$(window).scroll(this._offset);
		$(window).resize(function(){
			$('#overlay').css({
				height: $(document).height() + 'px',
				width: $(window).width() + 'px'
			});

			obj._offset();
		});

		this.status = true;

		$('<div class="popup"></div>').attr('id', this.popupID).appendTo('body');

		/*
		"Anywhere" click closing function.
		*/
		$('#overlay').click(function(){
			obj.close('obj.init');
		});
	},

	loadContent: function(e) {
		$('div.popup').html(e).show();
		this._offset();
	},

	close: function(evtfunc) {
		$('div.popup').remove();
		$("#overlay").remove();

		this.status = false;

		$(document).unbind('keydown', evtfunc);

		return false;
	},

	loadMessage: function() {
		$('div.popup').html('<p class="tcenter"><strong>Loading... please wait.</strong></p>')
		$('div.popup').show();

		this._offset();
	},

	_offset: function() {
		this.offsetToTop = $(window).scrollTop();
		this.offsetOfElement = parseInt(($(window).height() - $('div.popup').height()) / 2);
		$('div.popup').css('top', parseInt(this.offsetToTop + this.offsetOfElement) + 'px');
	}
};



/*
Search tips
*/
function SearchTips()
{
	// Ensure search tips exists; otherwise end function.
	if($("#ftr-searchtips").size() < 1)
	{
		return false;
	}

	// On page load, ensure search tips are hidden.
	$("#ftr-searchtips").hide();

	// Setup "serach tips" button click event.
	$("div.banner-search #search-tips").click(function(e){
		$("#ftr-searchtips").fadeIn("medium");
		return false;
	});
}



/*
Photo & AV gallery
This functinality has been disabled.
*/
function PhotoAVGallery()
{
	// Ensure photo & AV gallery exists; otherwise end function.
	if($("div.ftr-photo-av-gallery").size() < 1)
	{
		return false;
	}

	// Go through list of thumbnail and attach appropriate icon for the
	// media type it matches.
	$("div.ftr-photo-av-gallery div ul a").each(function(i){
		$(this).after('<span class="icon '+ $(this).attr("rel") + '"></span>');
	});
}



/*
Our history
*/
function OurHistory()
{
	// Hide all but first set of historical facts.
	$("#ftr-our-history ul.our-history:gt(0)").hide();

	// Setup click events for various year segments.
	$("#ftr-our-history ul.clearfix a").each(function(i){
		$(this).click(function(e){
			// Hide/show historical facts.
			$("#ftr-our-history ul.our-history").hide();
			$("#ftr-our-history ul.our-history:eq(" + i + ")").show();

			// Toggle navigation item on/off.
			$("#ftr-our-history ul.clearfix a").removeClass("lit");
			$(this).addClass("lit");

			return false;
		});
	});
}



/*
Global Presence Content Panel
*/
function ContentPanels()
{
	// Scan for "imcoming" content panel request; if none, revert to first.
	if($('#tertiary li a[@href="'+ location.hash +'"]').size() > 0)
	{
		ChangePanel(location.hash.substr(1));
	}
	else
	{
		$('div.contentpanel:gt(0)').hide();
	}

	function ChangePanel(tab)
	{
		$('div.contentpanel').hide();
		$('div.contentpanel[@id="contentpanel-' + tab + '"]').show();
		$('#tertiary li a').removeClass('lit');
		$('#tertiary li a[@href="#'+tab+'"]').addClass('lit');
	}

	// Setup click event for each tab.
	$('#tertiary li a').click(function(e){
		ChangePanel($(this).attr('href').substr(1));
		return false;
	});
}



var PhotoGallery = {
	// Number of photos in the gallery.
	_numPhotosInGallery : 0,

	// Current (selected) photo in the gallery.
	_currPhotoInGallery : 0,

	// Current photo gallery
	_currGallery : 0,

	_currLang : '',


	init : function(e) {this._langStrings('previous');
		// Determine parent of gallery.
		this._currGallery = $(e).parents('div.box');

		this._numPhotosInGallery = $('a[@rel="photo"]', this._currGallery).size();
		this._currPhotoInGallery = (e) ? $('a[@rel="photo"]', this._currGallery).index(e) : 0;

		// Retrieve the current language, as set on our wrapper DIV.
		this._currLang = $('#wrapper').attr('class');

		PopupOverlay.init('PhotoGallery');
		PopupOverlay.loadContent(this._buildTemplate());

		/*
		Setup events for closing the photo gallery.
		*/
		$('#PhotoGallery_Banner a').click(function(e){
			return PopupOverlay.close();
		});
		$(document).bind('keydown', function ClosePopup(e){
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			(key == 27) ? PopupOverlay.close(ClosePopup) : false;
		});

		this.loadImage(this._currPhotoInGallery, this._currGallery);
		this._initNavigation();
		this._navigationControls();
	},

	loadImage : function(imgID) {

   		var newImg = $(document.createElement('img')).attr('src', $('a[@rel="photo"]', this._currGallery).eq(imgID).attr('href')).appendTo('#PhotoGallery_Image').css({opacity: 0}).load(FadeInOutImage);

   		function FadeInOutImage()
   		{
   			if($('#PhotoGallery_Image img').size() > 1)
   			{
   				$('#PhotoGallery_Image img:first').animate({opacity: 0}, 2000, function(){
   					$(this).remove();
   				});
   			}

   			$(newImg).animate({opacity: 1}, 2000);
   		}

		if(newImg[0].complete)
		{
			FadeInOutImage();
		}

		// Caption/description of the current image.
		$('#PhotoGallery_Description').html($('a[@rel="photo"]', this._currGallery).eq(imgID).children('span.description').html());
	},

	/*
	Creates static HTML template that will be used for displaying the photo
	viewer.
	*/
	_buildTemplate : function() {
		return '<div id="PhotoGallery_Wrapper" class="' + $('#wrapper').attr('class') + '">' +
					'<h1 id="PhotoGallery_Banner" title="' + this._langStrings('title') + '">' +
					this._langStrings('title') +
					'<a href="#" title="' + this._langStrings('close') + '">' + this._langStrings('close') + '</a>' +
					'</h1>' +
					'<div id="PhotoGallery_Image"></div>' +
					'<div class="clearfix"><a href="#" id="PhotoGallery_Prev">' + this._langStrings('previous') + '</a>' +
					'<a href="#" id="PhotoGallery_Next">' + this._langStrings('next') + '</a></div>' +
					'<div id="PhotoGallery_Description"></div>' +
					'<div id="PhotoGallery_Usage">' + $('p.usagerights').html() + '</div>' +
				'</div>';
	},

	_initNavigation : function() {
		(this._currPhotoInGallery == 0) ? $('#PhotoGallery_Prev').hide() : $('#PhotoGallery_Prev').show();
		(this._currPhotoInGallery < this._numPhotosInGallery - 1) ? $('#PhotoGallery_Next').show() : $('#PhotoGallery_Next').hide();
	},

	_navigationControls : function() {
		var obj = this;

		$('#PhotoGallery_Prev').click(function(){
			obj.loadImage(obj._currPhotoInGallery - 1, obj._currGallery);
			obj._currPhotoInGallery--;
			obj._initNavigation();
			return false;
		});
		$('#PhotoGallery_Next').click(function(){
			obj.loadImage(obj._currPhotoInGallery + 1, obj._currGallery);
			obj._currPhotoInGallery++;
			obj._initNavigation();
			return false;
		});
	},

	_langStrings : function(tag) {
		var lang_en = {
			title : 'Photo Gallery',
			close : 'Close',
			next : 'Next',
			previous : 'Previous'
		}

		var lang_fr = {
			title : 'Galerie de photos',
			close : 'Fermer',
			next : 'Suivant',
			previous : 'Précédent'
		}

		return (this._currLang == 'en') ? lang_en[tag] : lang_fr[tag] ;
	}

};



/*
Attempt to load URL and filter out content based on the ID provided. Any
errors will result in the page loading as a normal hyperlink.
*/
function NewsReleasesLogin(e)
{
	/*
	Contains the URL to load and the ID of the element to filter the content
	by.
	*/
	var pageOptions = $(e).attr('href').split('#');

	PopupOverlay.init('popup-login-for-commenting');

	$.ajax({
		dataType : "html",
		type : "GET",
		url : pageOptions[0],

		beforeSend : function(XMLHttpRequest) {
			PopupOverlay.loadMessage();
		},

		complete : function(XMLHttpRequest, textStatus) {

		},

		error : function(XMLHttpRequest, textStatus, errorThrown) {
			window.location.href = $(e).attr('href');
		},

		success : function(data, textStatus){
			if($('#' + pageOptions[1], data).size() < 1)
			{
				window.location.href = $(e).attr('href');
				return false;
			}

			/*
			Replace loading message with the content retrieved from above.
			*/
			PopupOverlay.loadContent($('#' + pageOptions[1], data).parent().html());

			/*
			Add a unique ID to the content in order to differentiate it from
			the normal/non-JavaScript version; add a language class for use
			with background image replacement.
			*/
			$('div.popup').attr('id', 'popup-' + pageOptions[1]);
			$('div.popup').children(':first').addClass($('#wrapper').attr('class'));

			/*
			Create a close button within the header region of the popup and
			setup click event to allow for closing the popup.
			*/
			$('<a href="#"></a>').appendTo('div.popup h1').click(function(e){
				PopupOverlay.close();
				return false;
			});
		}
	});
}

/*
	Language Toggle - build links
*/
function LanguageToggle(){
	var langAnchor = document.getElementById("langToggle");
	var langCodeField = document.getElementById("langToggle_lang");

	if (langAnchor && langCodeField && langCodeField.value){
		var currUrl = location.href;                    
		var newLocale = langCodeField.value.replace('-','_');
		
		//Construct the new url
		var newUrl = replaceQueryString(currUrl, "vgnLocale", newLocale);                 
		
		//Change the href
		langAnchor.href = newUrl;
	}
}

//Method to replace a param value in a query string
function replaceQueryString(url,param,value) {
	var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
	if (url.match(re))
		return url.replace(re,'$1' + param + "=" + value + '$2');
	else if (url.indexOf("?") == -1)
		return url + '?' + param + "=" + value;
	else
		return url + '&' + param + "=" + value;
}

function AdvisorLanguageToggle(){

	var langAnchor = document.getElementById("langToggle");
	if (langAnchor){
		var currUrl = location.href;                    

		
		  //Construct the language toggle url
      if (currUrl.indexOf('\/F\/') >=0){
		    currUrl = currUrl.replace('/F/', '/E/');                 
			//Change the href
			langAnchor.href = currUrl ;
      }
	  else if  (currUrl.indexOf('\/f\/') >=0){
			currUrl = currUrl.replace('/f/', '/e/');  
			//Change the href
			langAnchor.href = currUrl ;
	  }
	}
	
}


function AdvisorContentPanels()
{
	
	
	// Scan for "imcoming" content panel request; if none, revert to first.
	if($('#tertiary li a[@href="'+ location.hash +'"]').size() > 0)
	{
		//AdvisorChangePanel(location.hash.substr(1));
		
	}
	else
	{
		
		$('div.AdvisorContentPanel:gt(0)').hide();
	}

	function AdvisorChangePanel(tab)
	{
		$('div.AdvisorContentPanel').hide();
		$('div.AdvisorContentPanel[@id="AdvisorContentPanel-' + tab + '"]').show();
		$('#tertiary li a').removeClass('lit');
		$('#tertiary li a[@href="#'+tab+'"]').addClass('lit');
	}

	// Setup click event for each tab.
	$('#tertiary li a').click(function(e){
		AdvisorChangePanel($(this).attr('href').substr(1));
		return false;
	});

	// Setup click event for each tab.
	$('#contactme').click(function(e){
		AdvisorChangePanel($(this).attr('href').substr(1));
		return false;
	});
}