$(document).ready(function() {

	$( "#own #purchase_type_select img" ).click( function() { 

		var clicked = this;

		$( this ).parent().fadeOut( "fast", function() {

			// jQuery wont do it....?
			$( this ).css( "display", "none" );

			if( $( clicked ).hasClass( "dvd" ) )
			{
				var option = $( "#own #download_format ul li a[rel='dvd']" );
			} else {
				var option = $( "#own #download_format ul li[rel!='false'] a[rel!='dvd']" );

				if( !option.length )
					option = $( "#own #download_format ul li a[rel='mp4-std']" );
				if( !option.length )
					option = $( "#own #download_format ul li:not(.listheader) a[rel!='dvd']" );

				if( option.length > 1 )
					option = option[0];
			}

			$( "#own #download_format > span" ).text( $(option).text() ) ;
			$( "#own #download_format input" ).val( $(option).attr( "rel" ) );
			
			if( $(option).parent().attr( "rel" ) != "false" )
			{	
				updateStats();
				$( "#own #purchase_config" ).css( "display", "block" )
				$( "#own #purchase_request" ).css( "display", "none" )
			} else {
				$( "#own #purchase_config" ).css( "display", "none" )
				$( "#own #purchase_request" ).css( "display", "block" )
			}
			
			var image = $( "#own .buy_image" );
			if( !$( image ).hasClass( $( "#own #download_format input" ).val() ) )
			{
				if( $( "#own #download_format input" ).val() == "dvd" )
				{
					$( image ).removeClass( "download" ).addClass( "dvd" );
					$( "#own #purchase_clip" ).fadeOut( "fast" );
				} else {
					$( image ).removeClass( "dvd" ).addClass( "download" );
					$( "#own #purchase_clip" ).fadeIn( "fast" );
				}
			}
			
			$( "#own #purchase_options" ).show();
		});

		return false;
	});

	$( "#own .select" ).click( function() {
		var id = $( this ).attr( "id" );

		$( "#own .select" ).each( function() {
			if( id != $( this ).attr( "id" ) )
				$( this ).children( "div" ).slideUp();
		});

		$( this ).children( "div" ).slideToggle();

		return false;
	});

	$( "#own #purchase_clip ul li a" ).click( function() {

		$( "#own #purchase_clip input[name=purchase_clip]" ).val( $( this ).attr( "rel" ) );

		updateStats();
		
		if( $( this ).attr( "rel" ) == "clip" )
		{
			var target = $( "#pageWrapper" ).offset().top;
			$('html,body').animate( {scrollTop: target}, 1000 );

			//the try block hides the errors created
			//the flashObject won't be available until the
			//the player fully loads
			try
			{
				var flashObject = document.getElementById('flashPlayer');

				if ( flashObject )
				{
					flashObject.showEditView();
				}
			}
			catch(err)
			{
			}
		}

		$( this ).children( "div" ).slideToggle();

	});

	$( "#own #download_format ul li a" ).click( function() {
		$( "#own #download_format > span" ).text( $( this ).text() ).attr( "rel", $( this ).children( "span" ).attr( "rel" ) ) ;

		$( "#own #download_format input" ).val( $( this ).attr( "rel" ) );

		$( "#own #download_format div" ).slideUp();

		if ($(this).attr("rel") == 'mp4-high')
		{
			$( "#own #purchase_clip input[name=purchase_clip]" ).val('clip');
			updateStats();
			if( $( "#own #purchase_config" ).css( "display" ) != "block" )
			{
				$( "#own #purchase_request" ).fadeOut( "fast", function() {
					$( "#own #purchase_config" ).fadeIn( "fast" );
				});
			}
			var target = $( "#pageWrapper" ).offset().top;
			$('html,body').animate( {scrollTop: target}, 1000 );

			//the try block hides the errors created
			//the flashObject won't be available until the
			//the player fully loads
			try
			{
				var flashObject = document.getElementById('flashPlayer');

				if ( flashObject )
				{
					flashObject.showEditView();
				}
			}
			catch(err)
			{
			}
		}
		else if( $( this ).parent().attr( "rel" ) != "false" || $(this).attr("rel") == 'mov-std' || $(this).attr("rel") == 'avi-std')
		{
			updateStats();
			if( $( "#own #purchase_config" ).css( "display" ) != "block" )
			{
				$( "#own #purchase_request" ).fadeOut( "fast", function() {
					$( "#own #purchase_config" ).fadeIn( "fast" );
				});
			}
		}
		else
		{
			if( $( "#own #purchase_request" ).css( "display" ) != "block" )
			{
				$( "#own #purchase_config" ).fadeOut( "fast", function() {
					$( "#own #purchase_request" ).fadeIn( "fast" );
				});
			}
		}

		var image = $( "#own .buy_image" );
		var imgclass = $("#own #download_format input").val();
		if(imgclass != "dvd")
			imgclass = "download";
		if( !$( image ).hasClass(imgclass) )
		{
			$( image ).fadeOut( "fast", function() {
				if( $( "#own #download_format input" ).val() == "dvd" )
				{
					$( image ).removeClass( "download" ).addClass( "dvd" );
					$( "#own #purchase_clip" ).fadeOut( "fast" );
				} else {
					$( image ).removeClass( "dvd" ).addClass( "download" );
					$( "#own #purchase_clip" ).fadeIn( "fast" );
				}

				$( image ).fadeIn( "fast" );
			});
		}

		return false; 
	});

	$( "#own #purchase_config a .add_to_cart" ).parent().click( function(e) {
		e.preventDefault();

		var format = $( "#own .purchase_format" ).val();
		var clip = $( "#own #purchase_config input[name=purchase_clip]" ).val();	

		if( ( $( "#own #purchase_config input[name=purchase_clip_start]" ).val() == 0 &&
			$( "#own #purchase_config input[name=purchase_clip_stop]" ).val() == $( "#own #purchase_config input[name=purchase_length]" ).val() )
			|| format == "dvd" )
		{
			clip = "full";
		}
		
//		if( clip == "clip" )
		if(format != 'dvd')
		{
			var programid = $( "#own" ).attr( "rel" );
			if(clip == "full")
			{
				var clipStart = 0;
				var clipStop = 0;
				var clipAction = "showFull";
			}
			else
			{
				var clipStart = $( "#own #purchase_config input[name=purchase_clip_start]" ).val();
				var clipStop = $( "#own #purchase_config input[name=purchase_clip_stop]" ).val();
				var clipAction = "showClip";
			}

			$.ajax({
				url: "/videoLibrary/ajax/create_clip.php",
				type: "GET",
				data: "programid=" + programid + "&format=" + format + "&clipStart=" + clipStart + "&clipStop=" + clipStop + "&action=" + clipAction,
				cache: false,
				success: function( data ) {
//					alert($(data).text());
					if( $( data ).text().match( /Oops!/ ) )
					{
						$.fancybox( data, {scrolling: 'no'} );
						Cufon.refresh('.swap-cufon');
						return;
					}
					
					//Ugly hack, but Safari broke our ability to overlay fancybox over the flash player without messing up the position of the contents.
					var agent = navigator.userAgent.toLowerCase();
					var macsafari_check = false;
					if(agent.indexOf('mac os x') != -1 && agent.indexOf('safari') != -1)
						macsafari_check = true;
					
					if(macsafari_check)
						$("#flashPlayer").hide();
					$.fancybox( data,
					   			{
									modal: true,
									scrolling: 'no'
								} );
					Cufon.refresh('.swap-cufon');

					$( "#fancybox-inner .cancel" ).unbind("click").click( function() {
						$.fancybox.close();
						if(macsafari_check)
							$("#flashPlayer").show();
						return false;
					});

					$( "#fancybox-inner .continue" ).click(function() {
						if(macsafari_check)
							$("#flashPlayer").show();
						downloads_show_tos(function(){
							if(clip == "clip" || format == "mp4-high" || format == "mp3-std" || format == "avi-std" || format == "mov-std" )
							{
								$.ajax({
									url: "/videoLibrary/ajax/create_clip.php",
									type: "GET",
									data: "programid=" + programid + "&format=" + format + "&clipStart=" + clipStart + "&clipStop=" + clipStop + "&action=create",
									cache: false,
									success: function( data ) {
		
										if( $( data ).text().match( /^Oops!.*$/ ) )
										{
											$.fancybox( data, {scrolling: 'no'} );
											Cufon.refresh('.swap-cufon');
											return;
										}
		
										var after_load = function() {
											$.ajax({
												url: "/videoLibrary/ajax/create_clip.php",
												type: "GET",
												data: "programid=" + programid + "&format=" + format + "&clipStart=" + clipStart + "&clipStop=" + clipStop + "&action=getId",
												cache: false,
												success: function( data ) {
		
													if( data.match( /^[0-9]+$/) )
													{
														$( "#own #add_to_cart input[name=buyid]" ).val( data );
														$( "#own #add_to_cart" ).submit();
													} else {
														$.fancybox( "<div>" + data + "</div>", {scrolling: 'no'} );
														Cufon.refresh('.swap-cufon');
													}
												}
											});
										};
		
										$.fancybox( data, { modal: true, onComplete: after_load, scrolling: 'no' } );
										Cufon.refresh('.swap-cufon');
										$.fancybox.showActivity();
										$( "#fancybox-loading" ).css( "margin-top", parseInt(parseInt( $( "#fancybox-loading" ).css( "margin-top" ) ) + 20 ) + "px" );
									}
								});
							}
							else
							{
								$.fancybox.close();
								var id = $( "#own #download_format li a[rel=" + format + "]" ).parent().attr( "rel" );
								$( "#own #add_to_cart input[name=buyid]" ).val( id );
					
								$( "#own #add_to_cart" ).submit();
							}
						});

						return false;
					});
				}
			});			
//		} else if(format != 'dvd') {
//			downloads_show_tos(function(){
//				$.fancybox.close();
//				var id = $( "#own #download_format li a[rel=" + format + "]" ).parent().attr( "rel" );
//				$( "#own #add_to_cart input[name=buyid]" ).val( id );
//	
//				$( "#own #add_to_cart" ).submit();
//			});
		} else {
			var id = $( "#own #download_format li a[rel=" + format + "]" ).parent().attr( "rel" );
			$( "#own #add_to_cart input[name=buyid]" ).val( id );

			$( "#own #add_to_cart" ).submit();
		}

		return false;
	});

	$( "#own .request_download" ).click(function() {
		var programid = $( "#own" ).attr( "rel" );
		var format = $( "#own #download_format input" ).val();

		var parts = format.match( /([a-z0-9]+)-([a-z0-9]+|)/ );

		format = parts[1];

		if(parts[2] == "high" )
			var quality = "high";
		else if(parts[2] == "low")
			var quality = "low";
		else
			var quality = "standard";
	
		$.ajax({
			url: "/videoLibrary/ajax/download_request.php",
			type: "GET",
			data: "programid=" + programid + "&format=" + format + "&quality=" + quality + "&action=request",
			cache: false,
			success: function( data ) {
				$.fancybox( data, {enableKeyboardNav: false, scrolling: 'no'} );
				Cufon.refresh('.swap-cufon');

				$( "#notify_form" ).submit( function(e) {
					e.preventDefault();

					var name = $(this).find( "input[name=name]" ).val();
					var email = $( this ).find( "input[name=email]" ).val();
					var url = $( this ).attr( "action" );
					
					if(email.match(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i))
					{
						$.ajax({
							url: url,
							type: "POST",
							data: {name: name, email: email},
							cache: false,
							success: function( data ) {
								$.fancybox( data, {scrolling: 'no'} );
								Cufon.refresh('.swap-cufon');
							}
						});
					}
					else
						$("#dlReqError").html("Cannot process request: invalid email provided.").show();

					return false;
				});
			}
		});			


		return false;
	});

	$( "#own #download_format ul li:first-child a" ).click();

	$( "#own #purchase_config .price_samples" ).click( function() {
		$.ajax({
			url: "/videoLibrary/ajax/download_pricing_samples.php",
			type: "GET",
			success: function( data ) {
				$.fancybox( data, {
								transitionIn: 'elastic',
								transitionOut: 'elastic',
								easingIn: 'swing',
								easingOut: 'swing',
								centerOnScroll: true,
								autoDimensions:false, 
								width: 420, 
								height: 650
							});
//				Cufon.refresh('.swap-cufon');
				}
			
		});

		return false;
	});
	
	if($("#userOptions").length > 0)
	{
		$("#userOptions a.user_action").unbind('click').click(function(){
			$.ajax({
				url: $(this).attr('href'),
				type: "GET",
				data: $("#userOptions form").serialize() + "&action=" + $(this).attr('rel'),
				success: function(html){
					$.fancybox(html, {scrolling: 'no'});
//					alert('create clip');
					Cufon.refresh('.swap-cufon');
					$("#createClip").unbind('submit').submit(function(){
						var clipform = $(this);
						$.ajax({
							url: $(clipform).attr('action'),
							type: "POST",
							data: $(clipform).serialize(),
							success: function(html){
								if(html.match(/clip_error/))
								{
									$.fancybox(html, {scrolling: 'no'});
									Cufon.refresh('.swap-cufon');
								}
								else
								{
									$.fancybox.close();
									location.href = $("#currentUserLink").attr('href') + "&filter=clips";
								}
							}
						});
						return false;
					});
				}
			});
			return false;
		});
		$("#userOptions input[name='progfav']").unbind('click').click(function(){
			var thischk = $(this);
			var chkdata = $("#userOptions form").serialize() + "&action=updateFavorite";
			if($(thischk).is(":checked"))
				chkdata += "&progfav";
			$(thischk).attr('disabled', 'disabled');
			$.ajax({
				url: $("#userOptions form").attr('action'),
				type: "POST",
				data: chkdata,
				success: function(html){
					$(thischk).removeAttr('disabled');
					$(thischk).parent().siblings(".user_timestamp").html(html);
				}
			});
			return true;
		});
	}
	
	if($("#userShare form .program_follow").length > 0)
	{
		$("#userShare form .program_follow").unbind("click").click(function(){
			if(!$(this).hasClass("disabled"))
			{
				var thisstar = $(this);
				$(thisstar).addClass("disabled");
				var chkdata = $("#userShare form").serialize() + "&action=updateFavorite";
				if(!$(thisstar).hasClass("program_follow_selected"))
				{
					$(thisstar).addClass("program_follow_selected");
					chkdata += "&progfav=true";
				}
				else
					$(thisstar).removeClass("program_follow_selected");
				$.ajax({
					url: $("#userShare form").attr('action'),
					type: "POST",
					data: chkdata,
					success: function(html){
						$(thisstar).removeClass('disabled');
						if($(thisstar).hasClass("program_follow_selected"))
							$(thisstar).attr('title', html);
						else
							$(thisstar).attr('title', 'Click to mark this as a favorite program');
					}
				});
			}
			return false;
		});
	}

});

