/* 
	This is the master JavaScript function library used throughout the site. It
	requires jQuery 1.6.4, jQuery UI, Cufon 1.09i, and may require jQuery Tools 
	depending on the specific function.
*/

jQuery.support.cors = true; // force cross-site scripting
var encHomeServer = null;
Cufon.replace(''); // Force Cufon to initialise and hide content-to-be-styled

$(document).ready(function() {
	encHomeServer = $('script[src*="global.js"]').attr('src').substr(0,$('script[src*="global.js"]').attr('src').indexOf('/',9));

	setMainRollover(); // Set main menu rollover
	setTextResizing(); // Set text sizing buttons

	// Set up search box functionality
	$('#header .search-box form')
		.submit(function() {document.location.href= encHomeServer + "/search/?" + $('#header #search-input').serialize();return false;})
		.find('#search-input').focus(function() {$(this).val('');}).blur(function() {if ($(this).val() == '') $(this).val('Search');});

	// Replace selected text with corporate fonts. Cufon is required as
	// Encana internal security does not allow @font-face
	Cufon.replace('h1, #banner p, #banner a, #content .content .callout a.callout-btn, .home .slide a, #content .content .callout p.title, #content .content .callout p.subtitle, #slides .slides_container p, #featured h2, #profiles h3 span, .row-text-left h2, .row-text-right h2, h2.community-map', { fontFamily: 'HumanistLight521'}); 
	Cufon.replace('#header ul.nav-main li a.primary, .dropdown-column-2 strong, #content #buckets h2, body.home #buckets h2, #content #profiles h2, #featured h3, .related h3, #content .content .callout p.secondary-subtitle, h3.quick-facts, #content .content h2:not(ul.thumb-list h2, #featured h2, .row-text-left h2, .row-text-right h2, ul.video-list h2, h2.title, .page-current-news h2, h2.community-map), .col p.heading, .community-news h2, #profiles h3, .story .caption p, div.story-details .related-stories h3 ', { fontFamily: 'Humanist521', hover: true }); 
	Cufon.now();

	window.setTimeout(finishInit,10); // spawn other init processes to speed up page load
	$(window).resize(positionFooter); // attach event handler to look for page resize
});

// This is to allow slower JS engines (e.g. IE7) to finish displaying the page before executing 
// some heavier scripts. See functions for individual descriptions.
function finishInit() {
	var tmp;
	buildSectionNav(); 
	buildBreadcrumb();
	setActiveStates();
	setAccordion();
	setOurStoriesImgRollover();
	setFormEvents();
	positionFooter();
	loadDisclaimers(); // both Investors and Multimedia Gallery sections

	window.setTimeout(setCarousel,10);
	
	//tmp = 'setExternalLinks("")';
	//window.setTimeout(tmp,10);
}

// Sets up the rollover events for the main menu
function setMainRollover() {
	$('#header ul.nav-main li').hover(function () {
		$(this).find("div.dropdown").stop(false, true).slideDown(500);
		$(this).find("a.primary").addClass('roll');
	}, function () {
		$(this).find("div.dropdown").stop(false, true).hide();
		$(this).find("a.primary").removeClass('roll');
	});	
}

// Sets up the accordion behaviours when the accordion classes are present
function setAccordion() {
	if ($('body').hasClass('accordion-closed')) {
		// hide "closed" accordion content (default state)
		$(".accordion-content").css("display", "none");
	} 
	else {
		// Hide all accordion content except the first one
		$(".accordion .accordion-content:not(:first)").css("display", "none");
		$(".accordion li:first").addClass("open");
	}
	accordionClick();
}

// Attach onclick event handlers for the accordions
function accordionClick() {
	$(".accordion a.heading").click(function(e) {
		e.stopPropagation();
		e.stopImmediatePropagation();
		if ($(this).parent().hasClass("open")) {
			$(this).parent().removeClass("open");
			$(this).next().slideUp('fast');
		} 
		else {
			$(this).parent().addClass("open");
			$(this).next().slideDown('fast');
		}
		return false;
	});
}

