/**
 * START:// styleswitcher.js
 *
 **/

 function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);


/**
 * END:// styleswitcher.js
 *
 **/


/**
 * START:// swfobject.js
 *
**/

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;


/**
 * END:// swfobject.js
 *
**/


/**
 * START:// global.js
 *
**/

/**
 * 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();

	// Photo & AV gallery
	//PhotoAVGallery();

	// Tertiary links (country pages)
	$('#tertiary').show();

	//Tertiary_US links (country pages) for US HOME PAGE

	$('#tertiary_US li').click(function(e){
		$('#tertiary_US li').removeClass('active');
		$(this).addClass('active');
		US_ChangePanel($(this).children("a").attr('href').substr(1));
	});
	$('div.contentpanel').hide();
	$('div.contentpanel[id="contentpanel-tab2"]').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);
	 // Setup third level navigation
    thirdLevelNavigation();


	//invert floatee
	// invertFloatee();

	//Build link for Language Toggle
	LanguageToggle();

	myLinks();
}


/*
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?");
		});
	});
}



/*
Print friendly
*/
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'
		};
		// added for hongkong
		var lang_zh = {
			printpage : '&#21015;&#21360;',
			closepage : '&#38364;&#38281;'
		};

		var langTag;
		//Check body for SunlifeCA home page - the home page does not have "en/fr" attached to #wrapper
		var objBody = document.getElementsByTagName("body")[0];
		if (objBody && objBody.className != ""){
			if (objBody.className == "en")
				langTag = lang_en[tag];
			else
			if (objBody.className == "fr")
				langTag = lang_fr[tag];
			else
			if (objBody.className == "zh")
				langTag = lang_zh[tag];

			if (!langTag){
				langTag = ($('#wrapper').attr('class') == 'en') ? lang_en[tag] : lang_fr[tag] ;
			}

			return langTag;
		} else{
			// if page is other then SunlifeCA home page
			if($('#wrapper').attr('class') == 'fr'){
				return  lang_fr[tag] ;
			}else if($('#wrapper').attr('class') == 'zh'){
				return lang_zh[tag] ;
			}else{
				return lang_en[tag] ;
			}
		}		
	}

	$("#print-page a").click(function(e){

		var content_vlue	= document.getElementById("content-body").innerHTML;
		var content_vlue	= document.getElementById("content-body").innerHTML;
		var header			= document.getElementById("header").innerHTML;
		var breadcrumb		= document.getElementById("breadcrumb").innerHTML;
		var footer			= document.getElementById("footer").innerHTML;

		//Clean up footer - remove web-analytics script
		var analyticsStart = "<!--start-analytics-->";
		var analyticsEnd = "<!--stop-analytics-->";
		footer = cleanupContent(footer, analyticsStart, analyticsEnd);
		// Parul z189 - Check added to remove Brighter Feed section from Print preview for new CA Home page - Project (CA Q2 Refresh)
		if($(".home-brighterlife").html() != null){
			
			var bfeedHtml = $(".home-brighterlife").html();
			content_vlue = content_vlue.replace(bfeedHtml,"");
		}
		var links =	'<div id="printpagenav" style="position:absolute;top:160px;right:0;padding:10px;">' +
					'<a href="javascript:self.print();" id="printpage">' + _langStrings('printpage') + '</a>' +
					'&#160;|&#160;' +
					'<a href="javascript:self.close();" id="closepage">' + _langStrings('closepage') + '</a>' +
					'</div>';


	  	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/slfglobal/styles/print.css" type="text/css" media="screen" />');
		docprint.document.write('<link rel="stylesheet" href="/static/slfglobal/styles/print_hidenav.css" type="text/css" media="print" />');
		docprint.document.write('<link rel="stylesheet" href="/static/slfglobal/styles/print.css" type="text/css" media="print" />');
		docprint.document.write('</head><body>');
		docprint.document.write('<div id="header">'+header+'</div>');
		docprint.document.write('<div id="breadcrumb">'+breadcrumb+'</div>');
		docprint.document.write(links);
		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="footer">'+footer+'</div>');
		docprint.document.write('</body></html>');
		docprint.document.close();
		docprint.focus();

		return false;

	});
}