$(document).ready(function() {
	var container = $("#flagVideo");	

	$.ajax({
		type: "GET",
		url: $(container).attr("rel"),
		success: function(html){
			$(container).html(html);

			$(container).fadeIn("slow");
		
			var val = $("#options div div ul li:first-child a").attr("rel");

			$("#options div .smallBack").val(val);

			$("#flagVideo #text .videoFlag").unbind("click").click(function() {
				
				if($(this).attr("href") == "Request")
				{
					$.ajax({
						type: "GET",
						url: $(container).attr("rel"),
						data: {flag:"Request"},
						success: function(html) {
							$(container).html(html);
							$(container).fadeIn("slow");					
						}

					});
					return false;
				}

				$(this).parent().hide();
				$(this).parent().parent().children("#options").show();
				return false;
			});

      			$("#options .select").unbind('click').click(function(){
                		$(this).children('div').slideToggle();
        		});

        		$("#flagVideo .select ul li a").unbind('click').click(function(){

              			var container = $( "#options .select span" );

                		$(container).text( $(this).text() );

                		$(this).parent().parent().parent().slideUp();

                		return false;
       			});

			$("#flagVideo input[type=submit]").unbind('click').click(function() {
				var option = $( "#options .select span" );

				if($( option ).text() == "Other" && $("#otherText").val() == "")
				{
					$("#options").hide();
					$("#explain").show();
					
					return false;
				}

			        $.ajax({
       				         type: "GET",
       				         url: $(container).attr("rel"),
					 data: {flag:$( option ).text(), comment:$("#otherText").val()},
        			         success: function(html){
			                        $(container).html(html);

                        			$(container).fadeIn("slow");
						return false;
					}
				});
			});
		}
	});		

	var relcontainer = $("#relatedBox");
	$.ajax({
		type: "GET",
		url: $(relcontainer).attr('rel'),
		success: function(html){
			$(relcontainer).html(html);
			
			$("#relatedBoxTop > div > ul").fadeIn("slow");
			
			$("#relatedBox .action-bar .pager a").unbind('click').click(function(){
				if($(this).hasClass('active'))
					return false;
				
				var url = $(this).attr("href");
				
				var relulcontainer = $("#relatedBoxTop > div > ul");
				
				$("#relatedBox .action-bar .pager .active").removeClass('active');
				$(this).addClass('active');
				
				$(relulcontainer).fadeOut("slow", function(){
					$.ajax({
						type: "GET",
						url: url,
						success: function(html){
							$(relulcontainer).html(html);
		
							$(relulcontainer).fadeIn("slow");
						}
					});		
				});		
				
				return false;
			});
		}
	});

});

