
var supports_video = function() {
    return (!!document.createElement('video').canPlayType && ((navigator.userAgent.indexOf("Firefox")!=-1 && !navigator.mimeTypes["application/x-shockwave-flash"]) || navigator.userAgent.indexOf("Firefox")==-1 && navigator.userAgent.indexOf("Chrome") == -1 && navigator.userAgent.indexOf("MSIE 9.0") == -1));
}

function closeVideo() {
	if(!WidgetHandler.DisableVideoClose) WidgetHandler.VideoClose();
}

function shareRequest(type) {
	WidgetHandler.OpenShareWindow(type);
}

var FlashFallback = function() {
	this.VideoId = null;
	this.VideoPath = null;
	this.VideoStillPath = null;
	this.DataPath = null;
	this.VideoPlayerPath = null;
	this.ExpressInstallationPath = null;
	this.ExtraLink = null;
	this.ExtraTarget = null;
	this.ExtraLabel = null;
}

var WidgetSlide = function() {
	this.Id = null;
	this.Index = function() { return this.Id - 1; },
	this.Type = null;
	this.Video = null;
	this.Percentage = 0;
	this.DOM = null;
	this.ShareMenu = null;
	this.VideoControls = null;
	this.CloseButton = null;
	this.PlayButton = null;
	this.VideoProgressContainer = null;
	this.VideoBufferBar = null;
	this.VideoProgressBar = null;
	this.VideoCurrentTimeDisplay = null;
	this.VideoDurationDisplay = null;
	this.VideoSoundContainer = null;
	this.VideoVolumeBar = null;
	this.FlashFallback = new FlashFallback();
}

