                                                                     
                                                                     
                                                                     
                                             
// brilliant_futures.js for PwC Brilliant Futures website
// site-wide functionality

var videoPagePath = 'video.html';
var lang = (location.href.indexOf('/fr/') > -1) ? 'fr' : 'en';

/**********************************************************************
   Page initialization
 *********************************************************************/

$(document).ready(function(){
	
	// external links
	$('a.external').bind('click', function(event) {
			event.preventDefault();
			window.open(this.href, 'external', 'location,menubar,resizable,scrollbars,status,toolbar');
		});
	
	// iphone video
	var videoLink = $('.brilliant-video');
	if (navigator.userAgent.match(/iPhone/i)) {
		videoLink.removeClass('brilliant-video');
		videoLink.attr('href', getParameterByName('video', videoLink.attr('href')) + '.m4v');
	}
	
	// video in url string
	if (getParameterByName('person') && getParameterByName('video') && $('body#video-viewer').length == 0) {
		var videoUrl = videoPagePath + '?person=' + getParameterByName('person') + 'video=' + getParameterByName('video') + '&referrer=' + window.location.href;
		if (navigator.userAgent.match(/iPhone/i)) {
			location.href = videoUrl;
		}
		else {
			$('body').append('<a id="brilliant-initial-video" href="' + videoUrl + '">initial video</a>');
			$('#brilliant-initial-video').overlay( {
				target: '#pwc-media-overlay',
				effect: 'apple',
				speed: 'normal',
				closeOnClick: true,
				closeonEscape: true,
				fadeInSpeed: 0,
				fadeOutSpeed: 0,
				zIndex: 20000,	
				fixed: false,
				top: '8%',						
				mask: {
					color: '#ffffff',
					loadSpeed: 200,
					opacity: 0.85
				},
				onClose: function() {
					$("#media-player").empty();
				},
				onBeforeLoad: function() {
					this.getOverlay().appendTo('body'); //IE7 fix for z-index issue
					var externalHtml = '<iframe type="text/html" width="720" height="448" src="' + videoUrl + '" frameborder="0" style="border: 1px solid #888; overflow:hidden" scrolling="no"></iframe>';
					$("#media-player").html(externalHtml);
				},
				load: true
			});
		}
	}
	
	// video links
	$('.brilliant-video').each(function() {
		$this = $(this);
		var videoUrl = $this.attr('href');
		$this.overlay( {
			target: '#pwc-media-overlay',
			effect: 'apple',
			speed: 'normal',
			closeOnClick: true,
			closeonEscape: true,
			fadeInSpeed: 0,
			fadeOutSpeed: 0,
			zIndex: 20000,	
			fixed: false,
			top: '8%',						
			mask: {
				color: '#ffffff',
				loadSpeed: 200,
				opacity: 0.85
			},
			onClose: function() {
				$("#media-player").empty();
			},
			onBeforeLoad: function() {
				this.getOverlay().appendTo('body'); //IE7 fix for z-index issue
				var externalHtml = '<iframe type="text/html" width="720" height="448" src="' + videoUrl + '" frameborder="0" style="border: 1px solid #888; overflow:hidden" scrolling="no"></iframe>';
				$("#media-player").html(externalHtml);
			}
		});
	});
	
	// tabs on apply page
	$( "#job-category-tabs" ).tabs();
	
	if ($('body#video-viewer').length > 0) {
		
		// interface translations
		var numTranslations = translations.length;
		for (var index = 0; index < numTranslations; index++) {
			var item = translations[index];
			var element = eval('$("' + item.jqueryElement + '")');
			if (element.length) {
				element.html(item[lang]);
			}
		}
		
		// video viewer controls
		var personId = getParameterByName('person');
		var videoId = getParameterByName('video');
		
		var detect = document.createElement('video') || false;
		var html5 = detect && typeof detect.canPlayType !== "undefined";
		var videoSupport = {
			mp4: html5 && (detect.canPlayType("video/mp4") === "maybe" || detect.canPlayType("video/mp4") === "probably"),
			ogg: html5 && (detect.canPlayType("video/ogg") === "maybe" || detect.canPlayType("video/ogg") === "probably"),
			webm: html5 && (detect.canPlayType("video/webm") === "maybe" || detect.canPlayType("video/webm") === "probably")
		};
 
 		// references to the video player and aliases for methods
		if (videoSupport.mp4 || videoSupport.ogg || videoSupport.webm) {
			var video = {
				'play': function() { $('video')[0].player.play(); },
				'stop': function() { $('video')[0].player.stop(); },
				'pause': function() { $('video')[0].player.pause(); },
				'volume': function(newVolume) { $('video')[0].volume = newVolume; },
				'fullscreen': function() { $('video')[0].player.enterFullScreen(); }
			};
			$('#fullscreen-control').css('display', 'block');
			$('video')[0].addEventListener('canplay', function() { $('#video-mask').css('display', 'none'); }, true);
			$('video')[0].addEventListener('ended', function() { showWhereToNext(); }, true);
		}
		else {
			var video = {
				'play': function() { flowplayer(0).play(); },
				'stop': function() { flowplayer(0).stop(); },
				'pause': function() { flowplayer(0).pause(); },
				'volume': function(newVolume) { flowplayer(0).setVolume(newVolume); },
				'fullscreen': function() { flowplayer(0).toggleFullscreen(); }
			};
			flowplayer(0).onLoad = function() {
				$('#video-mask').css('display', 'none');
			};
			//flowplayer(0).getControls().css('display', 'none');
		}
		
		// clicking a control toggles any toggleable content associated with that control
		$('#video-controls > li > a').bind('click', function(e) {
			var $this = $(this);
			if ($this.parent().hasClass('show-toggleable-content')) {
				$this.parent().removeClass('show-toggleable-content');
			}
			else {
				$('.show-toggleable-content').removeClass('show-toggleable-content');
				$this.parent().addClass('show-toggleable-content');
			}
			
			// moving off a control or it's content will hide any toggleable content associated with that control
			// IE has a problem with this
			if (navigator.userAgent.match(/MSIE/) == null) {
				$this.parent().hover(function() {
					}, function(){
					$(this).removeClass('show-toggleable-content');
				});
			}
			
			e.preventDefault();
		});
		
		// social media links
		var referrerURL = getParameterByName('referrer');
		referrerURL = referrerURL.replace(/(&)*video=[^&?]*/, '').replace(/\?$/, '');
		referrerURL += ((referrerURL.indexOf('?') == -1) ? '?' : '&') + 'person=' + personId + '&video=' + videoId;
		$('a.facebook').attr('href', $('a.facebook').attr('href') + '?u=' + escape(referrerURL));
		$('a.twitter').attr('href', $('a.twitter').attr('href') + '?url=' + escape(referrerURL));
		$('a.linkedin').attr('href', $('a.linkedin').attr('href') + '&url=' + escape(referrerURL));
		
		// play / pause control
		if (getParameterByName('autoplay')) {
			$('#play-pause-control > a').addClass('playing');
		}
		$('#play-pause-control > a').bind('click', function(e) {
			var $this = $(this);
			if ($this.hasClass('playing')) {
				$this.removeClass('playing');
				video.pause();
			}
			else {
				$this.addClass('playing');
				video.play();
				if (typeof _trackEvent != 'undefined') {
					_trackEvent('Brilliant Futures videos', 'play video', 'video id', getParameterByName('video'));
				}
			}
			e.preventDefault();
		});
		
		// volume control
		$('#volume-slider').draggable({
			axis: 'y',
			containment: '#volume-track',
		 	drag: function(event, ui) { 
		 		video.volume((63 - parseInt($(this).css('top'))) / 63);
			}
		});
		
		// fullscreen control
		$('#fullscreen-control > a').bind('click', function(e) {
			video.fullscreen();
			e.preventDefault();
		});
		
		// view by topic content
		if (viewByTopic[personId][videoId]) {
			$('#view-by-topic-content').append(getVideoDescription(viewByTopic[personId][videoId]));
		}

		// view by people content
		if (viewByPeople[personId][videoId]) {
			$('#view-by-people-content').append(getVideoDescription(viewByPeople[personId][videoId]));
		}
		
		// where to next content
		if (thisStory[personId][videoId]) {
			$('#this-story-text').append(thisStory[personId][videoId].text[lang]);
			var linksHtml = '<ul>';
			for (link in thisStory[personId][videoId].links) {
				linksHtml += '<li><a href="' + thisStory[personId][videoId].links[link].linkUrl + '" target="_top">';
				linksHtml += thisStory[personId][videoId].links[link].linkDescription[lang];
				linksHtml += '</a></li>';
			}
			$('#this-story').append(linksHtml);
		}
		/*if (fromThisPerson[personId][videoId]) {
			$('#other-stories').append(getVideoDescription(fromThisPerson[personId][videoId]));
		}*/
		if (relatedStories[personId][videoId]) {
			$('#other-stories').append(getVideoDescription(relatedStories[personId][videoId]));
		}
		$('#where-to-next').append('<a class="close" />');
		$('.close').bind('click', function(e) {
			hideWhereToNext();
			e.preventDefault();
		});
	}
	
	// scrollable content
	setTimeout('addScrollbars()', 500);
				
	// autoplay doesn't seem to work: object doesn't get written into the page until play is clicked
	var isIE = (navigator.userAgent.indexOf('MSIE') > -1);
	if (isIE && typeof autoplay !== 'undefined' && autoplay == 'autoplay') {
		$('#play-pause-control > a').trigger('click');
		$('#play-pause-control > a').trigger('click');
	}

});