$(document).ready(function() {
	$("#video-width").blur(function() {

		if($(this).attr("rel") != $(this).val())
			$(this).addClass("changed");

		if(!$("#video-height").hasClass("changed"))
		{
			if($("#video-info").attr("checked"))
				var scale = (500/410);
			else
				var scale = (375/410);

			$("#video-height").val(Math.round($(this).val()*scale));
			$("#video-height").attr("rel", $("#video-height").val());
			$("#video-height").blur();
		}

		updateTextCopy("width", $(this).val());
	});

	$("#video-height").blur(function() {

		if($(this).attr("rel") != $(this).val())
			$(this).addClass("changed");

		if(!$("#video-width").hasClass("changed"))
		{
			if($("#video-info").attr("checked"))
				var scale = (410/500);
			else
				var scale = (410/375);
			
			$("#video-width").val(Math.round($(this).val()*scale));
			$("#video-width").attr("rel", $("#video-width").val());
			$("#video-width").blur();
		}

		updateTextCopy("height", $(this).val());
	});

	$("#video-info").click(function () {
		var to = "";
		var from = "";

		if($(this).attr("checked"))
		{
			to = "full";
			from = "embedded";
		} else {
			to = "embedded";
			from = "full";
		}
		
		var text = $("#codeBox textarea");
		var str = $(text).text();

		var pattern = "style=" + from;
		
		var regex = new RegExp(pattern, "g");

		str = str.replace(regex, "style=" + to);

		text.text(str);

		if(to == "embedded")
		{
			$("#video-height").val(375);
			$("#video-height").attr("rel", 375);
			$("#video-height").blur();
			$("#video-width").val(410);
			$("#video-width").attr("rel", 410);
			$("#video-width").blur();
			$("#video-height").removeClass("changed");
			$("#video-width").removeClass("changed");
		} else {
			$("#video-height").val(500);
			$("#video-height").attr("rel", 500);
			$("#video-height").blur();
			$("#video-width").val(410);
			$("#video-width").attr("rel", 410);
			$("#video-width").blur();
			$("#video-height").removeClass("changed");
			$("#video-width").removeClass("changed");
		}
	});

	function updateTextCopy(wording, val)
	{
		var text = $("#codeBox textarea");
		var str = $(text).text();

		var pattern = wording + "='\\d+'";

		var regex = new RegExp(pattern, "g");

		str = str.replace(regex, wording + "='" + val +"'"); 

		text.text(str);
	}
});