// Sets up the active states for the main menu and the left-hand section sub-menu. This
// function applies only CSS classes, which are defined in global.css.
// Communities > Canada > Atlantic has a special override due to its menu structure. All
// active state information is derived from matching the current URL to menu items.
function setActiveStates() {
	var isAtlantic = (document.location.href.indexOf('/communities/canada/atlantic/') > 0)?true:false;

	$('ul.nav-main li a.primary').each(function() {
		var url = document.location.href;
		if ( url.indexOf( $(this).attr('href') ) > 0 ) {
			$(this).addClass('active');
		}
	});

	$('ul.nav-secondary li>a').each(function() {
		var url = document.location.href;
		if ( url.indexOf( $(this).attr('href') ) > 0 ) {
			$(this).addClass('active');
		}
	});
	
	$('#columns .section-nav a').each(function() {
		var url = document.location.href;
		if ( url.indexOf( $(this).attr('href') ) > 0 ) {
			if (!isAtlantic) $(this).parent().addClass('active');
			var urlPrefix = document.location.protocol + '//' + document.domain + ((location.port != '')?':'+location.port:'');
			if (url.substr(urlPrefix.length) == $(this).attr('href')) {
				$(this).addClass('current');
				if (isAtlantic) {
					$(this).parent().addClass('active');
					if ($(this).next('ul').length >  0) {
						$(this).next('ul').removeClass('atlanticsub');
						$(this).parent().addClass('collapsible')
					}	
					if ($(this).parents('ul').hasClass('atlanticsub')) {
						$(this).parents('ul').removeClass('atlanticsub');
						$(this).parents('ul').parents('li').addClass('collapsible').addClass('active');
						//$(this).parent('li').addClass('collapsible active');	
					} 
				}
			}
		}
	});

	// Sets up the tabs on pages they exist
	$('#tabs').tabs();
	$('#tabs table tbody tr').each(function() {
		$(this).children('td:first').addClass('row-label');
	});
}

// Dependent function for setExternalLinks. This determines if a specific link should
// be an exception to having it open in a new window.
function checkException(link) {
	var exceptions = ['investor.shareholder.com','encana.com'];
	var found = false;
	for (i in exceptions) {
		// Is the link an exception, not a PDF, and we're not on a third-party site? 
		if (link.indexOf(exceptions[i]) > 0 && link.indexOf('.pdf') < 0) {
			found = true;
			break;
		}
	}
	return found;
}

// All links on the page are scanned for domain name. Any links with a different domain
// name from the hosting server (with exceptions) will open in a new window/tab. Also,
// links to PDF, Word, Excel, or forced-download files will also open in a new window/tab.
function setExternalLinks(elem) {
	if (!elem) elem = "";
	if (elem != '') elem += " ";
	elem += "a";
	var docDomain = window.location.protocol + '//' + document.domain;
	var isTestimonials = ($('.page-testimonials').length)?true:false;

	$(elem).each(function(){
		var isSet = false;
		var isTestimonialVideo = (isTestimonials && this.href.indexOf('youtube') > 0)?true:false;
		var isBreadCrumb = (this.className.indexOf('bc') >= 0);
		var isAlreadyExternal = (this.className.indexOf('external') >= 0);
		
		// Make sure there is a URL on this <a>, that it's not part of a video list (YouTube vids)
		// and see if it's not on the exceptions list
		if (this.href && !isTestimonialVideo && this.href.substr(0,1) != '#' && !checkException(this.href)) { 
			if (((this.href).substr(0,docDomain.length) != docDomain) && ((this.href).substr(0,6) != 'mailto' ) && !isBreadCrumb && !isAlreadyExternal) {
				if (!($(this).children('img').length)) {
					$(this).addClass('external');	
				}
                $(this).unbind('click');
				$(this).click( function() {
					window.open( $(this).attr('href') );
					return false;
			    });
				isSet = true;
			}

			if (this.href.indexOf('.pdf') > 0 || this.href.indexOf('.doc') > 0 || this.href.indexOf('.xls') > 0 || this.href.indexOf('file-download.php') > 0) {
				if (!isSet) {
                    $(this).unbind('click');
					$(this).click( function() {
						window.open( $(this).attr('href') );
						return false;
				    });
				}
				$(this).attr('onclick','return false;');
			}
		}
	});
}