/*
Method to clean up content - removing the given substring
@param content - content to be cleaned up
@param startStr - start of the string to be stripped off from the content
@param endStr - End of the string to be removed from the content

@return
	the cleaned up content
*/
function cleanupContent(content, startStr, endStr){

	var startIndex = content.indexOf(startStr);
	var endIndex = content.indexOf(endStr);

	if (startIndex != -1 && endIndex != -1){
		endIndex = endIndex + endStr.length;
	}

	var contentToRemove = content.substring(startIndex, endIndex);
	content = content.replace(contentToRemove, "");

	return content;
}

/*
Print friendly - OLD VERSION
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 winRef = window.open('', 'PrintFriendly', 'location=0,directories=0,status=0,scrollbars=1,resizable=1,width=800,height=600');
		winRef.location.reload();

		// Create print and close links.
		var lnkPrint = '<a href="#" id="printpage">' + _langStrings('printpage') + '</a>';
		var lnkClose = '<a href="javascript:self.close();" id="closepage">' + _langStrings('closepage') + '</a>';

		// Insert head statements.
		winRef.document.writeln('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">');
		winRef.document.writeln('<head><title>' + $('title').html() + '</title>');
		winRef.document.writeln('<link rel="stylesheet" href="/static/global/styles/print.css" type="text/css" media="screen" />');
		winRef.document.writeln('<link rel="stylesheet" href="/static/global/styles/print.css" type="text/css" media="print" />');
		winRef.document.writeln('</head><body>');
		winRef.document.writeln($('body').html());
		winRef.document.writeln('<div style="position:absolute;top:0;right:0;padding:10px;">' + lnkPrint + '&nbsp;|&nbsp;' + lnkClose + '</div>');
		winRef.document.writeln('</body></html>');
		winRef.focus();

		winRef.document.getElementById('printpage').onclick = function(){
			self.print();
			self.focus();
			return false;
		};

		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});
        $('#billboard img:first').css({zIndex: 10});
				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');
				$('#content-body div.top div.mini-dashboard div.signin select').css('visibility', 'hidden');
			}
		},
		function() {
			$("#choose-country-content").hide();
			$('#content-sidebar div.feature:first select').css('visibility', 'visible');
			$('#content-body div.top div.mini-dashboard div.signin select').css('visibility', 'visible');
		}
	);

	$("#choose-country-content").hover(
		function() {
			$("#choose-country-content").show();
			$('#content-sidebar div.feature:first select').css('visibility', 'hidden');
			$('#content-body div.top div.mini-dashboard div.signin select').css('visibility', 'hidden');
		},
		function(){
			$("#choose-country-content").hide();
			$('#content-sidebar div.feature:first select').css('visibility', 'visible');
			$('#content-body div.top div.mini-dashboard div.signin 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;
	});
}


/*
Global Presence Content Panel For US Home Page
*/


/*function US_ContentPanels()
{
	// Scan for "imcoming" content panel request; if none, revert to first.
	if($('#tertiary_US li a[href="'+ location.hash +'"]').size() > 0)
	{

		US_ChangePanel(location.hash.substr(1));
	}
	else
	{

		$('div.contentpanel:gt(0)').hide();
	}

	function US_ChangePanel(tab)
	{

		$('div.contentpanel').hide();
		$('div.contentpanel[id="contentpanel-' + tab + '"]').show();
		$('#tertiary_US li a').removeClass('active');
		$('#tertiary_US li a[href="#'+tab+'"]').addClass('active');
	}

	// Setup click event for each tab.
	$('#tertiary_US li a').click(function(e){
		US_ChangePanel($(this).attr('href').substr(1));
		return false;
	});
}*/