$(function(){

	$("#who .grid-view").unbind("click").click(function(){
		$("#who .grid").show();
		$("#who .list").hide();
		
		return false;
	});

	$("#who .list-view").unbind("click").click(function(){
		$("#who .grid").hide();
		$("#who .list").show();
		
		return false;
	});
	
	$("#relatedBox .action-bar .pager a").click(function(){
		if($(this).hasClass('active'))
			return false;
		
		var url = $(this).attr("href");
		
		var container = $("#relatedBoxTop > div > ul");
		
		$("#relatedBox .action-bar .pager .active").removeClass('active');
		$(this).addClass('active');
		
		$(container).fadeOut("slow", function(){
			$.ajax({
				type: "GET",
				url: url,
				success: function(html){
					$(container).html(html);

					$(container).fadeIn("slow");
				}
			});		
		});		
		
		return false;
	});
	
	$("#featuredVideo .video-content #dispFullAbstract").click(function(){
		$("#featuredVideo .video-content .shortAbstract").hide();
		$("#featuredVideo .video-content .fullAbstract").show();
		
		return false;
	});
	
	$("#timeline tr").click(function(){
		playerSeek(parseInt($(this).attr('id').substr(4), 10));
		
		return false;
	});
	
	$("#timeline").hover(function(){
		$(this).addClass('timeline-over');
	}, function(){
		$(this).removeClass('timeline-over');
	});

	$("#tabBox").tabs();
	
	$("#shareBox input[type=text]").hover(
		function() {
			$(this).css("background-color", "#CCCCCC");
		}, function() {
			if($(this).attr("rel") != "in")
				$(this).css("background-color", "#DDDDDD");
		}
	);

	$("#shareBox input[type=text]").focus(function(){

		$(this).css("background-color", "#CCCCCC");
		$(this).attr("rel", "in");

		if($(this).attr("title") == $(this).val())
			$(this).val("");
	}); 

	$("#shareBox input[type=text]").blur(function(){

		$(this).css("background-color", "#DDDDDD");
		$(this).attr("rel", "");

		if($(this).val() == "")
			$(this).val($(this).attr("title"));
	});

	$("#shareBox .send-video").click(function(){
		if($("#shareBox .share-pop:visible").length > 0)
			$("#shareBox .share-pop").slideUp({ direction: 'down'});
		else if($("#shareBox .share-confirm:visible").length > 0)
			$("#shareBox .share-confirm").slideUp({ direction: 'down'});
		else
			$("#shareBox .share-pop").slideDown({ direction: 'down'});
		
		return false;
	});
	
	$("#close-send").click(function(){
		$("#shareBox .share-pop").slideUp({ direction: 'down'});
		
		return false;
	});
	
	$("#close-confirm").click(function(){
		$("#shareBox .share-confirm").slideUp({ direction: 'down'});
		
		return false;
	});
	
	$("#shareEmail").submit(function(){
		
		$.post("/videoLibrary/ajax/ajax-share-email.php", {
			sender: $("#send-fromname").val(),
			recipient: $("#send-toname").val(),
			email: $("#send-email").val(),
			progid: $("#send-progid").val()
		},
		function(data){
			$("#shareBox .share-confirm .top").html(data);
			$("#shareBox .share-confirm").show();
			$("#shareBox .share-pop").hide();
		});
		
		return false;
	});
	
	if($("#timeline .transcript").length > 0)
		initTranscript();
});