function getVideoTag(person, video, autoplay) {
	var videoName = person.video[video].url;
	var html;
	var isIE = (navigator.userAgent.indexOf('MSIE') > -1);
	if (!isIE || (isIE && getIEVersion() < 9) ) {
		html += '<video class="video-js" width="720" height="404" preload="auto" poster="' + person.imgPoster + '" ' + ((autoplay && navigator.userAgent.indexOf('MSIE 9') == -1) ? 'autoplay="autoplay"' : '') + '>';
		html += '<source src="' + videoName + '.mp4" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />';
		html += '<source src="' + videoName + '.webm" type=\'video/webm; codecs="vp8, vorbis"\' />';
		html += '<source src="' + videoName + '.ogv" type=\'video/ogg; codecs="theora, vorbis"\' />';
	}
	// Flash Fallback. Use any flash video player here. Make sure to keep the vjs-flash-fallback class.
	html += '<div id="flash_fallback_1" style="display:block; width:720px; height:404px;">';
	html += '<img src="' + person.imgPoster + '" width="720" height="404" />';
	html += '</div>';
	if (!isIE || (isIE && getIEVersion() < 9) ) {
		html += '</video>';
	}
	return html;
}

function showWhereToNext() {
	$('#page-mask').css('display', 'block');
	$('#where-to-next').css('display', 'block');
	if (typeof _trackEvent != 'undefined') {
		_trackEvent('Brilliant Futures videos', 'video complete view', 'video id', getParameterByName('video'));
	}
}

