var resizeOK = true;
var resizeTimer;
var AL_vloadSavedHeight;
var AL_vloadSavedWidth;

/**
 * AL_vLoad is a simple streaming video lightbox plugin for jQuery. It was designed to be minimal, cross-platform, and reliable. To play the videos,
 * vLoad uses Flash whenever possible. But on environments where downloading Flash is not an option, vLoad reverts to using the upcoming HTML5 standard's
 * <video> tag. By encoding linked videos into H.264 MPEG-4 format (.mp4), you can make your content available on all browsers (even going back to IE6!).
 * 
 * Use the following settings guidelines to encode H.264 videos: http://wiki.slideshowpro.net/SSPdir/Tips-EncodingVideo
 *
 * @author Mike Dombrowski
 * @version 1.2
 * @requires jQuery <http://jquery.com/>
 * @requires SWFobject <http://code.google.com/p/swfobject/>
 * @requires SlideShowPro <http://slideshowpro.net/>
 * 
 * @param {String} version - which version of Adobe Flash Player to load & require. Default is 9, set to any number past 9 to disable Flash all the time.
 * @param {String} player - location of the player SWF object to load. default is "../swf/player.swf"
 */
(function($){
	$.fn.extend({
		vLoad: function(params) {
				// set up default settings
				var settings={
					version: '9',
					player: '../cms/swf/player.swf'
				};
				
				// merge parameters with default settings
				if (params) {
					$.extend(settings, params);
				}
				
				/*
				 * Generates a size for the dimmer layer, based on the current screen position.
				 */
				function AL_setDimmerSize() {
					var wHeight = Math.floor($(document).height()) + 'px';
					var wWidth = Math.floor($(document).width()) + 'px';
					$('html').css({'overflow':'hidden'});
					$('#vload-dimmer').css({'height':wHeight , 'width':wWidth})
					$('html').css({'overflow':'auto'});
				}
				
				/*
				 * Centers the #vload-window (content area) horizontally and vertically.
				 */
				function AL_setWindowPosition() {
					var scrollTop = $(window).scrollTop();
					var wh = $(window).height();
					var hOffset = Math.floor((wh / 2)) - (Math.floor((video.h / 2))) + scrollTop;
						hOffset = (hOffset > 0) ? hOffset + 'px' : '0px';
					var ww = $(document).width();
					var mw = $('#vload-window').width();
					var wOffset = Math.floor((ww / 2)) - (Math.floor((video.w / 2)));
						wOffset = (wOffset > 0) ? wOffset + 'px' : '0px';
					$('#vload-window').css({'background-color': '#fff' , 'width':video.w , 'height': video.h , 'top':hOffset , 'left':wOffset});
					}
				/*
				 * Hides the #vload-window from view. Activated by clicking the dimmer layer or the "(X)" at the top-right
				 * corner of #vload-window
				 */
				function AL_closeWindow() {
					$('#vload-window').css('visibility','hidden').hide();
					if (swfobject.hasFlashPlayerVersion(settings.version) ) {
						swfobject.removeSWF('vload-video');
					} else {
						$('#vload-video').remove();
					}
					$('#vload-window').prepend('<div id="vload-video"></div>');
					$('#vload-dimmer').animate({opacity:0},400,function(){$(this).hide();});
				}
					
				/*
				 * Detects Android 2.1, whose native browser comes with Flash.
				 */
				function AL_detectAndroid() {
					var flash = true;
					var agent = navigator.userAgent;
					if (agent.indexOf('Android') > -1) {
						var agentVer = parseFloat(agent.split(' Android ')[1].substr(0,3));
						flash = (agentVer >= 2.1) ? false : true
						}
					return flash
				}
			
			// ** Create markup and default values
				var defaultVideoHeight = 320;
				var defaultVideoWidth = 480;
				var video = {};
					//
					video.frame = '	<div id="vload-dimmer"></div>';
					video.frame+= '	<div id="vload-window">';
					video.frame+= '		<div id="vload-video"></div>';
					video.frame+= '		<div id="vload-close"></div>';
					video.frame+= '	</div>';
					//
					$('body').append(video.frame);
					
					
			
			// ** Runtime, apply vLoad to all elements selected
				
				return this.each(function() {
					
					$(this).click(function() {
						
					// ** Load Vars
						
						// Get video source
						video.src = $(this).attr('href');
						video.h = ($(this).attr('vh') > 0) ? $(this).attr('vh') : defaultVideoHeight;
						video.w = ($(this).attr('vw') > 0) ? $(this).attr('vw') : defaultVideoWidth;
						
						// Build video string
						video.str = '	<video src="'+ video.src +'" width="'+ video.w +'" height="'+ video.h +'" controls="controls" autoplay="autoplay" onclick="this.play();">';
						video.str+= '		<div id="vload-error">';
						video.str+= '			<p><strong>Error:</strong><br />';
						video.str+= '				Can not play video - Please <a href="http://www.adobe.com/support/flashplayer/downloads.html">download Adobe Flash Player</a>.</div>';
						video.str+= '			</p>';
						video.str+= '	</video>';
					
					// ** Initialize
						
						// Detect Android 2.1+
						var android21 = AL_detectAndroid();
						
						// Inject video
						if (!(android21 || swfobject.hasFlashPlayerVersion(settings.version)))	$('#vload-video').html(video.str);
						
						// Set dimmer
						AL_setDimmerSize();
						
						// Set video
						AL_setWindowPosition();
						
						// unless video.src is already an absolute path, escape the /cms/ folder
						if (!(video.src.indexOf('http://') > -1)) {
							video.src='../../'+video.src;
						}
						

					
					// ** Show
						
						// Fade-in dimmer and show video
						$('#vload-dimmer').show().animate({opacity:.5},400,function() {
							$('#vload-window').show().css('visibility','visible');
							$(window).bind('resize',function() {
								if ($('#vload-window:visible').length > 0) {
									if (AL_vloadSavedHeight != $(window).height() && AL_vloadSavedWidth != $(window).width()) {
										clearTimeout(resizeTimer);
										resizeTimer = setTimeout(function() {
											AL_setDimmerSize();
											AL_setWindowPosition();
											AL_vloadSavedHeight = $(window).height();
											AL_vloadSavedWidth = $(window).width();
											clearTimeout(resizeTimer);
										},250);
									}
								}
							});
							$('#vload-dimmer,#vload-close').bind('click', function() {
								$(window).unbind('resize');
								AL_closeWindow();
							});
						});
						
						if (android21 || swfobject.hasFlashPlayerVersion(settings.version)) {
							var attributes = {
								// id: "ex",
								width: 	video.w,
								height: video.h
							};
							var params = {
								bgcolor: "#000000",
								wmode: "transparent",
								allowfullscreen: "true"
							};
							var flashvars = {       
								contentAreaInteractivity: "Action Area and Navigation",
								xmlFileType: "Single Content",
								xmlFilePath: video.src,
								feedbackVideoButtonScale: 2,
								navButtonStyle: "Default",
								navAppearance: "Hidden",
								toolAppearanceContentArea: "Action Area Hidden", 
								videoAutoStart: "On",
								navButtonsAppearance: "Hide Display Mode and Gallery Button",
								mediaPlayerAppearance: "Always Visible"
							};
							var swf = settings.player;
							var target = 'vload-video';
							swfobject.embedSWF(swf, target, video.w, video.h, "9", "", flashvars, params, attributes);
						}
						
					// ** Kill link action on non-mobile devices
						return false;
					});
				});
			}
		});
	})(jQuery);