// The breadcrumb is built automatically in a combination of the current URL
// path, plus the current page <h1> tag. The path is determined by walking the
// main menu hierarchy. Atlantic Canada has a specific override to insert the 
// Community Map link because it sits outside the hierarchy. 
function buildBreadcrumb() {
	if ($('#pane-nav').length) {
		var currentPath = document.location.href.substring((window.location.protocol + '//' + document.location.host).length);
		var breadBlock = document.createElement('ul');
		var parts = [];
		var tmp = (currentPath.substring(1)).split('/');
		var chkPath = '/';
	
		// Take URL, break into pieces based on "/", insert into array to search
		for (i in tmp) {if (tmp[i] != '') parts.push(tmp[i]);}

		$(breadBlock).append('<li><a href="' + ((encHomeServer)?encHomeServer:"/") + '">Home</a></li>'); // Home link

		var hasMapLink = false; // Check to see if Community Map link has been inserted
		for (i in parts) {
			chkPath += parts[i];
			$('#nav a').each(function(index) {
				var linkChk = $(this).attr('href');
				if (linkChk.substring(linkChk.length-1) == '/') {
					linkChk = linkChk.substring(0,linkChk.length-1); // drop the trailing slash
				}

				// Links that appear in a .content block do not get searched
				if (linkChk == chkPath && !$(this).parent().hasClass('content')) {
					var itemtext = $(this).text();

					// Are we in communities, and does this NOT have a Community Map link yet?
					if (!hasMapLink && (linkChk.indexOf('/communities/canada')>-1 || linkChk.indexOf('/communities/usa')>-1)) {
						$(breadBlock).append('<li><a href="/communities/encana-community-map.html" class="bc">Community Map</a></li>');
						hasMapLink = true;
					}

					// Check the breadcrumb length. If getting too long, lop off parts with "&" and " - ".
					if ($(breadBlock).text().length > 50) {
						if (itemtext.indexOf('&') > 0) itemtext = itemtext.substr(0,itemtext.indexOf('&')-1);
						if (itemtext.indexOf(' - ') > 0) itemtext = itemtext.substr(0,itemtext.indexOf(' - '));
					}
					$(breadBlock).append('<li><a href="' + linkChk + '" class="bc">' + itemtext + '</a></li>');
					return false;
				}
			
			});
		
			chkPath += "/";
		}
		$('#pane-nav .breadcrumb').append(breadBlock);

		// Next, let's make sure the actual page in the breadcrumb (not always in the menu menu)
		var lastCrumb = $("#pane-nav .breadcrumb li:last a").attr("href").replace(/\/$/, '');
		if (lastCrumb.indexOf(window.location.protocol + '//' + document.location.host) > -1) lastCrumb = lastCrumb.substr((window.location.protocol + '//' + document.location.host).length);

		// Finally, check to see if current URL is in the trail. The replace yanks any trailing slashes to improve the match.
		if (lastCrumb != currentPath.replace(/\/$/, '')) {
			var itemtext = $('h1').text();
			
			// Have to check length again. Some of the titles (notably News Releases) are VERY long
			// and must be truncated. We add an ellipsis if needed.
			if ($(breadBlock).text().length + itemtext.length > 90) {
				itemtext = itemtext.substr(0,100 - $(breadBlock).text().length);
			 	itemtext = itemtext.substr(0,itemtext.lastIndexOf(' '));
				itemtext += "...";
			}
			
			$(breadBlock).append('<li>' + itemtext + '</li>');
		} 
		else {
			// Kills the link in the final trail item (why click to a page you're already on?)
			$("#pane-nav .breadcrumb li:last a").contents().unwrap();
		}
	}
}

// This makes the text bigger or smaller. Very simple, and has a range of only 6 pixels, in
// increments of 2
function setTextResizing() {
	$('#pane-nav .text-print a:not(.print)').click(function(){
		var ourText = $('#content .content p, #content .content li, #content .content h3, #content .content a').not('div.callout *, p.pullquote, h1, h2, div.related h3');
		var currFontSize = ourText.css('fontSize');
		var finalNum = parseFloat(currFontSize, 10);
		var stringEnding = currFontSize.slice(-2);
		if(this.id == 'resize-large') {
			if (finalNum < 16) finalNum += 2;
			if (finalNum > 16) finalNum = 16;
		}
		else if (this.id == 'resize-small') {
			if (finalNum > 10) finalNum -= 2;
			if (finalNum < 10) finalNum = 10;
		}
		ourText.css('fontSize', finalNum + stringEnding);
		return false;
	});
}