function US_ChangePanel(tab)
	{
		$('div.contentpanel').hide();
		$('div.contentpanel[id="contentpanel-' + tab + '"]').show();
	}


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;
			});
		}

			});
}

		/*
Third Level Navigation Collapse/Expand
*/
function thirdLevelNavigation() {
    $("li.children > a").click(function() {
        $(this).next('ul').toggle();
        $(this).next('div').children('ul').toggle();  /* IE 6 hacks */
        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
		//Check if this page points to the sunlifeCA homepage and uses a short url
		//If so handle differently
		var newUrl = "";
		if (currUrl == 'http://stage-www.ca.sunlife'
			|| currUrl == 'http://stage-www.ca.sunlife/')
			newUrl = "http://stage-www.ca.sunlife/canada/v/index.jsp?vgnextoid=9788e7a80ca5d010vgnprod1000067c7d09fRCRD&vgnLocale=fr_CA";
		else
		if (currUrl == 'http://stage-www.sunlife.ca'
			|| currUrl == 'http://stage-www.sunlife.ca/')
			newUrl = "http://stage-www.sunlife.ca/canada/v/index.jsp?vgnextoid=9788e7a80ca5d010vgnprod1000067c7d09fRCRD&vgnLocale=fr_CA";
		else
		if (currUrl == 'http://www.ca.sunlife'
			|| currUrl == 'http://www.ca.sunlife/' || currUrl == 'http://www.ca.sunlife/#')
			newUrl = "http://www.ca.sunlife/canada/v/index.jsp?vgnextoid=9788e7a80ca5d010vgnprod1000067c7d09fRCRD&vgnLocale=fr_CA";
		else
		if (currUrl == 'http://www.sunlife.ca'
			|| currUrl == 'http://www.sunlife.ca/' || currUrl == 'http://www.sunlife.ca/#' )
			newUrl = "http://www.sunlife.ca/canada/v/index.jsp?vgnextoid=9788e7a80ca5d010vgnprod1000067c7d09fRCRD&vgnLocale=fr_CA";
		else
		//for PHI
		if (currUrl == 'http://www.healthinsuranceincanada.ca' 
				|| currUrl == 'http://www.healthinsuranceincanada.ca/')
			newUrl = "http://www.healthinsuranceincanada.ca/canada/v/index.jsp?vgnextoid=c899f3f64fce0210VgnVCM1000009b80d09fRCRD&vgnLocale=fr_CA";		
		else 
		if (currUrl == 'http://healthinsuranceincanada.ca/?utm_source=SunLife&utm_medium=BannerA&utm_campaign=CorpRef')
			newUrl = "http://www.healthinsuranceincanada.ca/canada/v/index.jsp?vgnextoid=c899f3f64fce0210VgnVCM1000009b80d09fRCRD&vgnLocale=fr_CA&utm_source=SunLife&utm_medium=BannerA&utm_campaign=CorpRef";			
		else
		if (currUrl.indexOf("/e/") != -1)
			newUrl = currUrl.replace("/e/", "/f/");
		else
		if (currUrl.indexOf("/f/") != -1)
			newUrl = currUrl.replace("/f/", "/e/");
		else
		if (currUrl.indexOf("/en_CA/") != -1)
			newUrl = currUrl.replace("/en_CA/", "/fr_CA/");
		else
		if (currUrl.indexOf("/fr_CA/") != -1)
			newUrl = currUrl.replace("/fr_CA/", "/en_CA/");
		else
			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;
}



/*
My Links
*/
function myLinks() {
	//$('#my-links div.dashboard').appendTo('body').css("right", parseInt(($(window).width() - 969) / 2) + "px").addClass('dashboard-ready');

	$('<input type="hidden" name="dashPosTop" value="0" />').appendTo('div.dashboard');
	$('<input type="hidden" name="dashPosLeft" value="0" />').appendTo('div.dashboard');
	
		
	$('#my-links, #sign-in').hover(
		function() {
			$('> a.hdr', this).addClass('lit');
			$('div.mini-dashboard div.signin select').hide();
			$('div.dashboard', this).show();
			
			var coords = $('div.dashboard').offset();
      			$('input[name="dashPosTop"]', 'div.dashboard').val(coords.top);
      			$('input[name="dashPosLeft"]', 'div.dashboard').val(coords.left);
			
		},
		
		function() {
			$('> a.hdr', this).removeClass('lit');
			$('div.mini-dashboard div.signin select').show();
			
			$('div.dashboard', this).hide();
		}
	);
	

	/*
	Setup actions that are available ("Add" and "Edit") within My links.
	*/
	$('span.add a, span.edit a, span.help a', 'div.dashboard').click(function(){
		Popup($(this).attr('href'), 'mylinks', $('input[name="dashPosTop"]', 'div.dashboard').val(), $('input[name="dashPosLeft"]', 'div.dashboard').val());
		return false;
	});
}



/*
Create a popup window at a specificed location on the screen.
*/
function Popup(href, windowName, y, x){
	var popup = window.open(href, windowName, 'width=415,height=340,location=no,menubar=no,status=no,scrollbars=yes,top='+ (parseInt(y) + 30) +',left='+ (parseInt(x) - 20));
	popup.focus();
}

/**
 * END:// global.js
 *
**/