var WidgetHandler = {
	PageContainer: null,
	WidgetContainer: null,
	WidgetFlashVideoContainer: null,
	CursorOver: false,
	CurrentSlide: null,
	PreviousSlide: null,
	Slides: [],
	Timer: null,
	FadeSpeed: 1000,
	Delay: 8000,
	Paused: true,
	Playing: false,
	ShowingShareMenu: false,
	FullSize: false,
	UrlParameters: {},
	Override_ShareUrl: null,
	StartIndex: -1,
	ShowMovieOnLoad: false,
	DisableVideoClose: false,
	
	Init: function(override_ShareUrl) 
	{
		if(override_ShareUrl && override_ShareUrl != null && override_ShareUrl != undefined && override_ShareUrl.length > 0)
		{
			//This overrides the normal behaviour that adds default.aspx to the end of the share url.
			//You set this value when calling the WidgetHandler.Init methid (usually from the WidgetControl usercontrol.
			this.Override_ShareUrl = override_ShareUrl;
		}

		//Retrieves all the URL Parameters and stores the key value pairs in the UrlParameters variable.
		this.GetUrlParameters();
		$('#widgetItems div:first-child').css({ opacity: 1 });
		this.WidgetFlashVideoContainer = $('#widgetFlashVideoContainer')
		this.PageContainer = $('#pageContainer');
		this.WidgetContainer = $('#widget');
		
		this.PageContainer.css('display', 'none');
		this.WidgetFlashVideoContainer.css('display', 'none');
		
		//Creates the Slide Navigation
		if(this.Slides.length > 1) {
			var slideNavigationHtml = '<div class="widget-nav"><ul id="slideShowCount"><li class="slide right" onclick="WidgetHandler.Next();return false;"><span></span></li>';
			for (var i = this.Slides.length - 1; i >= 0; i--) {
				slideNavigationHtml += '<li id="slide' + i + '" class="slide"></li>';
			}
			slideNavigationHtml += '<li class="slide left" onclick="WidgetHandler.Previous();return false;"><span></span></li></ul></div>';
			this.WidgetContainer.after(slideNavigationHtml);
		}

		//Binds the on click events for the Slide Navigation
		for (var i = 0, l = this.Slides.length; i < l; i++) {     
			$('#slide' + i).bind("click", { index: i }, function (event) {
				WidgetHandler.CurrentSlide = WidgetHandler.Slides[event.data.index];
				WidgetHandler.GoToSlide(WidgetHandler.CurrentSlide);
                _gaq.push(['_trackEvent', 'hero_space_carousel', 'click_circle_' + (event.data.index + 1)])          
			});
		}

		$("#widgetItems div.widgetItem")
			.bind("mouseover", function () {
				clearTimeout(WidgetHandler.Timer);
				WidgetHandler.CursorOver = true;
			})
			.bind('mouseout', function () {
				if(WidgetHandler.Playing == false)
				{
					WidgetHandler.Timer = setTimeout("WidgetHandler.NextSlide()", WidgetHandler.Delay)
					WidgetHandler.CursorOver = false;
				}
				else
				{
					WidgetHandler.CursorOver = true;
				}
			});

		$('.slide')
			.bind('mouseover', function () {
				clearTimeout(WidgetHandler.Timer);
				WidgetHandler.CursorOver = true;
			})
			.bind('mouseout', function () {
				if(WidgetHandler.Playing == false)
				{
					WidgetHandler.Timer = setTimeout("WidgetHandler.NextSlide()", WidgetHandler.Delay)
					WidgetHandler.CursorOver = false;
				}
				else
				{
					WidgetHandler.CursorOver = true;
				}
			});

		$('.slide.left').bind('click', function() {
			_gaq.push(['_trackEvent', 'hero_space_carousel', 'click_arrow_left']);
		});
		$('.slide.right').bind('click', function() {
			_gaq.push(['_trackEvent', 'hero_space_carousel', 'click_arrow_right']);
		});
		
		//Binds the window resize event so if a video is in fullscreen mode it will resize with the window.
		$(window).resize(function() {
			if(WidgetHandler.FullSize == true){
				WidgetHandler.VideoResizeFullScreen();
			};
		});
		
		//Sets the Current Slide to the first slide and starts the timer.
		this.NextSlide();
		
		//Tries to get the UrlParameter "i" which indicates if we should start the widget on a specific Slide index
		var startIndex = TryParseInt(this.UrlParameters["i"], -1);
		if(startIndex == -1)
			startIndex = this.StartIndex;
		
		//Tries to get the UrlParameter "m" which indicates if we shouls start any video in the active slide.
		var showMovieOnLoad = (TryParseInt(this.UrlParameters["m"], 0) > 0) || this.ShowMovieOnLoad;
		
		//If the startIndex has been set and is within the Slides range we show the slide.
		//This also disables the automatic slide event by clearing the Timer.
		if(startIndex > -1 && startIndex <= this.Slides.length -1) {
			this.CurrentSlide = this.Slides[startIndex];
			this.GoToSlide(this.CurrentSlide);
			clearTimeout(this.Timer);
		}
		if((showMovieOnLoad == true && this.CurrentSlide.Video != null) || (showMovieOnLoad == true && this.CurrentSlide.FlashFallback != null && this.CurrentSlide.FlashFallback.VideoPath != null))
			this.VideoOpen();
	},
	
	AutoPlayVideo: function(index)
	{
		this.CurrentSlide = this.Slides[index];
		this.GoToSlide(this.CurrentSlide);
		clearTimeout(this.Timer);

		this.VideoOpen();
	},
	
	GetUrlParameters: function()
	{
		var e,
			a = /\+/g,  // Regex for replacing addition symbol with a space
			r = /([^&=]+)=?([^&]*)/g,
			d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
			q = window.location.search.substring(1); 

		while (e = r.exec(q))
		   this.UrlParameters[d(e[1])] = d(e[2]);
	},
	
	Next: function()
	{
		if (this.CurrentSlide == null || this.CurrentSlide.Index() >= this.Slides.length - 1) {
			this.CurrentSlide = this.Slides[0];
		} 
		else 
		{
			this.CurrentSlide = this.Slides[this.CurrentSlide.Index() + 1];
		}
		this.GoToSlide(this.CurrentSlide);
	},
	
	Previous: function()
	{
		if (this.CurrentSlide.Index() < 1) {
			this.CurrentSlide = this.Slides[this.Slides.length - 1];
		} 
		else 
		{
			this.CurrentSlide = this.Slides[this.CurrentSlide.Index() - 1];
		}
		this.GoToSlide(this.CurrentSlide);
	},
	
	NextSlide: function()
	{
		if (!this.CursorOver) this.Next();
	},
	
	GoToSlide: function(slide)
	{
		if(this.Playing == true) this.VideoClose();

		if(this.Slides.length == 1)
		{
			$('#slide' + slide.Index()).addClass('selectedTab');
			slide.DOM.show().stop().animate({ opacity: 1 }, this.FadeSpeed, function() {
				slide.DOM.css("z-index", "1000");

				if(slide.Type == "Flash") {
					WidgetHandler.LoadFlashSlide(slide);
				}
			});
			
			if (this.Timer != null) clearInterval(this.Timer);
		}
		else if(slide != this.PreviousSlide)
		{
			if(this.PreviousSlide != null)
			{
				var previousId = this.PreviousSlide.Id;

				this.PreviousSlide.DOM.show().stop().animate({ opacity: 0 }, this.FadeSpeed, function() { 
					WidgetHandler.PreviousSlide.DOM.css("z-index", "1"); 
					if(WidgetHandler.PreviousSlide.Type == "Flash") {
						WidgetHandler.PreviousSlide.DOM.empty();
						WidgetHandler.PreviousSlide.DOM.append('<div id="widgetItemFlash-' + previousId + '"></div>');
					}

					WidgetHandler.PreviousSlide = WidgetHandler.CurrentSlide;
				});
				$('.slide').removeClass('selectedTab');
			}
			else this.PreviousSlide = this.CurrentSlide;
			
			$('#slide' + slide.Index()).addClass('selectedTab');
			slide.DOM.show().stop().animate({ opacity: 1 }, this.FadeSpeed, function() {
				slide.DOM.css("z-index", "1000");

				if(slide.Type == "Flash") {
					WidgetHandler.LoadFlashSlide(slide);
				}
			});
			
			if (this.Timer != null) clearInterval(this.Timer);
			this.Timer = setTimeout("WidgetHandler.NextSlide()", this.Delay)
		}
	},

	LoadFlashSlide: function(slide) {
		var params = { };
		params.allowScriptAccess = "always";
		params.wmode = "transparent";
		
		var flashvars = { };
		flashvars.xmlPath = slide.FlashFallback.DataPath;
	
		var flashPlayerPath = (slide.FlashFallback.VideoPath != null ? slide.FlashFallback.VideoPath : slide.FlashFallback.VideoPlayerPath);
		if(swfobject.hasFlashPlayerVersion("9.0.0"))
			swfobject.embedSWF(flashPlayerPath, "widgetItemFlash-" + slide.Id, "728", "366", "9.0.0", slide.ExpressInstallationPath, flashvars, params);
		else
		{
			var imageFallback = $("#widgetItemFlash-" + slide.Id + " img");
			if(imageFallback.length > 0) $(imageFallback.eq(0)).show();
		}
	},
	
	VideoInit: function()
	{
		this.VideoProgress();
		this.InitVideoVolume();

		$(this.CurrentSlide.Video).bind('progress', function() {
			if ((WidgetHandler.CurrentSlide.Video.buffered != undefined) && (WidgetHandler.CurrentSlide.Video.buffered.length != 0)) {
				var loaded = parseInt(((WidgetHandler.CurrentSlide.Video.buffered.end(0) / WidgetHandler.CurrentSlide.Video.duration) * 100), 10);
				WidgetHandler.CurrentSlide.VideoBufferBar.css({ width: loaded + '%' });
			}
		});
		
		$(this.CurrentSlide.Video).bind('timeupdate', function() {
			WidgetHandler.CurrentSlide.Percentage = 0;
			if (WidgetHandler.CurrentSlide.Video.duration != null && WidgetHandler.CurrentSlide.Video.duration != "undefined" && WidgetHandler.CurrentSlide.Video.duration > 0) {
				WidgetHandler.CurrentSlide.Percentage = 100 * WidgetHandler.CurrentSlide.Video.currentTime / WidgetHandler.CurrentSlide.Video.duration;
			}

			if(WidgetHandler.CurrentSlide.Video.currentTime == WidgetHandler.CurrentSlide.Video.duration) {
				WidgetHandler.Paused = true;
				WidgetHandler.CurrentSlide.PlayButton.removeClass("videoPlay").addClass("videoPause");
			}

			WidgetHandler.CurrentSlide.VideoProgressBar.css("width", WidgetHandler.CurrentSlide.Percentage + "%");
			WidgetHandler.UpdateTimeDisplay();
		});
			
		this.CurrentSlide.VideoProgressContainer.click(function(e) {
			var x = e.pageX - $(this).offset().left;
			var pos = x / $(this).width();
			WidgetHandler.CurrentSlide.Video.currentTime = WidgetHandler.CurrentSlide.Video.duration * pos;
			if(WidgetHandler.Paused == true)
				WidgetHandler.CurrentSlide.Video.pause();
		});
	},
	
	VideoOpen: function() 
	{
		if(supports_video())
		{
			this.VideoInit();
			this.CurrentSlide.VideoContainer.css("display", "block");
			this.Playing = true;
			
			if(this.ShowingShareMenu == true)
			{
				this.CurrentSlide.ShareMenu.css("display", "none");
				this.ShowingShareMenu = false;
			}
			
			if(!this.ShowMovieOnLoad) this.VideoPlayPauseToggle();
			else if(this.ShowMovieOnLoad && navigator.userAgent.toLowerCase().indexOf("ipad") == -1) this.VideoPlayPauseToggle();
		}
		else
		{
			this.PageContainer.css('display','none');
			this.WidgetContainer.css('display','none');
			this.CurrentSlide.DOM.find('div.widgetVideo').css("display", "none");
			this.Playing = true;
			
			var params = { };
			params.allowScriptAccess = "always";
			params.allowFullScreen = true;
			params.wmode = "transparent";
			
			var flashvars = { };
			flashvars.vidId = this.CurrentSlide.FlashFallback.VideoId;
			flashvars.vidPath = this.CurrentSlide.FlashFallback.VideoPath;
			flashvars.stillPath = this.CurrentSlide.FlashFallback.VideoStillPath;
			flashvars.autoPlay = true;
			
			if(	(this.CurrentSlide.FlashFallback.ExtraLink != null && this.CurrentSlide.FlashFallback.ExtraLink.length > 0) &&
				(this.CurrentSlide.FlashFallback.ExtraLabel != null && this.CurrentSlide.FlashFallback.ExtraLabel.length > 0)) 
			{
				flashvars.extraLink = this.CurrentSlide.FlashFallback.ExtraLink;
				flashvars.extraTarget = this.CurrentSlide.FlashFallback.ExtraTarget;
				flashvars.extraLabel = this.CurrentSlide.FlashFallback.ExtraLabel;
			}
			else
			{
				flashvars.extraLink = undefined;
				flashvars.extraTarget = undefined;
				flashvars.extraLabel = undefined;
			}
			
			var videoPlayerPath =  this.CurrentSlide.FlashFallback.VideoPlayerPath;
			
			swfobject.embedSWF(videoPlayerPath, "widgetFlashVideo", "728", "360", "9.0.0",  this.CurrentSlide.FlashFallback.ExpressInstallationPath, flashvars, params);
			this.WidgetFlashVideoContainer.css('display','block');
		}
	},
	
	VideoClose: function()
	{
		if(!supports_video())
		{
			this.WidgetContainer.css("display", "block");
			this.WidgetFlashVideoContainer.css("display", "none");
			this.Playing = false;
			this.WidgetFlashVideoContainer.empty();
			this.WidgetFlashVideoContainer.append('<div id="widgetFlashVideo"></div>');
		}
		else
		{
			if(this.FullSize == true)
			{
				this.VideoFullScreenToggle();
			}
			else
			{
				try
				{
					this.CurrentSlide.Video.pause();
					this.CurrentSlide.Video.currentTime = 0.0;
				}
				catch(err) { }
				
				this.CurrentSlide.DOM.find("div.widgetVideo").css("display", "none");
				this.Playing = false;
				this.Paused = true;
				this.CurrentSlide.PlayButton.removeClass("videoPlay").addClass("videoPause");
				this.NextSlide();
			}
		}
	},
	
	VideoProgress: function()
	{
		if (this.CurrentSlide.Video.duration && this.CurrentSlide.Video.duration != "undefined" && this.CurrentSlide.Video.duration != null && this.CurrentSlide.Video.duration > 0) {
			this.CurrentSlide.Percentage= 100 * this.CurrentSlide.Video.currentTime / this.CurrentSlide.Video.duration;
			this.CurrentSlide.Video.currentTime = this.CurrentSlide.Video.duration * this.CurrentSlide.Percentage / 100;
		}
	},
	
	InitVideoVolume: function()
	{
		this.CurrentSlide.Video.volume = 1;
		$(this.CurrentSlide.Video).bind('volumechange', function() {
			var slide = WidgetHandler.CurrentSlide;
			
			slide.VideoVolumeBar.css("width", slide.Video.volume*100 + "%");
			
			if(slide.Video.muted == true) slide.VideoSoundContainer.find("a").removeClass("active");
			else slide.VideoSoundContainer.find("a").addClass("active");
		});
		this.CurrentSlide.VideoSoundContainer.find("a").click(function(e) {
			e.preventDefault();
			var video = WidgetHandler.CurrentSlide.Video;
			if(video.muted == true) video.muted = false;
			else video.muted = true;
		});
		this.CurrentSlide.DOM.find('.video_sound_volume').click(function(e) {
			var x = e.pageX - $(this).offset().left;
			var vol = x / this.CurrentSlide.DOM.find('.video_sound_volume').width();
			
			if(vol > 1) this.CurrentSlide.Video.volume = 1;
			else if (vol < 0 ) this.CurrentSlide.Video.volume = 0;
			else this.CurrentSlide.Video.volume = vol;
		});
	},
	
	VideoPlayPauseToggle: function()
	{
		if(this.Playing == true)
		{
			if(this.Paused == true)
			{
				this.CurrentSlide.Video.play();
				this.Paused = false;
				
				this.CurrentSlide.PlayButton.removeClass("videoPause").addClass("videoPlay");
			}
			else
			{
				this.CurrentSlide.Video.pause();
				this.Paused = true;
				
				this.CurrentSlide.PlayButton.removeClass("videoPlay").addClass("videoPause");
			}
		}
	},
	
	VideoFullScreenToggle: function()
	{
		if(this.FullSize == true)
		{
			this.FullSize = false;
		}
		else
		{
			if (navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") == -1) 
			{
				// Only for Safari
				this.CurrentSlide.Video.webkitEnterFullScreen();
			}
			else
			{
				this.FullSize = true;
				var winWidth = window.innerWidth + "px";
				var winHeight = window.innerHeight + "px";
			
				this.CurrentSlide.VideoContainer.css( { position: 'fixed', left: 0, top: 0 });
				this.CurrentSlide.VideoContainer.animate({ height: winHeight, width: winWidth }, 1);
				
				this.CurrentSlide.Video.style.top = 0;
				this.CurrentSlide.Video.style.left = 0;
				this.CurrentSlide.Video.style.paddingLeft = 0;
				$(this.CurrentSlide.Video).animate({ height: winHeight, width: winWidth }, 1);
				
				this.CurrentSlide.VideoControls.css("bottom", 0);
				this.CurrentSlide.VideoControls.animate({ width: winWidth }, 1);
				this.CloseButton.css("position", "fixed");
				
				if(this.ShowingShareMenu == true) this.CurrentSlide.ShareMenu.animate({ width: winWidth }, 1);
			}
		}
	},
	
	VideoResetSize: function()
	{
		this.CurrentSlide.VideoContainer.css('position','absolute');
		this.CurrentSlide.VideoContainer.animate({ height: 360, width: 728 }, 1);

		this.CurrentSlide.Video.style.paddingLeft = "44px";
		$(this.CurrentSlide.Video).animate({ height:'360', width:'640'}, 1);

		this.CurrentSlide.VideoControls.css("paddingLeft", 0);
		this.CurrentSlide.VideoControls.animate({ width: 728 }, 1);

		this.CloseButton.css("position", "absolute");
		if(this.ShowingShareMenu == true) this.CurrentSlide.ShareMenu.animate({ width: 728 }, 1);
	},
	
	UpdateTimeDisplay: function()
	{
		this.CurrentSlide.VideoCurrentTimeDisplay.html(this.FormatTime(this.CurrentSlide.Video.currentTime));
		if(this.CurrentSlide.Video.duration && this.CurrentSlide.Video.duration != null && this.CurrentSlide.Video.duration != undefined)
			this.CurrentSlide.VideoDurationDisplay.html('<span style="display:inline-block; padding-right:6px;">/</span>' + this.FormatTime(this.CurrentSlide.Video.duration));
	},
	
	// Return seconds as MM:SS
	FormatTime: function(seconds)
	{
		seconds = Math.round(seconds);
		minutes = Math.floor(seconds / 60);
		minutes = (minutes >= 10) ? minutes : "0" + minutes;
		seconds = Math.floor(seconds % 60);
		seconds = (seconds >= 10) ? seconds : "0" + seconds;
		return minutes + ":" + seconds;
	},
	
	ShareMenuToggle: function()
	{
		var winWidth = window.innerWidth + "px";
		if (this.ShowingShareMenu == false)
		{
			this.CurrentSlide.ShareMenu.css("display", "block");
			if(this.FullSize == true) this.CurrentSlide.ShareMenu.animate({ width: winWidth }, 1);
			this.ShowingShareMenu = true;
		}
		else
		{
			this.CurrentSlide.ShareMenu.css("display", "none");
			this.ShowingShareMenu = false;
		}
	},
	
	OpenShareWindow: function(type)
	{
		var baseUrl = window.location.toString().toLowerCase();
		
		if(baseUrl.indexOf((WidgetHandler.Override_ShareUrl == null ? 'default' : WidgetHandler.Override_ShareUrl.substr(0, WidgetHandler.Override_ShareUrl.indexOf('.') > -1 ? WidgetHandler.Override_ShareUrl.indexOf('.') : WidgetHandler.Override_ShareUrl.length)).toLowerCase()) == -1)
			baseUrl += (baseUrl.substr(-1) === "/" ? '' : '/') + (WidgetHandler.Override_ShareUrl == null ? 'default.aspx' : WidgetHandler.Override_ShareUrl);
			
		var url = baseUrl + "?i=" + WidgetHandler.CurrentSlide.Index() + "&m=1";
		var settings = "toolbar=0,status=0,width=800,height=500,location=1";
		
		switch(type) 
		{
			case "facebook": 
				url = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(url); 
				break;
			case "twitter": 
				url = "http://twitter.com/home?status=Look:+" + encodeURIComponent(url); 
				//settings = ""; 
				break;
			case "delicious": 
				url = "http://del.icio.us/post?v=4&amp;partner=[partner]&amp;noui&amp;jump=close&amp;url=" + encodeURIComponent(url); 
				break;
			case "email": 
				url = ""; 
				ShowModal('emailpage.aspx?url=' + (WidgetHandler.Override_ShareUrl == null ? 'default.aspx' : WidgetHandler.Override_ShareUrl) + '?i=' + WidgetHandler.CurrentSlide.Index() + '&m=1', 470, 500);
				break;
			default: url = ""; break;
		}

		if(url.length > 0) 
		{
			var popup = window.open(url, "share", settings);
			if(popup)
				popup.focus();
		}
	}
}