// Builds the left-side sub menu. This is done by copying part of the main menu structure
// (it contains a near-complete sitemap to minimise maintenance), and placing a portion of
// it in the side menu. 
function buildSectionNav() {
	var currentPath = document.location.href.substring((window.location.protocol + '//' + document.location.host).length);
	var section = currentPath.substring(0,currentPath.indexOf('/', 2));
	var isAtlantic = (document.location.href.indexOf('/communities/canada/atlantic/') > 0)?true:false; // Atlantic section has specific overrides
	var isWelcome = (document.location.href.indexOf('/careers/welcome') > 0)?true:false; // Careers welcome page has a specific side menu
	var tPNav = (encHomeServer == '')?'':$('body').attr('class'); // Third-party sites require a bit of finessing
	var tPNavElem = {'shareholder':'invest','vovici':'','sarps':'contractors'}; // Array to define which part of the main menu to use for third-party submenus
	if (tPNav.indexOf(' ') > -1) tPNav = tPNav.substr(0,tPNav.indexOf(' '));
	
	if (!isWelcome) {
		var sectionMenu = null;

		var navBlock = document.createElement('ul');

		// Atlantic has a very specific portion of the menu, which is ID'd for simplicity
		if (isAtlantic) {
			var submenu = $('#atlanticmenu').children('li').clone();
			$(navBlock).append(submenu);
			sectionMenu = navBlock;
		} 
		// Check to see if we're doing a third-party submenu
		else if (tPNav != '') {
			var subParent = $('#nav li.' + tPNavElem[tPNav]);
			if (!subParent.length) subParent = $('#nav li#' + tPNavElem[tPNav]);
			submenu = $(subParent).find('ul.ul-column').children('li').clone();
			$(navBlock).append(submenu);
			$(navBlock).children('li').each(function(index, elem) {
				if ($(elem).children('ul').length > 0) {
					$(elem).addClass('collapsible');
				}
			});

			sectionMenu = navBlock;
		}
		// Okay, we're doing the real thing
		else {
			$('#nav a').each(function() {
				var linkChk = $(this).attr('href');
				if (linkChk.substring(linkChk.length-1) == '/') linkChk = linkChk.substring(0,linkChk.length-1);

				if (linkChk == section) {
					var submenu = $(this).parent('li').find('ul.ul-column').children('li').clone(); // Clone is necessary, or the menu will be MOVED to the submenu
					$(navBlock).append(submenu);
					$(navBlock).children('li').each(function(index, elem) {
						// Check to see if this is a nested menu
						if ($(elem).children('ul').length > 0) {
							$(elem).addClass('collapsible'); 
						}
					});

					sectionMenu = navBlock;
					return false;
				}
			});
		}
		$('#columns .section-nav').append(sectionMenu);
	}
}

// The footer will either appear 30px below the main content block, or at the bottom of the browser
// window, depending on how short the content is on a given page, and the height of a person's browser
// window. The page elements are added up with an 80px buffer.
function positionFooter() {
	var homeHeight = $('#slides').outerHeight() + $('#buckets').outerHeight();
	var bannerHeight = $('#banner').outerHeight();
	var contentHeight = $('#content').outerHeight();
	var headFootHeight = $('#header').outerHeight() + $('#ticker').outerHeight() + $('#footer').outerHeight() + 80;
	var elemHeight = (($('body.home').length > 0)?homeHeight:(bannerHeight + contentHeight)) + headFootHeight;

	if ($(window).height() > elemHeight) {
		$('#footer,#ticker').css('position','absolute');
		$('#footer').css('bottom','0');
		$('#ticker').css('bottom',$('#footer').outerHeight());
	}
	else $('#footer,#ticker').css('position','relative').css('bottom','');
}

// Sets up the rollovers seen on the News & Stories > Our Stories page
function setOurStoriesImgRollover() {
	$('.story').hover(function() {
		$(this).find('div.caption').stop(false,true).fadeTo(400, 0.7);
		$(this).find('div.caption p').show();
	},function() {
		$(this).find('div.caption').stop(false,true).fadeTo(400, 0.0);
		$(this).find('div.caption p').hide();
	});
}

// Sets up the form logic used for the Careers forms, seen on the homepage and
// on the careers landing page
function setFormEvents() {
	$('form.searchjobs input.submit, form.searchjobs a').click(function(e) {
		e.preventDefault();	
		if ($('.country').val() == 'CAN') {
			
			if ($('form.searchjobs .employment').val() == '0') window.location = '/careers/opportunities-canada.html';
			else window.location = '/careers/students-new-grads/canada/opportunities.html';
		}
		else {
			if ($('form.searchjobs .employment').val() == '0') window.location = '/careers/opportunities-usa.html';
			else window.location = '/careers/students-new-grads/usa/opportunities.html';
		}
		return false;
	});
}