function initTranscript()
{
	var url = $("#timeline .ajaxurl").attr('href');
	
	var container = $("#timeline .transcript");
	
	$.ajax({
		type: "GET",
		url: url,
		success: function(html){
			$(container).html(html);
			
			Cufon.replace("#timeline .transcript .swap-cufon");
			
			$("#transcriptSearch").unbind('submit').submit(function(){
				$(".transselect > div:visible").slideUp();
				$("#transcriptSearch button").attr('disabled', 'disabled').addClass('disabled');
				searchTranscript();
				return false;
			});
			
			$("#transcriptSearch input[type=text]").unbind('focus').focus(function(){
				$(this).addClass('focus');
			});
			
			$("#transcriptSearch input[type=text]").unbind('blur').blur(function(){
				$(this).removeClass('focus');
			});
			
			$(".transselect span").unbind('click').click(function(){
				if($(this).siblings('div:visible').length > 0)
					$(this).siblings('div:visible').slideUp();
				else
				{
					$(".select > div:visible").css('z-index', 11).slideUp();
					$(this).siblings('div').css('z-index', 12).slideDown();
				}
			});
			
			$(".transselect ul li").unbind('click').click(function(e){
				if(e.shiftKey && $(".transselect li.psn-last").length > 0)
				{
					$(".transselect li.selected").removeClass('selected');
					var psnlast = $(".transselect li.psn-last").get(0);
					var psnthis = $(this).get(0);
					var indexlast = $(".transselect li").index(psnlast);
					var indexthis = $(".transselect li").index(psnthis);
					if(indexlast == -1 || indexlast == indexthis)
						$(this).toggleClass('selected');
					else if (indexlast > indexthis)
					{
						for(var i = indexthis; i <= indexlast; i++)
							$(".transselect li").eq(i).addClass('selected');
					}
					else //if (indexlast < indexthis)
					{
						for(var i = indexlast; i <= indexthis; i++)
							$(".transselect li").eq(i).addClass('selected');
					}
				}
				else if(e.ctrlKey || e.metaKey)
				{
					$(".transselect li.psn-last").removeClass('psn-last');
					$(this).addClass('psn-last');
					$(this).toggleClass('selected');
				}
				else if($(this).hasClass('selected') && $(".transselect li.selected").length == 1)
				{
					$(".transselect li.psn-last").removeClass('psn-last');
					$(this).removeClass('selected');
				}
				else
				{
					$(".transselect li.psn-last").removeClass('psn-last');
					$(".transselect li.selected").removeClass('selected');
					$(this).addClass('selected').addClass('psn-last');
				}
				
				var psnCnt = $(".transselect li.selected").length;
				if(psnCnt == 1)
				{
					$(this).parents('.transselect').children('span').text($(".transselect li.selected").text());
					$("#trans-person").val($(".transselect li.selected a").attr('rel'));
				}
				else if(psnCnt == 0 || psnCnt == $(".transselect li").length)
				{
					$(this).parents('.transselect').children('span').text("All Speakers");
					$("#trans-person").val('0');
				}
				else
				{
					var psnSearch = '';
					$(".transselect li.selected a").each(function(){
						psnSearch += ':' + $(this).attr('rel'); 
					});
					$(this).parents('.transselect').children('span').text(psnCnt.toString() + " Speakers");
					$("#trans-person").val(psnSearch.substr(1));
				}
				
				return false;
			});
			
			$("#trans-nonids").unbind('click').click(function(){
				if($("#trans-nonids").attr('checked'))
					$(".transselect li.psn-nonid").show();
				else
					$(".transselect li.psn-nonid").hide();
			});
			
			$("#timeline tr").unbind('click').click(function(){
				playerSeek(parseInt($(this).attr('id').substr(4), 10));
//				if($("#timeline #transcript-results").is(":visible"))
//					$(window).scrollTo($("#featuredVideo"), 200);
				
				return false;
			});
		}
	});
}

