/* --- scope ends up being something like this:

<div class="flvpage">
	<div class="flvtop">
		<div class="flvplayer"></div>
		<div class="desc_area">
			<div class="title">Title</div>
			<div class="description">Description <span class="duration">(1:00)</span></div>
			<div class="more"><a href="#">Link</a></div>
		</div>
		<div class="chapter_area">
			<div class="chapter_title">Jump within this video:</div>
			<ul>
				<li><a href="#">
					<img src="#" />
					<span class="description">
						<span class="title">Chapter 1</span><span class="duration">(1:00)</span>
					</span>
				</a></li>
			</ul>
		</div>
	</div>
	<div class="flvbottom">
		<ul>
			<li><a href="#flv_tab_all">All Videos</a></li>
			<li><a href="#flv_tab_1">More Info</a></li>
			<li><a href="#flv_tab_email">Email This</a></li>
		</ul>
		<div id="flv_tab_all"></div>
		<div id="flv_tab_1"><iframe src="#"></iframe></div>
		<div id="flv_tab_email"><iframe src="#"></iframe></div>
	</div>
</div>

*/


(function() {
	jQuery.fn.flvPage = function(o) {
		return this.each(function() {
			new jQuery.flvPage(this, o);
			})
		};
	
	jQuery.flvPage = function(e, o) {
		var publ = this;
		jQuery.extend(publ, {
			scope : function() { return priv.scope },
			player : function() { return priv.player }
			});
		
		window.fp = publ;
		
		var priv = {
			o: {
				autoPlay: location.hash ? location.hash.substr(location.hash.indexOf('#')+1) : true
				},
			
			scope: null,
			player: null,
			
			init: function(e, o) {
				if(o) jQuery.extend(priv.o, o);
				
				var s = priv.scope = jQuery(e);
				var pl = priv.readPlaylist(s);
				s.empty().append('<div class="flvpage"><div class="flvtop"><div class="flvplayer"></div><div class="desc_area"></div><div class="chapter_area" style="display: none"><div class="chapter_title">Jump within this video:</div><ul></ul></div></div><div class="flvbottom"><ul><li><a href="#flv_tab_all">All Videos</a></li><li><a href="#flv_tab_email">Email This</a></li></ul><div id="flv_tab_all"></div><iframe width="100%" scrolling="yes" frameborder="0" id="flv_tab_email"></iframe></div></div>');
				
				s.find('#flv_tab_email').attr('src', $.absUrl('../html/email_this.html'));
				
				s.find('.flvplayer').flvPlayer({
					playlist: pl,
					repeat: true,
					autoPlay: priv.o.autoPlay,
					initHandler: function() {
						priv.player = this;
						priv.playlistChange();
						},
					clipChangeHandler: priv.clipChange,
					chapterChangeHandler: priv.chapterChange
					});
				
				s.find('.flvbottom').tabs(1);
				priv.resizeTabArea();
				$(window).resize(priv.resizeTabArea);
				},
			
			playlistChange : function() {
				var p = priv.scope.find('#flv_tab_all').empty();
				
				if(!priv.player) return;
				
				var ul = $('<ul class="playlist"></ul>').appendTo(p);
				
				for(var i = 0; i < priv.player.playlist.length; i++) {
					var clip = priv.player.playlist[i];
	 				$('<li></li>')
	 					.append($('<a href="#"></a>')
							.append($('<img class="screenshot" />').attr('src', clip.metadata.image))
							.append($('<span class="info"></span>')
								.append($('<strong class="title"></strong>').text(clip.metadata.title)
									.append($('<span class="duration"></span>').text(' ('+FLVPlayer_Clip.formatTime(clip.duration)+')'))
									)
								.append($('<span class="description">').text(clip.metadata.description))
								)
							)
						.click(makeClick(i))
						.appendTo(ul);
					}
				
				function makeClick(n) {
					return function() { priv.player.play(n); return false; };
					}
				
				priv.scope.find('#flv_tab_all > ul > li').removeClass('current').eq(priv.player.currentNum()).addClass('current');
				
				// if(priv.player && priv.player.playlist.length > 1) {
				// 	priv.scope.find('.flvbottom > ul > li > a[@href$=#flv_tab_all]').parent().show();
				// 	priv.scope.find('.flvbottom > #flv_tab_all').show();
				// 	}
				// else {
				// 	priv.scope.find('.flvbottom > ul > li > a[@href$=#flv_tab_all]').parent().hide();
				// 	priv.scope.find('.flvbottom > #flv_tab_all').hide();
				// 	}
				},
			
			clipChange : function(num, clip, status) {
				// fill in description info
				var d = priv.scope.find('.desc_area');
				d.empty().append('<div class="title"></div><div class="description"></div>');
				if(clip.metadata.formattedTitle) {
					d.find('.title').html(clip.metadata.formattedTitle);
					}
				else {
					d.find('.title').text(clip.metadata.title);
					}
				if(clip.metadata.formattedDescription) {
					d.find('.description').html(clip.metadata.formattedDescription);
					}
				else {
					d.find('.description').text(clip.metadata.description);
					}
				d.find('.description').append('<span class="duration"></span>');
				d.find('.description .duration').text(' ('+FLVPlayer_Clip.formatTime(clip.duration)+')');
				var l = clip.metadata.links || [];
				for(var i = 0; i < l.length; i++) {
					var x = $('<div class="more"><a target="_blank"></a></div>');
					x.find('a').text(l[i][1]);
					x.find('a').attr('href', l[i][0]);
					d.append(x);
					}
				
				// fill in chapters
				var c = priv.scope.find('.chapter_area');
				c.find('ul').empty();
				if(clip.numChapters()) {
					for(var i = 0; i < clip.numChapters(); i++) {
						var ch = clip.getChapter(i);
						var x = $('<li><a><img /><span class="info"><span class="description"></span><span class="duration"></span></span></a></li>');
						x.find('img').attr('src', ch[1].image);
						x.find('.description').text(ch[1].description);
						x.find('.duration').text(' ('+FLVPlayer_Clip.formatTime(clip.chapterDuration(i))+')');
						x.find('a').click(makeSeek(ch[0]));
						c.find('ul').append(x);
						}
					c.show();
					}
				else {
					c.hide();
					}
				
				function makeSeek(s) {
					return function() { priv.player.seek(s); return false; };
					}
				
				priv.scope.find('#flv_tab_all > ul > li').removeClass('current').eq(num).addClass('current');
				
				// fill in tabs
				priv.scope.find('.flvbottom > ul > li').gt(1).remove();
				priv.scope.find('.flvbottom > .tabs-container').gt(1).remove();
				var t = clip.metadata.tabs || [];
				for(var i = 0; i < t.length; i++) {
					$('<li></li>').append($('<a></a>').attr('href', '#flv_tab_'+(i+1)).text(t[i][1])).appendTo(priv.scope.find('.flvbottom > ul'));
					$('<iframe width="100%" scrolling="yes" frameborder="0"></iframe>').attr('id', 'flv_tab_'+(i+1)).addClass('tabs-container').attr('src', t[i][0]).appendTo(priv.scope.find('.flvbottom'));
					}
				priv.scope.find('.flvbottom').tabs(t.length ? 3 : 1);
				priv.resizeTabArea();
								
				},
			
			chapterChange : function(num, chapter) {
				var cc = priv.scope.find('.chapter_area li').removeClass('current').eq(num).addClass('current');
				if(cc.length) {
					var o = cc[0];
					var p = cc.parent()[0];
					p.scrollTop = o.offsetTop - p.offsetTop;
					}
				},
				
			resizeTabArea : function() {
				function getWindowHeight() {
					var windowHeight = 0;
					if (typeof(window.innerHeight) == 'number') {
						windowHeight = window.innerHeight;
						}
					else {
						if (document.documentElement && document.documentElement.clientHeight) {
							windowHeight = document.documentElement.clientHeight;
							}
						else {
							if (document.body && document.body.clientHeight) {
								windowHeight = document.body.clientHeight;
								}
							}
						}
					
					return windowHeight;
					}
				
				var height = getWindowHeight();
				try {
					// guess what browser this randomly fails in sometimes (hint: starts with "I" ends with "E")
					priv.scope.find('.tabs-container').height(height-498);
					}
				catch(e) {}
				},
			
			/* --- readPlaylist digests something like this:
			
			<div class="playlist">
				<div class="clip" id="gsob">
					<h1 class="title">A Greener Shade of Blue: UB's Environmental Leadership</h1>
					<span class="date">9/18/2006</span>
					<p class="description">From pioneering efforts more than three decades ago to President John Simpson&rsquo;s signing of the American College and University Presidents Climate Commitment to fight global warming, the University at Buffalo has led the way in environmental stewardship. This video provides an overview of the green paths forged by UB in research, education, and practice around our campus, the region, and the world.</p>
					<span class="duration">3:52</span>
					<a href="#">Visit a Greener Shade of Blue Web site</a>
					<img src="video_thumbnails/interfaith/main.jpg" />
					<a rel="tab" href="video_info_interfaith.html">More Info</a>
					<a rel="stream:350000" href="playlists/interfaith/high.smil">Flash High Bandwidth</a>
					<a rel="stream:35000" href="playlists/interfaith/low.smil">Flash Low Bandwidth</a>
					<ul>
						<li>
							<a rel="chapter" href="#3:50">
								<img src="video_thumbnails/interfaith/flute.jpg" />
								Musical Prelude (Nawang Khechog, Tibetan flute master)
							</a>
						</li>
						<li>
							<a rel="chapter" href="#20:15.2">
								<img src="video_thumbnails/interfaith/welcome.jpg" />
								Welcome (Bert Gambini, Master of Ceremonies)
							</a>
						</li>
					</ul>
				</div>
			</div>
			
			*/

			readPlaylist : function(el) {
				return $.map( $(el).find('.clip'), parseClip );

				function parseClip(el) {
					var el = $(el);
					var clip = new FLVPlayer_Clip();
					clip.metadata.id = el.attr('id');
					clip.metadata.title = $.trim(el.find('.title').text());
					clip.metadata.formattedTitle = $.trim(el.find('.title').html());
					clip.metadata.date = $.trim(el.find('.date').text());
					clip.metadata.description = $.trim(el.find('.description').text());
					clip.metadata.formattedDescription = $.trim(el.find('.description').html());
					clip.metadata.image = abs(el.find('img').attr('src'));
					clip.duration = FLVPlayer_Clip.parseTime(el.find('.duration').text());
					clip.metadata.links = $.map( el.find('a').not('[@rel]'), function(a) { return [ [ abs($(a).attr('href')), $.trim($(a).text()) ] ] } );
					clip.metadata.tabs = $.map( el.find('a[@rel=tab]'), function(a) { return [ [ abs($(a).attr('href')), $.trim($(a).text()) ] ] } );
					el.find('a[@rel^=stream:]').each(function() {
						clip.addStream(abs($(this).attr('href')), parseFloat($(this).attr('rel').split(':')[1]) || 0);
						});
					el.find('a[@rel^=chapter]').each(function() {
						var offset = $(this).attr('href');
						offset = offset.substr(offset.lastIndexOf('#')+1);
						clip.addChapter(FLVPlayer_Clip.parseTime(offset), {
							description: $.trim($(this).text()),
							image: abs($(this).find('img').attr('src'))
							});
						});
					
					return clip;
					}
				
				function abs(url) {
					if(url.length == 0) return "";
					if(url.indexOf('://') > -1) return url;
					if (url.substr(0, 1) == '/') return location.href.substr(0, location.href.indexOf('/', 8)) + url;
					return location.href.substr(0,location.href.lastIndexOf('/')+1) + url;
					}
				
				}
			
			};
		
		priv.init(e, o);
		};
	})();