// Image background preloader
function preloadImages(strImagePath) {
	var heavyImage = new Image();
	heavyImage.src = strImagePath;
}

// For entire Investors section, load disclaimer message
function loadDisclaimers() {
	// Investors section
	if($("body").hasClass("section-investors")) disclaimerOverlay("/includes/elements/disclaimer-investors.html","disclaimerInvestors");

	// Multimedia Gallery pages (Video, B-Roll, Photographs, Advertisting, Publications)
	if($("body").hasClass("disclaimer-check")) disclaimerOverlay("/includes/elements/disclaimer-media-gallery.html","disclaimerMediaGallery");		
}

// Disclaimer Overlay functions - used in Multimedia section 
function disclaimerOverlay(url,cookieName) {
	// test if cookie has already been set
	if($.cookie(cookieName)!="agree") buildDisclaimerOverlay(url,cookieName);
}

// Sets up the disclaimer overlay. Requires jQuery UI.
function buildDisclaimerOverlay(url,cookieName) {
	$(".disclaimer-overlay").overlay({
		top: 30,		
		fixed: false,
		mask: {
			color: '#000',
			loadSpeed: 800,
			opacity: 0.6
		},
		closeOnClick: false, // function inserted into overlay to handle cookies
		//load: true,
		
		onBeforeLoad: function() {
			var wrap = this.getOverlay().find(".content-wrap");
			wrap.load(url);
		},
		onLoad: function() {
			$(".content-wrap").fadeIn();		
		}
	});	
	$(".disclaimer-overlay").data("overlay").load();	
}

// Ensures cookies are written out for disclaimers
function disclaimerOnclick(val,cookieName) {
	if(val=="agree") {
		$.cookie(cookieName, 'agree', { path: '/' });
		closeDisclaimerOverlay();		
		location.reload();		
	}
	if(val=="decline") {
		closeDisclaimerOverlay();
		history.go(-1);		
	}
}

// Attaches animation for closing the disclaimer overlay
function closeDisclaimerOverlay() {
	$(".disclaimer-overlay").fadeOut("fast", function(){
		$("#exposeMask").fadeOut();
	});	
}

// Sets up the viewer functionality for the carousel (see setCarousel
// below) that appears in the right-hand column next to the main image 
// on the Community pages. Requires jCarouselLite plugin.
function mediaViewer() {
	// If doesn't have a carousel class, avoid running this method
	if ($(".media-viewer .carousel").length > 0) {
		mvCarousel = $(".media-viewer .carousel");
	    mvCarousel.jcarousel({
	    	wrap: 'circular',
	    	scroll: 2,
	    	buttonNextHTML: '<a href="javascript:void(0);" class="next">Next</a>',
	    	buttonPrevHTML: '<a href="javascript:void(0);" class="prev">Previous</a>'
	    });
	
		// Remove navigation if there is only one item (which is actually 3 when jCarouselLite creates the ul)
		if ($(mvCarousel).find("li").length <= 2) {
			$(".media-viewer a.prev").hide();
			$(".media-viewer a.next").hide();
		}
	
		// hover event
		$(mvCarousel).find("ul li a").hover(function () {
			$("img", this).addClass("img-hover");
		}, function () {
			$("img", this).removeClass("img-hover");
		});		

		// Attach click events
		$(".carousel ul li a").click(function(){
			// clear all borders
			$(".carousel ul > li img").each(function(i, ele) {
				$(ele).removeClass("img-highlight");
			});

			// Grab image src and swap out "thumb" for "main"
			var path = $("img", this).attr("src");
			path = path.replace("thumb-","main-");

			// Add border for highlighted 
			$("img", this).addClass("img-highlight");
			$(".callout img.main").fadeOut("fast", function(){
				$(".callout img.main").fadeIn("slow").attr("src", path);
			});	
		
			//set title, desc, link for articles
			$(".callout-title").html($("img", this).attr("data-title"));
		
			// if there is no link attribute, remove the "view story" link
			$(".callout-link").html(""); //Clear previous contents of div
			$("img[data-link]", this).each(function() {
				var link = $(this).attr("data-link");
				if (link.length > 0 && link != "#") {
					var linkhtml = '<a href=" ' + link + '">View Story</a>';
					$(".callout-link").append(linkhtml);
				}
			});
		});	

		// show the viewer after all is loaded
		$(".media-viewer").css("visibility","visible");
	}
}