function hideWhereToNext() {
	$('#page-mask').css('display', 'none');
	$('#where-to-next').css('display', 'none');
}
function getVideoDescription(videoArray) {
	var html = '';
	for (videoIndex in videoArray) {
		var personObj = eval(videoArray[videoIndex].person);
		html += '<div class="video-description">';
		html += '<a href="' + videoPagePath + '?person=' + videoArray[videoIndex].person + '&video=' + videoArray[videoIndex].video + '&autoplay=autoplay">';
		html += '<img src="' + personObj.imgSmall + '" />';
		html += '</a>';
		html += '<h4>' + personObj.name + '</h4>';
		html += '<p>' + personObj.video[videoArray[videoIndex].video].description[lang] + '</p>';
		html += '</div>';
	}
	return html;
}

function toggleFullscreenOverlay(isFullscreen) {
	var $overlay = parent.$('#pwc-media-overlay');
	if (isFullscreen) {
		$overlay[0].originalPosition = { top: $overlay.css('top'), left: $overlay.css('left') };
		$overlay.css( { 'top': $(parent.window).scrollTop(), 'left': $(parent.window).scrollLeft() } );
	}
	else {
		$overlay.css( { 'top': $overlay[0].originalPosition.top, 'left': $overlay[0].originalPosition.left } );
	}
	var width = (isFullscreen) ? ($(parent.window).width() - 20) : 720;
	var height = (isFullscreen) ? ($(parent.window).height() - 20) : 448;
	parent.$('#media-player iframe').width(width);
	parent.$('#media-player iframe').height(height);
}

function addScrollbars() {
	$('.scrollable').each(function() {
		$this = $(this);
		$this.wrapInner('<div class="scroll-window"><div class="scroll-content">');
		
		var containerHeight = $this.height();
		var contentHeight = $('.scroll-content', $this).height();
		
		if (contentHeight > containerHeight) {
			$this.append('<div class="scrollbar"><div class="scrollbar-shuttle"></div></div>');
			$('.scrollbar-shuttle', this).draggable({
				axis: 'y',
				containment: 'parent',
				drag: function(event, ui) { 
					$this = $(this);
					var scrollContent = $this.parents('.scrollable').find('.scroll-content');
					var scrollWindow = $this.parents('.scrollable').find('.scroll-window');
					scrollContent.css('top', -(parseInt($this.css('top')) * (scrollContent.height() - scrollWindow.height()) / ($this.parent().height() - $this.height())));
				}
			});
		}
	});
}

/**********************************************************************
   Utilities
 *********************************************************************/

function getParameterByName(name, url) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url || window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function getIEVersion() {
  var rv = -1;
  var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
  if (re.exec(navigator.userAgent) != null) {
    rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
