var video = {
	setGlobals: function(){
		html5Video = '';
		video.videoType = '';
		video.videoFormat = '';
		video.downloadable = 1;
		video.openLinks = jQuery('a[rel="open-video"], a.open-videoBTN');
		video.closeRel = 'close-video-window';
		video.videoWindowHTML = '<div id="video-window"><a href="#" id="close-link" rel="' + video.closeRel + '">close window</a><div id="video-player"></div></div>';
		video.backButtonMask = '<div style="position: absolute; top: 0; left: 0; cursor: default; z-index: 100; background: white; height: 36px; width: 41px; opacity: 0;"></div>';
	},
	
	// Open video when appropriate querystring or URL hash is found
	urlOpenVideo: function(){
		// Look for video querystring
		if ( jQuery.url.param('video') ) {
			var urlParam = jQuery.url.param('video');
			video.openLinks.each(function(){
				var compareUrl = this.href.split('/').reverse()[0].split('.')[0];
				var $this = $(this);
				if(compareUrl === urlParam) {
					setTimeout(function(){
						$this.trigger('click');						
					}, 500);
					// Exit each()
					return false;
				}
			});
		// Look for URL hash
		} else if ( document.location.hash ) {
			var docHash = document.location.hash.replace('#', '');
			
			// If URL hash is just 'video,' look for singular page video and play if found
			if ( docHash === 'video' && video.openLinks.length === 1 ) {
				setTimeout(function(){
					video.openLinks.first().trigger('click');
				}, 500);
			} else {
				// Otherwise check to see if URL hash matches name of specific video
				video.openLinks.each(function(){
					var compareUrl = this.href.split('/').reverse()[0].split('.')[0];
					var $this = $(this);
					if(compareUrl === document.location.hash.replace('#', '')) {
						setTimeout(function(){
							$this.trigger('click');
						}, 500);
						// Exit each()
						return false;
					}
				});
			}
		}
	},
	
	// Hide/mask page elements when video is displayed
	hidePageElements: function(){
		// Hide thumb scroller
		jQuery('#thumb_scroller').css({ width: '0px', display: 'none', opacity: 0 });

		// If we're on the homepage, we need to dismiss the existing Flash
		if(jQuery('body#home').length) {
			swfobject.removeSWF('home-flash');
		}
		
		// Hide main content
		brizo.hideContentBody();
		
		// Add class to #wrapper to hide black line on Collection page
		$('#wrapper').addClass('video-playing');

		// Hide remaining elements
		brizo.sideNav.fadeOut('fast');
		brizo.scrollerTitles.fadeOut('fast');
		brizo.thumbWrapper.fadeOut('fast');
		
		// Hide extended content on Collection page
		$('div.extended-content-group').css({ visibility: 'hidden' });
		
		// Hide background image on Culinary page
		if ( $('body#culinary').length ) {
			var $wrapper = $('#wrapper');
			var wBG = $wrapper.css('background');
			$wrapper.data('bg', wBG);
			$wrapper.css({ background: 'white' });
		}
		
		// Add overlay to mask back link if present when movie overlay is invoked
		// maskBackLink: function(){
		// 	if(jQuery('a.back-link').length){
		// 		jQuery(video.backButtonMask).appendTo(jQuery('a.back-link')).animate({ opacity: 1 }, 250);
		// 	}		
		// }
	},
	
	// Re-display page elements when video is closed
	revealPageElements: function(){
		// Show main content
		brizo.showContentBody();
		
		// Remove class from #wrapper that hid black line on Collection page
		$('#wrapper').removeClass('video-playing');
		
		brizo.sideNav.fadeIn('fast');
		brizo.thumbWrapper.fadeIn('fast');
		brizo.scrollerTitles.fadeIn('fast', function(){
			jQuery('#thumb_scroller').css({ width: '680px', display: 'block', opacity: 1 });
		});
		
		// Show extended Collection page content
		if($('div.extended-content-group').length) {
			$('div.extended-content-group').css({ visibility: 'visible' });
		}
		
		// Show background image on Culinary page
		if ( $('body#culinary').length ) {
			var $wrapper = $('#wrapper');
			var wBG = $wrapper.data('bg');
			$wrapper.css({ background: wBG });
		}
		
		// Remove mask overlay from back link if present
		if(jQuery('a.back-link').length){
			var bm = jQuery('a.back-link div');
			bm.animate({ opacity: 0 }, 250, function(){ bm.remove(); });
		}
	},
	
	/*
	 * Main Video Player functionality goes here
	*/
	videoPlayer: {		
		// Store video size and other params
		config: {
			height: 542,
			width: 688,
			top: 120,
			left: 214,
			speed: 100,
			padLeft: 0
		},
		
		// Bind video links
		setOpenLinks: function(){
			video.openLinks.unbind('click').bind('click', function(e){
				e.preventDefault();
				var $this = $(this);
				
				// Track view in Google Analytics
				_gaq.push(['_trackEvent', 'Video Views', 'Video Viewed', $(this).attr('href')]);
				
				// Set var to enable selective display of video download links
				video.downloadable = $this.hasClass('no-download') ? 0 : 1;
				
				video.videoPlayer.launch($this.attr('href'), $this.data('hires'), $this.data('suppress-related'), $this.data('height'));
			});
		},
		
		// Determine whether browser supports HTML5 video and what format is needed
		html5Check: function(){
			var v = document.createElement("video");
			// Check to see if browser can play HTML5 video in one of our supported formats
			// Filtering out IE9 with jQuery.support check
			if ( v.play && (v.canPlayType('video/ogg') || v.canPlayType('video/mp4')) && jQuery.support.noCloneChecked ) {
				video.videoType = 'html5';
				
				// Check format
				if ( v.canPlayType('video/ogg') ) {
					video.videoFormat = 'ogv';
				} else if ( v.canPlayType('video/mp4') ) {
					video.videoFormat = 'mp4';
				}
			} else {
				video.videoType = 'flash';
			}
		},
		
		// Ensure video window is in view when launched
		setViewPosition: function(){
			if($(document).scrollTop() > 120) {
				$(document).scrollTop(120);
			}
		},
		
		addDownloadLinks: function(vPath, hires){
			var vName = vPath.split('/').reverse()[0].split('.')[0];
			var $ipodLink = $('<a href="/videos/m4v/'+ vName +'.m4v" class="alt-video-link link-ipod">iPod Download</a>');
			var $wmvLink = $('<a href="/videos/wmv/'+ vName +'.wmv" class="alt-video-link link-wmv">WMV Download</a>');
			var $hiresLink = $('<a href="'+ hires +'" class="alt-video-link link-hires hires-last">Hi-Res Download</a>');
			
			// Remove old download link set if present
			$('#download-links').remove();
			
			// Build download links set
			var $downloadLinks = $('<div id="download-links" />');
			
			// Only add download links if video downloads are not suppressed
			if( video.downloadable === 1 ) {
				$downloadLinks.append($ipodLink, $wmvLink);
				if( hires ) {
					$downloadLinks.append($hiresLink);
				}
			}			
			
			// Add download links to overlay			
			$('#video-player').after($downloadLinks);
		},
		
		insertAddThis: function(vPath){
			var addThisCode = '<div id="addthis-toolbox" class="addthis_toolbox addthis_default_style"><a href="http://addthis.com/bookmark.php?v=250" class="addthis_button_compact">Share</a><span class="addthis_separator"></span><a class="addthis_button_facebook"></a><a class="addthis_button_twitter"></a><a class="addthis_button_googlebuzz"></a><a class="addthis_button_email"></a><span class="addthis_separator"></span><a class="addthis_button_facebook_like"></a></div>';
			
			var initAddThis = function(vPath){
				vName = vPath.split('/').reverse()[0].split('.')[0];
				
				// Store location-related vars
				var docLoc = location.href;
				var docHash = location.hash;

				// Strip out any existing URL hash
				docLoc = docLoc.replace(docHash, '');

				// Build new URLs to share
				// - AddThis URL for sharing
				var shareUrl = docLoc.split('?')[0] + '?video=' + vName;

				// Instantiate AddThis button
				// - We pass in custom URL which includes hash to auto-launch video
				if(typeof addthis != "undefined"){
					addthis.toolbox("#addthis-toolbox", {}, {
						url: shareUrl
					});
				}

				// Customize URL of Facebook Like button
				if( $('a.addthis_button_facebook_like iframe').length ) {
					var frameSrc = 'http://www.facebook.com/plugins/like.php?href='+shareUrl+'&layout=button_count&show_faces=false&width=100&action=like&font=arial&colorscheme=light';
					$('a.addthis_button_facebook_like iframe').attr('src', frameSrc);
				}
			};
			
			$('#download-links').after(addThisCode);
			initAddThis(vPath);
		},
		
		// Create video overlay window
		buildVideoWindow: function(){
			$('div#wrapper').append(video.videoWindowHTML);
		},
		
		// Set up HTML5 video controls
		activateControls: function(){
			var $v = $('#vPlayer');
			var v = $v.get(0);
			var seeksliding;
			var $playpause = $('div.video-controls div.play-pause');
			var $volume = $('div.video-controls div.volume');
			
			// Set state of play/pause button based on video's state
			var setButtonPaused = function(){
				$playpause.removeClass('pause').addClass('play');
			};			
			var setButtonPlaying = function(){
				$playpause.removeClass('play').addClass('pause');
			};
			
			// Set default state of play/pause on iPad to Paused
			if ( isiPad ) {
				$playpause.addClass('play');
			}
			
			$v.bind('play', setButtonPlaying);
			$v.bind('pause', setButtonPaused);
			$v.bind('ended', function(){
				setButtonPaused();
				// Rewind video to beginning
				v.currentTime = 0;
				v.pause();
			});
			
			// iPad (and other iOS devices) disable JS-based volume settings,
			// so we hide the volume button there
			if ( !isiPad ) {
				$v.bind('volumechange', function(){
					if( $v.attr('muted') === true ) {
						$volume.addClass('muted');
					} else {
						$volume.removeClass('muted');
					}
				});
				
				// Make Mute button work
				$volume.bind('click', function(){
					if ( $v.attr('muted') === true ) {
						$v.attr('muted', false);
					} else {
						$v.attr('muted', true);
					}
				});
			} else {
				$volume.remove();
			}
			
			
			// Make play/pause button work
			$playpause.bind('click', function(e){
				if( v.paused ) {
					v.play();
				} else {
					v.pause();
				}
			});
			
			
			
			// Set up slider control				
			var createSeek = function() {
				if($v.attr('readyState')) {
					var video_duration = $v.attr('duration');
					$('div.video-slider').slider({
						value: 0,
						step: 0.01,
						orientation: 'horizontal',
						range: 'min',
						max: video_duration,
						animate: true,
						slide: function(){							
							seeksliding = true;
						},
						stop:function(e,ui){
							seeksliding = false;						
							$v.attr('currentTime', ui.value);
						}
					});
					// $video_controls.show();					
				} else {
					setTimeout(createSeek, 150);
				}
			};
			
			createSeek();
			
			var seekUpdate = function() {
				var currenttime = $v.attr('currentTime');
				if( !seeksliding ) {
					$('div.video-slider').slider('value', currenttime);
				}
			};

			$v.bind('timeupdate', seekUpdate);
		},
		
		// Build video player
		buildVideoPlayer: function(vPath, cHeight){
			var $videoWrapper = $('div#video-player');
			
			// Build video player
			// First, check to see if HTML5 video is supported
			if( video.videoType === 'html5' ) {
				// If HTML5 video is supported, we insert that player
				vName = vPath.split('/').reverse()[0].split('.')[0];
				var $vControls = $('<div class="video-controls"><div class="play-pause" /><div class="video-slider" /><div class="volume" /></div>');
				html5Video = $('<video id="vPlayer" autoplay />');
				html5Video.attr('width', 688);
				html5Video.attr('height', cHeight === 0 ? 386 : cHeight);
				
				// Add poster image
				html5Video.attr('poster', '/images/pic/video-poster-images/'+ vName +'.jpg');
				
				// Add appropriate video source
				if ( video.videoFormat === 'mp4' ) {
					html5Video.append('<source src="http://brizo.hansoninc.com/videos/mp4/'+ vName +'.mp4" />');
				} else if ( video.videoFormat === 'ogv' ) {
					html5Video.append('<source src="http://brizo.hansoninc.com/videos/ogv/'+ vName +'.theora.ogv" type=\'video/ogg; codecs="theora, vorbis"\' />');
				}
				
				// Append player and controls to overlay window
				$videoWrapper.append(html5Video);
				$videoWrapper.append($vControls);
				
				// Make controls active
				video.videoPlayer.activateControls();
				
			} else {
				
				// If no HTML5 video support is detected, we fall back to Flash
				$('#video-window').addClass('flash');
				
				var flashvars = { videoURL: vPath, channelID: "experience", playerAutoPlay: "true" };
				var params = { menu: "false", allowFullScreen: "false", scale: "noscale", salign: "lt", allowScriptAccess:"always", wmode:"transparent" };
				var attributes = { id: "video-player", name: "video-player" };
				
				swfobject.embedSWF( "/flash/videoplayer.swf", "video-player", "688", "522", "9.0.0", "flash/expressinstall.swf", flashvars, params, attributes);
			}
		},
		
		// Animate video window into view
		animateIn: function(vPath, cHeight){
			var $vw = $('div#video-window');
			
			var animParams = {
				opacity: 1,
				top: video.videoPlayer.config.top+'px',
				left: video.videoPlayer.config.left+'px',
				width: video.videoPlayer.config.width+'px',
				// height: video.videoPlayer.config.height+'px',
				paddingLeft: video.videoPlayer.config.padLeft+'px'
			};
			
			// Hide certain page elements
			video.hidePageElements();
			
			// Add video player
			video.videoPlayer.buildVideoPlayer(vPath, cHeight);
			
			// Display video window
			$vw.animate(animParams, video.videoPlayer.config.speed, brizo.easing, function(){
				$('a.alt-video-link').fadeIn(500);
				video.videoPlayer.setCloseLink();
			}).css({ zIndex: 79 });
			
			// Disable clicks on other open video links temporarily
			video.openLinks.unbind().bind('click', function(){
				return false;
			});
			
			// Track video view in analytics
			if(typeof(pageTracker) != "undefined"){
				pageTracker._trackPageview(vPath);
			}
		},
		
		// Dismiss video window
		animateOut: function(){
			var animParams = {
				opacity: 0,
				top: '275px',
				left: '401px',
				width: '300px',
				height: '200px'
			};
			
			var $vw = $('div#video-window');
			
			// Reinstate hidden page elements
			video.revealPageElements();
			
			$vw.animate(animParams, 200, brizo.easing, function(){			
				jQuery('#video-player').remove();
				$vw.remove();
			});

			// If related videos exist
			if($('#related-videos').length) {
				// Move them back to the body tag for future use
				$('#related-videos').appendTo('body').hide();
			}
			
			// Reenable other open video links
			video.videoPlayer.setOpenLinks();
		},
		
		// Activate close link
		setCloseLink: function(){
			$('#close-link').bind('click', function(e){
				e.preventDefault();
				video.videoPlayer.animateOut();
				$(this).unbind();
				// setTimeout(function(){ brizo.showContentBody(); }, 100);
			});
		},
		
		// Related videos functionality
		relatedVids: {
			// Determine whether there are related videos to display
			checkForRelatedVids: function(){
				var relatedVids = 0;
				if(location.href.indexOf('shower') !== -1 || location.href.indexOf('collection') !== -1) {
					return true;
					// relatedVids = jQuery.url.attr('file').replace('.html', '');
				}
			},
			
			addVids: function(){
				if( video.videoPlayer.relatedVids.checkForRelatedVids() ) {
					var urlToUse = '/experience/gallery/video-gallery/collection/'+ jQuery.url.segment(0) +'/'+ jQuery.url.attr('file') +' #content';
					
					console.log('urlToUse: ', urlToUse);
					
					// Store related vid HTML content
					var $relatedVids = $('<div id="related-videos" />').load(urlToUse, function(){
						processRelatedVids();
					});
					
					// Set highlight state on appropriate related vid thumb
					var setHighlight = function(elm){
						if ( $('li.related-video').length ) {
							if ( !elm ) {
								$('li.related-video').first().find('img').addClass('highlight');
							} else {
								$this = $(elm);
								$('li.related-video img').removeClass('highlight');
								$this.find('img').addClass('highlight');
							}
						}						
					};
					
					var playRelatedVid = function(vName){
						if ( video.videoType === 'html5' ) {
							// First remove previous source
							html5Video.find('source').remove();
							if ( video.videoFormat === 'mp4' ) {
								html5Video.append('<source src="/videos/mp4/'+ vName +'.mp4" />');
							} else if ( video.videoFormat === 'ogv' ) {
								html5Video.append('<source src="/videos/ogv/'+ vName +'.theora.ogv" type=\'video/ogg; codecs="theora, vorbis"\' />');
							}
							
							html5Video.get(0).load();
							html5Video.get(0).play();
						} else {
							// Swap existing Flash object with div
							$('object#video-player').replaceWith('<div id="video-player"/>');
							
							// Insert and play new video
							var flashvars = { videoURL: '/videos/'+ vName +'.flv', channelID: "experience", playerAutoPlay: "true" };
							var params = { menu: "false", allowFullScreen: "false", scale: "noscale", salign: "lt", allowScriptAccess:"always", wmode:"transparent" };
							var attributes = { id: "video-player", name: "video-player" };

							swfobject.embedSWF( "/flash/videoplayer.swf", "video-player", "688", "522", "9.0.0", "flash/expressinstall.swf", flashvars, params, attributes);
						}
					};
					
					// Set up retrieved code for use in overlay
					var processRelatedVids = function(){
						// Add video thumbs/links
						$('#video-window').append($relatedVids);
						
						// Set initial highlight state
						setHighlight();
						
						// Update main video when related vid is clicked
						$('li.related-video a').bind('click', function(e){
							e.preventDefault();
							
							var $this = $(this);							
							var vLink = $this.attr('href');
							var vName = vLink.split('/').reverse()[0].split('.')[0];
							
							// Update highlight state
							setHighlight(this);
							
							// Play clicked video
							playRelatedVid(vName);
							
							// Update download links
							video.videoPlayer.addDownloadLinks(vLink, $this.data('hires'));
						});
					};
				}
			},
			
			init: function(){
				video.videoPlayer.relatedVids.addVids();
			}
		},		
		
		launch: function(vPath, hires, suppressRelated, customHeight){			
			video.videoPlayer.setViewPosition(); // Scroll window back to top
			video.hidePageElements(); // Hide certain elements
			video.videoPlayer.html5Check();
			cHeight = customHeight || 0;
			video.videoPlayer.buildVideoWindow(); // Construct video player overlay
			video.videoPlayer.addDownloadLinks(vPath, hires);
			if ( !suppressRelated ) {
				video.videoPlayer.relatedVids.init();
			}
			video.videoPlayer.insertAddThis(vPath);
			video.videoPlayer.animateIn(vPath, cHeight); // Bring video player into view		
		}		
	},
	
	init: function(openLinks){
		video.setGlobals();
		video.videoPlayer.setOpenLinks();
		// video.setOpenLinks();
		video.urlOpenVideo();
	}
};