// Generic function to get a URL parameter value; returns "null" if none found
function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

// Function loading and showing videos from Encana's YouTube Channel. Used in
// Careers, News & Stories, and on Search results page. Requires SWFObject
// to load up the YouTube player in an overlay.
function loadVideo(playerUrl, autoplay, videoTitle, videoDescription)  {
	swfobject.embedSWF(
		playerUrl + '&rel=1&border=0&fs=1&autoplay=' + 
		(autoplay?1:0), 'player', '640', '358', '9.0.0', false, 
		false, {allowfullscreen: 'true', wmode: 'opaque'});
	$(".overlay-title").html(unescape(videoTitle));
	$(".overlay-description").html(unescape(videoDescription));
}

// Given a YouTube ID, will acquire a list of videos. Optional parameters
// for query (used in Search page), search (true/false), and maxvids (needed
// on Search page; max of 7)
function loadYouTubeVideos(youtube_id,query,search,maxvids) {
	$(".paging-section").hide();
	$("#encana-video-list").addClass("content-loading");

	if (query) query = "&q=" + escape(query.replace('/\s/$','+'));
	else query = '';
	if (!search) search = false;

	$.ajax({
		type: "GET",
		url: "http://gdata.youtube.com/feeds/users/" + youtube_id + "/uploads?max-results=50&alt=json-in-script&format=5" + query, //generateJSonPlayListCallBackUrl(),
		cache: false,
		crossDomain: true,
		dataType:'jsonp',
		success: function(data){
			showVideos(data,(search)?1:0,maxvids);
		}
	});	
}

// Set up the overlay for the YouTube videos. Requires jQuery UI.
function mediaOverlay(posFixed) {
	// Attach overlays
    if (posFixed == undefined) posFixed = true;
    if (posFixed == 'false') posFixed = false; 

    if (posFixed) {
       	$('a[rel]').overlay({
    		mask: {
    			color: '#000',
    			opacity: 0.6
    		},
    		effect: 'apple',
    		onClose: function() {
    			$("#playerContainer .player-wrap").html('<object id="player"></object><p class="overlay-title"></p><p class="overlay-description"></p>'); 
    		}			
    	});
    }
    else {
       	$('a[rel]').overlay({
    		mask: {
    			color: '#000',
    			opacity: 0.6
    		},
    		fixed: false, 
    		effect: 'apple',
    		onClose: function() {
    			$("#playerContainer .player-wrap").html('<object id="player"></object><p class="overlay-title"></p><p class="overlay-description"></p>'); 
    		}			
    	});
    }
}