function searchTranscript()
{
	var containerFull = $("#transcript-full");
	var containerResults = $("#transcript-results");
	$("#searchinfo").html("Searching transcript...").slideDown("fast");
	
	$("#trans-query").val($("#trans-search").val());
	
	var url = $("#timeline .ajaxurl").attr('href') + "&query=" + $("#trans-query").val() + "&personid=" + $("#trans-person").val();
	if($("#trans-nonids").length && !$("#trans-nonids").attr('checked'))
		url += "&nonids=true";
	var urlfull = url + "&full=true";
	
	$(containerFull).fadeOut("fast", function(){
		$.ajax({
			type: "GET",
			url: urlfull,
			success: function(html){
				$(containerFull).html(html);
				
				$("#transcript-full tr").unbind('click').click(function(){
					playerSeek(parseInt($(this).attr('id').substr(4), 10));
					
					return false;
				});
			}
		});
	});
	$(containerResults).fadeOut("fast", function(){
		$.ajax({
			type: "GET",
			url: url,
			success: function(html){
				$(containerResults).html(html);
				
				var numResults = $("#transcript-results tr").length;
				if(numResults > 0)
				{
					$("#searchinfo").html(numResults.toString() + " results found. <a href='#'>Close Search Results</a>");
					$(containerResults).fadeIn("fast");
					$("#searchinfo a").unbind('click').click(function(){
						$("#searchinfo").slideUp("fast");
						$(containerResults).fadeOut("fast", function(){
							$(containerFull).fadeIn("fast");
						});
						return false;
					});
				}
				else
				{
					if($("#trans-query").val() == '' && $("#trans-person").val() == '0')
					{
						$("#searchinfo").slideUp("fast");
						$(containerFull).fadeIn("fast");
					}
					else
					{
						$("#searchinfo").html("No results found for '" + $("#trans-query").val() + "'. <a href='#'>Show Full Transcript</a>");
						$("#searchinfo a").unbind('click').click(function(){
							$("#searchinfo").slideUp("fast");
							$(containerResults).fadeOut("fast", function(){
								$(containerFull).fadeIn("fast");
							});
							return false;
						});
					}
				}
				
				$("#transcript-results tr").unbind('click').click(function(){
					playerSeek(parseInt($(this).attr('id').substr(4), 10));
					$("#searchinfo").slideUp("fast");
					$(containerResults).fadeOut("fast", function(){
						$(containerFull).fadeIn("fast");
					});
					
					return false;
				});
				
				$("#transcriptSearch button").removeAttr('disabled').removeClass('disabled');
			}
		});
	});
}

