(function($){
	
	var buttontext = ['Click here', 'Click here', 'Click here'];

	$(function(){
		var query = window.location.search.match(/video=.*?(?=(&|$))/)
		if(query){
			$.medialibrary({href: query[0].replace('video=', ''), hash: window.location.hash}, '/1/PA_1_083Q9FJ08A002FBP5S00000000/content/flash/index.swf');
		}
	});

	$.medialibrary = function(link,flash){
		if(!link || !link.href){
			throw new Error('Media Library file path not defined');
			return;
		}
		if(!flash) {
			throw new Error('Media Player file name not defined.');
			return;
		}
		medialibrary.open(link,flash);	
	}
	
	$.medialibrary.recommend = function(id){
		if(medialibrary.isOpen) {
			var rec = $('#'+id+' p.recommendation a').attr('href');
			medialibrary.recommend.apply($(rec));
		}
	}
	
	$.medialibrary.play = function(id){
		if(medialibrary.isOpen) {
			medialibrary.play.apply($('#'+id));
		}
	}
	
	var medialibrary = {
		
		open:function(link,flash) {
			var obj = this;
			
			this.link = link
			this.overlay = $.overlay().append('<div class="intro"><h2 tabindex="0"></h2><p class="transcripts"><a href="/1/2/international/transcripts">Transcripts available</a></p></div><p class="subtitle"></p><div id="flash_movie"><p>Either you do not have Flash Player installed or it is disabled. Please <a href="http://get.adobe.com/flashplayer/">dowload the latest version</a> or alternatively continue to the <a href="change me">image gallery</a>.</p></div><div id="thumbnails"></div>').addClass('gallery_window_loading');
			this.overlay.bind('overlay.close',function(){
				medialibrary.isOpen = false;
				if(obj.link.focus){
					obj.link.focus();
				}
			});
			this.isOpen = true;

			var source = this.link.href;
			var hash = this.link.hash.replace('#','');
			source = source.split('#')[0].split('?')[0].split(';')[0];
			var path = source.match(/http:\/\/.*?(\/.*)/);
			path = (path) ? path[1] : source;
			path = path.replace(/index\..*?$/, '');

			var f = new HW.Flash();
			f.width = 750;
			f.height = 462;
			f.src = [8,flash+'?thumbPath='+path];
			f.name = 'video_player';
			f.id = 'video_player';
			f.allowScriptAccess = 'always';
			f.load('flash_movie');
			
			this.swf = window['video_player']||document['video_player'];
			
			$('#thumbnails').load(source+' ul.mediaThumbnails', function(){
				medialibrary.loaded(hash);
			});
			
		},
		
		loaded:function(hash) {
				
			if(hash && $('#thumbnails ul.mediaThumbnails li#'+hash).length) {
				medialibrary.play.apply($('#thumbnails ul.mediaThumbnails li#'+hash));
			}
			else {
				medialibrary.play.apply($('#thumbnails ul.mediaThumbnails li:first'));
			}
			
			$('#thumbnails ul.mediaThumbnails').carousel({offset:20,easing:'easeOutQuart'});
			
			$('#thumbnails ul.mediaThumbnails li .info').css({bottom:'-47px'});
			$('#thumbnails ul.mediaThumbnails li').hover(function(){
					$(this).find('.info').stop().animate({bottom:'0px'},'fast');
				},function(){
					$(this).find('.info').stop().animate({bottom:'-47px'},'fast');
				});
			
			$('#thumbnails ul.mediaThumbnails li p.recommendation').hide();
			$('#thumbnails ul.mediaThumbnails li p.related').hide();
			
			$('#thumbnails ul.mediaThumbnails li').click(medialibrary.play);
			
			
			$('.gallery_window_loading').removeClass('gallery_window_loading');
			
		},
			
		play:function() {
			
			var $this = $(this);
			try {
				$this.parent().find('li').removeClass('selected');
				$this.addClass('selected');
				$('#thumbnails ul.mediaThumbnails').trigger('adjust');
				medialibrary.overlay.find('h2').html($this.find('h3 a').html()).focus();
				medialibrary.overlay.find('p.subtitle').html($this.find('p.description').html());
				var str = [];
				$this.find('p.related a').each(function() {
					if($(this).attr('title') != "")
						str.push($(this).attr('href') + '++' + $(this).text() + '++' + $(this).attr('title'));
					else
						str.push($(this).attr('href') + '++' + $(this).text());
				});
				medialibrary.swf.loadMedia($this.find('h3 a').attr('href'),$this.attr('id'),str.join('--'));
			}
			catch(e) {
				setTimeout(function(){medialibrary.play.apply($this);},100);
			}
			return false;
			
		},
		
		recommend:function() {
			
			var $this = $(this);
			medialibrary.swf.setRecommendationData($this.attr('id'),$this.find('img').attr('src'),$this.find('h3 a').html(),$this.find('p.description').html());
			
		}
		
	}
	
	$.overlay = function() {
		var $content;
		
		function build() {
			
			if($.browser.msie && $.browser.version < 7) {
				$(document.body).append('<iframe class="gallery_mask"></iframe>');
			}
			$(document.body).append('<div class="gallery_mask"></div><div class="gallery_window"><div class="gallery_window_close"><a title="Close" href="#"></a></div><div class="gallery_window_top"><div class="gallery_window_content"></div></div><div class="gallery_window_bottom"></div>');
			
			$('.gallery_mask').css({height:$(document.body).height()});
			
			$content = $('.gallery_window_content');//.bind('overlay.close',close);
			$('.gallery_window_close a').click(function(){close();return false;});
			
			var top = $(window).scrollTop() + 100;
			$('.gallery_window').css({top:top+'px'});
			
			return $content;
		}
		
		function close() {
			$content.trigger('overlay.close');
			$content.find('object,embed').remove();
			$('.gallery_mask,.gallery_window').remove();
		}
		
		return build();
	}
	
	$.fn.carousel = function(opts) {
		
		var defaults = {
			width:	750,
			offset:	0,
			easing:	'swing',
			speed:	'slow'
		}
		
		opts = $.extend(defaults,opts);
		
		return $(this).each(function(){
		
			var $this = $(this);
			
			$this.wrap('<div class="carousel"><div class="carousel_window"><div class="carousel_inner"></div></div></div>');
			
			$this.closest('.carousel').append('<a href="#" class="carousel_left"></a><a href="#" class="carousel_right"></a>');
			$this.closest('.carousel_window').css({width:opts.width+'px'});
			
			$this.closest('.carousel').find('a.carousel_left,a.carousel_right').click(function(){move($(this).hasClass('carousel_left')?-1:1);return false;});
			
			var w = 0;
			$this.find('li').each(function(){w+=$(this).outerWidth(true);});
			
			var steps = $this.find('li').size(),
				visible = Math.ceil(opts.width/$this.find('li').outerWidth(true));
			$this.closest('.carousel_inner').css({width:w+'px'});
			
			$this.bind('adjust', function(){
				//test whether the lozenge for the selected video is inside the visible window area and adjusts if needed
				var $selected = $this.find('.selected');
				var lozOuterWidth = $selected.outerWidth(true);
				var $left = $selected[0].offsetLeft;
				var $cWindow = $this.closest('.carousel_window');
				var $inner = $this.closest('.carousel_inner');
				var $discrepency = $cWindow.width() - $selected[0].offsetLeft - $selected.outerWidth() - $inner[0].offsetLeft;
				if($discrepency < 0){
					
					$inner.css({
						left: $inner[0].offsetLeft + $discrepency
					});
					$this.data('cur', Math.round($left/lozOuterWidth + 1 - ($cWindow.width()/lozOuterWidth)));
				}
			});
			
			function move(d) {
				
				var	cur = $this.data('cur') || 0;
				var	to = Math.max(Math.min(steps-visible,cur+d),0);
				var lft = -1*to*$this.find('li').outerWidth(true)
				if(to != cur && (lft+'px') != $this.closest('.carousel_inner').css('left')) {
					$this.data('cur',to);
					$this.closest('.carousel_inner').stop().animate({left:lft+'px'},opts.speed,opts.easing,$this.trigger('carousel.move',to));
				}
			}
		
		});
	}

})(jQuery)