// Text overlays for Careers testimonials (no need for separate JS file)
function loadTestimonial(employee) {
	if(employee=="jacob") /* Jacob Schumway, Staff Testimonial */
	{
		loadVideo('http://www.youtube.com/v/t_YIXfVGKJE?version=3&f=user_uploads&app=youtube_gdata', true, 'Employee testimonial: Jacob', 'Jacob Shumway, Group Lead, Play Assessments &amp; New Ventures, main role at Encana is to explore new opportunities. Sounds interesting? Take a closer look.');
	}
	if(employee=="jerry") /* Jerry Ferguson, Staff Testimonial */
	{
		loadVideo('http://www.youtube.com/v/smdTfJqBnWI?version=3&f=user_uploads&app=youtube_gdata', true, 'Employee testimonial: Jerry', 'How does Jerry Ferguson, Production Coordinator, incorporate innovation in his job at Encana? Take a closer look.')
	}	
	if(employee=="jennifer") /* Jennifer Pond, Staff Testimonial */
	{
		loadVideo('http://www.youtube.com/v/NYyFcnfAuT0?version=3&f=user_uploads&app=youtube_gdata', true, 'Employee testimonial: Jennifer', 'What did Jennifer Fallon, Completions Engineer, win a CAPP Responsible Canadian Energy Award for at Encana? Take a closer look.');
	}	
	if(employee=="aubrey") /* Aubrey Marasco, Student Testimonial */
	{
		loadVideo('http://www.youtube.com/v/T4_5-oWBb4I?version=3&f=user_uploads&app=youtube_gdata', true, 'Student testimonial: Aubrey', 'Aubrey Marasco, Regulatory Compliance Finance Intern, got to see many areas of the Finance department during her summer internship at Encana. Take a closer look.');
	}
	if(employee=="megan") /* Megan Jamer, Student Testimonial */
	{
		loadVideo('http://www.youtube.com/v/RM6ZdwaPyrI?version=3&f=user_uploads&app=youtube_gdata', true, 'Student testimonial: Megan', 'What was it about Encana that made Megan Jamer, Student Geologist, want to work here for her summer term? Take a closer look.');
	}
	if(employee=="matt") /* Matt Stiasny, Student Testimonial */
	{
		loadVideo('http://www.youtube.com/v/l2nxJDqFvFg?version=3&f=user_uploads&app=youtube_gdata', true, 'Student testimonial: Matt', 'What was Matt Stiasny\'s, Production Engineering Intern, favourite part about being an intern at Encana? Take a closer look.');
	}
	if(employee=="derek") /* Derek Schlenker, Student Testimonial */
	{
		loadVideo('http://www.youtube.com/v/V2agzvOhKck?version=3&f=user_uploads&app=youtube_gdata', true, 'Student testimonial: Derek', 'What would Derek Schlenker, Mechanical Engineering Student, say to someone thinking about joining Encana? Take a closer look.');
	}
	if(employee=="summer2011") /* Summer Students 2011, Student Montage */
	{
		loadVideo('http://www.youtube.com/v/ip9houuQDiI?version=3&f=user_uploads&app=youtube_gdata', true, 'Summer Students 2011', 'Find out why our Canadian summer students had such a great time and learning experience working at Encana. Take a closer look.');
	}			
}

// Sets up click functions for the carousel (actual carousel functionality
// defined in mediaViewer above)
function setCarousel() {
    if ($(".carousel").length > 0) {
        var firstImg = $(".carousel ul li:eq(0) a img[data-link]");
        $(".callout-title").html(firstImg.attr("data-title"));
        var link = firstImg.attr("data-link");
        if (link && link.length > 0 && link != "#") {
            var linkhtml = '<a href=" ' + link + '">View Story</a>';
            $(".callout-link").append(linkhtml);
        }

        $('.carousel li a').each(function() { $(this).attr('onclick','return false;'); });

        // Add media viewer carousel functionality
        window.setTimeout(mediaViewer,10); 
        if ($('.section-communities').length > 0) window.setTimeout(mediaOverlay,10); 
    }
}

// Overlay to display compensation details on Careers > Why Encana page
function compensationOverlay(url) {						
	$("#compensation-overlay").overlay({
		top: 30,
		fixed: false,
		mask: {
			color: '#000',
			loadSpeed: 800,
			opacity: 0.8
		},
		closeOnClick: true,
		load: true,
		onBeforeLoad: function() {
			var wrap = this.getOverlay().find(".content-wrap");
			wrap.load(url);
		},
		onLoad: function() {
			$(".content-wrap").fadeIn();
		}	
	});	
}

// For pages that need a "read disclaimer" link
function readDisclaimer()
{
	$(".read-disclaimer").click(function(e){
		e.preventDefault();	
		$(".disclaimer-overlay").overlay({
			top: 30,		
			fixed: false,
			mask: {
				color: '#000',
				loadSpeed: 800,
				opacity: 0.6
			},
			closeOnClick: true, // function inserted into overlay to handle cookies
			load: false,
		
			onBeforeLoad: function() {
				var wrap = this.getOverlay().find(".content-wrap");
				wrap.load("/includes/elements/disclaimer-media-gallery.html", function(){ 
					$(this).parent().addClass("apple_overlay");
					$(".content-wrap .btns").css({"display":"none"});	
				});
				
			},
			onLoad: function() {
				var wrap = this.getOverlay().find(".content-wrap");
				wrap.load("/includes/elements/disclaimer-media-gallery.html", function(){ 
					$(this).parent().addClass("apple_overlay");
					$(".content-wrap .btns").css({"display":"none"});	
				});				
				$(".content-wrap").fadeIn();		
			}
		});	
		$(".disclaimer-overlay").data("overlay").load();				
	});
}