function playerSeek(time)
{
	//the try block hides the errors created
	//the flashObject won't be available until the
	//the player fully loads
	try
	{
		var flashObject = document.getElementById('flashPlayer');

		if ( flashObject )
		{
			flashObject.seek(time);
		}
	}
	catch(err)
	{
	}
}

function updateTranscript()
{
	//the try block hides the errors created
	//the flashObject won't be available until the
	//the player fully loads
	try
	{
		var flashObject = document.getElementById('flashPlayer');
		var timeoffset = 0;

		if ( flashObject && $(".timeline-over").length == 0 && $("#timeline input.focus").length == 0 )
		{
			if($("#timeline .ccnotice").length > 0)
				timeoffset = Math.max(0, flashObject.getTime() - 15);
			else
				timeoffset = flashObject.getTime();
			if($("#time"+timeoffset.toString()).length)
			{
				var tr = $("#time"+timeoffset.toString());
				$(tr).parents(".table-wrapper-inner").scrollTo($(tr), 200);
			}
			else
			{
				for(var x = timeoffset; x >= 0; x--)
				{
					if($("#time"+x.toString()).length)
					{
						var tr = $("#time"+x.toString());
						$(tr).parents(".table-wrapper-inner").scrollTo($(tr), 200);
						break;
					}
				}
			}
//			alert ( "time = " + flashObject.getTime() );
		}
	}
	catch(err)
	{
	}
	
}

function flash_updateClipInfo( start, stop )
{
	start = Math.round( start );
	stop = Math.round( stop );

	if( stop == 0 )
		stop = $( "#own #purchase_config input[name=purchase_length]" ).val();

	$( "#own #purchase_config input[name=purchase_clip_start]" ).val( start );
	$( "#own #purchase_config input[name=purchase_clip_stop]" ).val( stop ); 
	
	if($("#userOptions").length > 0)
	{
		$("#userOptions .dl-button").show();
		$("#userOptions input[name='start']").val(start);
		$("#userOptions input[name='stop']").val(stop);
	}

	updateStats();
}

function updateStats()
{
	var len = parseInt( $( "#own table input[name=purchase_length]" ).val() );
	var clip_start = parseInt( $( "#own table input[name=purchase_clip_start]" ).val() );
	var clip_stop = parseInt( $( "#own table input[name=purchase_clip_stop]" ).val() );

	if( $( "#own #purchase_clip input[name=purchase_clip]" ).val() == "full" )
	{
		var vidlength = len;
	} else {
		var vidlength = clip_stop - clip_start;
	}	

	var length_text = "";
	if ( (days = Math.floor(vidlength / 86400)) >= 1 ) {
		length_text = days + " day";	
		if(days > 1)
			length_text += "s";
	}
	if ( (hours = Math.floor(vidlength / 3600) % 24) >= 1 ) {
		if(length_text != "")
			length_text += ", ";
		length_text += hours + " hour";
		if(hours > 1)
			length_text += "s";
	}
	if ( (minutes = Math.floor(vidlength / 60) % 60) >= 1 ) {
		if(length_text != "")
			length_text += ", ";
		length_text += minutes + " minute";
		if(minutes > 1)
			length_text += "s";
	}
	if (vidlength < 60) {
		length_text = vidlength + " second";
		if(vidlength > 1)
			length_text += "s";
	}

	$( "#own table span.purchase_length" ).html( length_text );

	var price = "";

	if( $( "#own #download_format input" ).val() == "dvd" )
	{
		price = $( "#own #download_format > span" ).attr( "rel" );

		$( "#own #purchase_config .price_samples" ).fadeOut( "fast" );
	} else {
		var type = $( "#own #download_format input.purchase_format" ).val().match( /^([A-Za-z0-9]+)\-(high|std|low)$/ );

		if(type[1] == 'mp3')
			price = 0.99;
		else
		{
			if( vidlength <= 1200 ) // 15 min + 5 min
			{	
				price = 2.99;
			} else if( vidlength <= 7500 ) { // 120 min + 5 min
				price = 4.99;
			} else if( vidlength <= 29100 ) { // 8 hr + 5 min
				price = 6.99;
			} else {
				price = 7.99;
			}
	
			if( type[2] == "low" )
				price = price - 1;
			else if(type[2] == 'high')
				price = 150.0;
			
			if(type[1] == 'avi' || type[1] == 'mov')
				price *= 100;
		}

		$( "#own #purchase_config .price_samples" ).fadeIn( "fast" );
	}

	price = Math.round( price * 100 ) / 100;

	$( "#own .purchase_price" ).text( "$" + price.toFixed( 2 ) );

	var text = $( "#own #purchase_config #purchase_clip > span" ).text();
	var clip = $( "#own #purchase_config input[name=purchase_clip]" ).val();	

	if ( parseInt( vidlength ) != parseInt( len )  && clip == "clip" )
	{
		text = "Partial Program";
	} else {
		text = "Complete Program";
	}

	$( "#own #purchase_config #purchase_clip > span" ).text( text );
	
}

function updateClipTranscript()
{
	//the try block hides the errors created
	//the flashObject won't be available until the
	//the player fully loads
	try
	{
		var flashObject = document.getElementById('flashPlayer');
		var timeoffset = 0;
//		alert ( "time = " + flashObject.getTime() );

		if ( flashObject && !$("#Closed_Captioning").hasClass("ui-tabs-hide") && $(".timeline-over").length == 0 && $("#timeline input.focus").length == 0 )
		{
			timeoffset = Math.max(0, flashObject.getTime() - 15);
			if($("#time"+timeoffset.toString()).length)
			{
				var tr = $("#time"+timeoffset.toString());
				$(tr).parents(".table-wrapper-inner").scrollTo($(tr), 200);
			}
			else
			{
				for(var x = timeoffset; x >= 0; x--)
				{
					if($("#time"+x.toString()).length)
					{
						var tr = $("#time"+x.toString());
						$(tr).parents(".table-wrapper-inner").scrollTo($(tr), 200);
						break;
					}
				}
			}
		}
	}
	catch(err)
	{
	}
}

function downloads_show_tos(orderfunc)
{
	// If Download TOS has been agreed to already, a cookie is set. Skip showing the TOS if this cookie is set.
	if(document.cookie)
	{
		var cookie_arr = document.cookie.split(';');
		for(var i = 0; i < cookie_arr.length; i++)
		{
			if(cookie_arr[i].indexOf("cspanvl_dltos=") != -1)
			{
				orderfunc();
				return;
			}
		}
	}
	
	//Ugly, but unsure how else to fix issue with fancybox over flash player on Mac OS X w/ Safari
	var agent = navigator.userAgent.toLowerCase();
	var macsafari_check = false;
	if(agent.indexOf('mac os x') != -1 && agent.indexOf('safari') != -1)
		macsafari_check = true;
	
	$.ajax( {
		url: "/videoLibrary/tos.php?download_tos",
		type: "GET",
		cache: false,
		success: function( data ) {
			var tos = $("<div></div>");
			var tos_scroll = $( "<div id='tos_popup_text'><h3 style='font-size: 14px;'>Before you continue, please read and agree to the Terms of Service below</h3></div>" );

			$( tos_scroll ).append( "<br />" );
			
			$( tos_scroll ).append( $( data ).find( ".tos" ) );
			
			$(tos).append($(tos_scroll))
			$( tos ).append( "<div id='tos_popup_links'>" +
								"<div class='dl-button' style='float:left; margin-right:10px;'>" +
								"<div class='left'></div>" +
								"<div class='fill'><a href='#' class='swap-cufon dl-action tos_agree'>Agree</a></div>" +
								"<div class='right'></div>" +
								"</div>" +
								"<div class='dl-button' style='float:left;'>" +
								"<div class='left'></div>" +
								"<div class='fill'><a href='#' class='swap-cufon tos_disagree'>Refuse</a></div>" +
								"<div class='right'></div>" +
								"</div>" +
								"</div>");

			$.fancybox( $( tos ).html() , {modal: true, scrolling: 'no', onComplete: function(){
				$("#tos_popup_text").css("height", ($("#fancybox-inner").height() - 38).toString() + 'px');
				if(macsafari_check)
					$("#flashPlayer").hide();
				Cufon.refresh('.swap-cufon');
			}} );
			Cufon.refresh('.swap-cufon');

			$( ".tos_agree" ).click( function() {
				if(macsafari_check)
					$("#flashPlayer").show();
				orderfunc();
				var expireDate = new Date();
				expireDate.setTime(expireDate.getTime()+(10*365*24*60*60*1000));
				document.cookie = 'cspanvl_dltos=true; expires='+expireDate.toGMTString()+'; path=/';
				return false;
			});
			
			$( ".tos_disagree" ).click( function() {
				if(macsafari_check)
					$("#flashPlayer").show();
				$.fancybox("<h1 class='swap-cufon'>Order rejected</h1><p>Sorry, you must agree to the terms of service before your download can be processed.</p>", {scrolling:'no', autoDimensions:false, width: 450, height: 50});
				Cufon.refresh('.swap-cufon');
				return false;
			});
		}	
	});
}

