// Defaults...
var isFlashAvailable	= false,
	isPageInitialised	= false,
	embedSwfAfterLoad	= false;
	isFlashAvailable = window.deconcept && deconcept.SWFObjectUtil && deconcept.SWFObjectUtil.getPlayerVersion && deconcept.SWFObjectUtil.getPlayerVersion().major;

var iPlayerPlaylistURL = null,
	iPlayerDomId = null;

// Before this script there must be a reference to:
//	http://www.bbc.co.uk/doctorwho/s4/javascript/jquery/jquery-1-2-3/jquery-1.2.3.pack.js
//	http://www.bbc.co.uk/emp/swfobject.js
//	http://www.bbc.co.uk/emp/embed.js

if(window.jQuery){ (function($){ $(function(){

	
	//show ie 6 #columns, they get hidden using inline js to prevent fouc
	if($.browser.msie) $('#columns').css('visibility','visible');
	
	// Replace page H2 and H3 text with pretty swf object:
	var deviantStrainSWF='/doctorwho/s4/includes/swf/headings/deviant_strain.swf?v=200809';


	// Activate custom styles for js-enabled browsers: (Script next to the <body> tag should have done this already, so this is just a belt and braces measure)
	$("BODY").addClass("js");

	if(useBlackBG){
		$('#blq-container').css({ backgroundImage:'none', backgroundColor:'#000' });
		$('body').css({ backgroundColor:'#000' });
	}
	
	if(isCFClient){
		$('#cf-copy-nav .prompt').click(function(){
			$("DL.accordian_nav").accordion("destroy");
			var h=$('#rhn').html();
			$.copy(h);
			$('#cf-copy-nav .feedback').html("COPIED TO CLIPBOARD");
		});
		$('#cf-copy-nav .close').click(function(){
			$('#cf-copy-nav').hide();
		});
	}

	//32 bit PNGs have a negative CSS background position
	//this prevents the white solid background appearing before the HTC fix is applied in IE6
	//the fix resets the background position: it must be reset manually for non IE6 browsers
	//$.ifixpng('/doctorwho/s4/images/pixel.gif');
	//$("DIV.png32, H2.png32").ifixpng().css({ backgroundPosition:"0px 0px" });
	
	
	var $accordions;

	$('.latest_news_plate>h3 , .most_viewed_plate>h3 , #heading_plate>h2 , #heading_plate>h3 , #related-stuff .head span , .promo_set_327_plate>h3, .promo_set_280_plate>h3').css('visibility','hidden');
			
	setTimeout(function(){doAccordianInit(); }, 300);
	setTimeout(function(){doDeepLinking(); }, 400);
	setTimeout(function(){doDeepLinkingGames(); }, 1400);
	setTimeout(function(){$("BODY").removeClass("nojs"); }, 500);
	
	if(doAccordianJS){
		setTimeout(function(){doAccordianLHN(); }, 600);
		setTimeout(function(){prepareRHN(); }, 700);
	}
	
	setTimeout(function(){doBlockUI(); }, 750);
	
	setTimeout(function(){doHijax(); }, 800);
	
	setTimeout(function(){doJScrollPane(); }, 900);
	
	
	if(doTrailerMakerJS){
		setTimeout(function(){writeTrailerMaker('TrailerMakerContainer'); }, 1000);
	}

	setTimeout(function(){doRelatedStuff(); }, 1100);
	if($.browser.safari){
		setTimeout(function(){doSWFReplacement(); }, 350);
		setTimeout(function(){doSWFReplacement2(); }, 450);
	}else{
		setTimeout(function(){doSWFReplacement(); }, 250);
		setTimeout(function(){doSWFReplacement2(); }, 450);
	}
	
	try{
		if(inlineEmpPlaylist){	
			setTimeout(function(){embedInlineEMP(); }, 1500);
		}
	}catch(err){

	}
	try{		
		if(requireMiscJS!=undefined && requireMiscJS){	
			setTimeout(function(){processMiscJS(); }, 1500);
		}
	}catch(err){

	}	
	
		

	// Remove interim style now that accordians are ready to activate: (By using both js and nojs classes we can apply an interim style while long accordian content loads!)
	$("BODY").removeClass("nojs");




	
	isPageInitialised = true;
	

		
	//embed iPlayer EMP if required		
	if(iPlayerPlaylistURL && iPlayerDomId){
		embedIPlayerEMP(iPlayerDomId,iPlayerPlaylistURL);
	}
	

	function embedIPlayerEMP(domId,playlist){
		var emp = new bbc.Emp();
		emp.setWidth("512");
		emp.setHeight("323");
		emp.setDomId(domId);
		emp.set("config_settings_skin","black");		
		emp.setPlaylist(playlist);		
		//emp.setConfig("http://www.bbc.co.uk/emp/iplayer/config.xml");		
		emp.write();	
	};

	function embedInlineEMP(){
		var w = inlineEmpPlaylistWidth == undefined ? 512 : inlineEmpPlaylistWidth;
		var h = inlineEmpPlaylistHeight == undefined ? 323 : inlineEmpPlaylistHeight;
		var emp = new bbc.Emp();
		emp.setDomId("inline-emp");
		emp.setWidth(w);
		emp.setHeight(h);
		emp.set("config_settings_skin", "black");  
		emp.setPlaylist(inlineEmpPlaylist);
		emp.write();
	};


	function doSWFReplacement(){
		
		if(doHomeJS){
			if(isFlashAvailable)
			{
				if($('#main-promo').length && home_main_swf!=''){
					writeSWFPromo(home_main_swf,946,327,'main-promo','promo',home_main_swf_params);

				}else{
					$('body.js .promo974 img').css('display','block');
				}
				
				if($('#left-promo').length && doSplitPromo && left_main_swf.length){
					writeSWFPromo(left_main_swf,627,327,'left-promo','promo-left',left_main_swf_params);				
				}else{
					$('#left-promo img').css('display','block');
				}
				
				if($('#right-promo').length && doSplitPromo && right_main_swf.length){
					writeSWFPromo(right_main_swf,305,327,'right-promo','promo-right',right_main_swf_params);				
				}else{
					$('#right-promo img').css('display','block');
				}				
				
				if($('#center-promo').length && home_center_swf!=''){
					writeSWFPromo(home_center_swf,318,410,'center-promo','center-promo',home_center_swf_params);
				}

				if(jQuery.browser.opera){
					$('.promo_328 LI , .promo_328_foot').css('background-image','none');			
				}
			}else{
				$('body.js .promo974 img').css('display','block');
				$('#left-promo img').css('display','block');
				$('#right-promo img').css('display','block');
			}
		}


		if(doHomeJS){
			if( $('#blq-content.home  .latest_news_plate>h3').length ){ writeSWFHeading($('#blq-content.home .latest_news_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/latest_news_h3.jpg',32,2,false); }
			if( $('#blq-content.home .most_viewed_plate>h3').length ){ writeSWFHeading($('#blq-content.home .most_viewed_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/most_viewed_h3.jpg',32,2,false); }
		}
		if(doNewsJS){
			if( $('#blq-content.news #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.news #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/news_h2.jpg',32,1.5,true, "News"); }
			if( $('#blq-content.news .promo_set_327_plate>h3').length ){ writeSWFHeading($('#blq-content.news .promo_set_327_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/promo_set_327_h3.jpg',22,2,false); }
		}
		if(doGamesJS){
			if( $('#blq-content.games #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.games #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/games_h2.jpg',32,1.5,true); }
			if( $('#blq-content.games .promo_set_327_plate>h3').length ){ writeSWFHeading($('#blq-content.games .promo_set_327_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/promo_set_327_h3.jpg',22,2,false); }
		}
		if(doEpisodesJS){

			if( $('#blq-content.episodes  #heading_plate>h2').length ){ 
				//$('#blq-content.episodes #heading_plate>h2').html($('#blq-content.episodes h1').html());
				writeSWFHeading($('#blq-content.episodes #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/episodes_h2.jpg',32,2,false); 
			
			}
		}
		if(doCharactersJS){
			if( $('#blq-content.characters #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.characters #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/characters_h2.jpg',18,1,true); }
			if( $('#blq-content.characters #heading_plate>h3').length ){ writeSWFHeading($('#blq-content.characters #heading_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/characters_h3.jpg',32,2,false); }
		}
		if(doVideosJS){
			if( $('#blq-content.videos #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.videos #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h2.jpg',32,1.5,true); }
			if( $('#blq-content.videos #heading_plate>h3').length ){ writeSWFHeading($('#blq-content.videos #heading_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h3.jpg',32,2,false); }
		}
		
		if(doFaqJS){
			if( $('#blq-content.faq #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.faq #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h2.jpg',32,1.5,true); }
			if( $('#blq-content.faq #heading_plate>h3').length ){ writeSWFHeading($('#blq-content.faq #heading_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h3.jpg',32,2,false); }
			if( $('#blq-content.faq .promo_set_327_plate>h3').length ){ writeSWFHeading($('#blq-content.faq .promo_set_327_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/promo_set_327_h3.jpg',22,2,false); }
		}

		

		if(doFeaturesJS){
			if( $('#blq-content.features #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.features #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/features_h2.jpg',32,1.5,true); }
			
			if( $('#blq-content.features #heading_plate>h3').length ){ writeSWFHeading($('#blq-content.features #heading_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/features_h3.jpg',32,2,false); }
			

			if( $('#blq-content.features #mainpromo .mainpromo_summary>h3').length ){ 

writeSWFHeading(
	$(
		'#blq-content.features #mainpromo .mainpromo_summary>h3'),
		deviantStrainSWF, 
		'/doctorwho/s4/img/headings/flash_bgs/features_home_h3.jpg',
		32,
		1.5,
		false,
		false,
		"0xFFFF00"
		);

			}

			if( $('#blq-content.features #head_bar>h3,#episode-features-block #head_bar>h3').length ){ writeSWFHeading($('#blq-content.features #head_bar>h3,#episode-features-block #head_bar>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/features_home_h3_bottom.jpg',22,2,true); }

			if( $('#blq-content.features .promo_set_280_plate>h3').length ){ writeSWFHeading($('#blq-content.features .promo_set_280_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/promo_set_280_h3.jpg',20,2,true); }

			//if( $('#blq-content.features #SeeAlso .relatedlinks_header>h3').length ){ writeSWFHeading($('#blq-content.features #SeeAlso .relatedlinks_header>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/promo_set_280_h3.jpg',20,2,true); }	
			if( $('#blq-content.features .SeeAlso .relatedlinks_header>h3').length ){ 
				$('#blq-content.features .SeeAlso .relatedlinks_header>h3').each(function(){
					writeSWFHeading($(this),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/promo_set_280_h3.jpg',20,2,true); 
				});
			}	

		}

			

		if(doFaqJS){
			if( $('#blq-content.faq #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.faq #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h2.jpg',32,1.5,true); }
			if( $('#blq-content.faq #heading_plate>h3').length ){ writeSWFHeading($('#blq-content.faq #heading_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h3.jpg',32,2,false); }
			if( $('#blq-content.faq .promo_set_327_plate>h3').length ){ writeSWFHeading($('#blq-content.faq .promo_set_327_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/promo_set_327_h3.jpg',22,2,false); }
		}


		if(doImagesJS){
			if( $('#blq-content.images #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.images #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h2.jpg',32,1.5,true); }
			if( $('#blq-content.images #heading_plate>h3').length ){ writeSWFHeading($('#blq-content.images #heading_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h3.jpg',32,2,false); }
		}
		if(doAudioJS){
			if( $('#blq-content.audio #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.audio #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h2.jpg',32,1.5,true); }
			if( $('#blq-content.audio #heading_plate>h3').length ){ writeSWFHeading($('#blq-content.audio #heading_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/videos_h3.jpg',32,2,false); }
		}
		if(doConfidentialJS){
			if( $('#heading_plate .confidential>h2').length ){ writeSWFHeading($('#heading_plate .confidential>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/confidential_h2.jpg',32,2,false); }
		}
		if(doCreateJS){

			if( $('#blq-content.create #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.create #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/games_h2.jpg',32,1.5,true); }
		}
		if(doMiscJS){
			if( $('#blq-content.misc #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.misc #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/misc_h2.jpg',32,1.5,true); }
			if( $('#blq-content.misc .promo_set_327_plate>h3').length ){ writeSWFHeading($('#blq-content.misc .promo_set_327_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/promo_set_327_h3.jpg',22,2,false); }
		}	
		
	}

	function doSWFReplacement2(){
	
		if( $('#related-stuff .head span').length ){ writeSWFHeading($('#related-stuff .head span'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/related_content.jpg',20,2,false); }
		if( $('#elsewhere-in-bbc .head span').length ){ writeSWFHeading($('#elsewhere-in-bbc .head span'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/related_content.jpg',20,2,false); }
		
		if( $('#heading_plate .features>h2').length ){ writeSWFHeading($('#heading_plate .features>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/features_main_h2.jpg',32,1.5,false); }
		
		if( $('#heading_plate .features_article>h2').length ){ writeSWFHeading($('#heading_plate .features_article>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/confidential_h2.jpg',32,1.5,false); }
		
		if( $('#blq-content.misc #heading_plate>h2').length ){ writeSWFHeading($('#blq-content.misc #heading_plate>h2'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/misc_h2.jpg',32,1.5,true); }
		if( $('#blq-content.misc .promo_set_327_plate>h3').length ){ writeSWFHeading($('#blq-content.misc .promo_set_327_plate>h3'),deviantStrainSWF,'/doctorwho/s4/img/headings/flash_bgs/promo_set_327_h3.jpg',22,2,false); }
		
		
		
		
		


		if(!isFlashAvailable){
			$('#heading_plate H2, #heading_plate H3, .related-stuff SPAN').css('text-indent','0px').css('padding-top','5px');
			$('DIV.promo974 IMG').css('display','block');
		}else{
			$('#flash_required').css('display','none');
			if(embedSwfAfterLoad){
				writeSWFPromo(embed_swf_path,embed_swf_width,embed_swf_height,embed_swf_target_id,embed_swf_id,null);
			}
		}
	
	}




	function doJScrollPane(){
		
		if( doScrollPaneJS && !isCFAjax ){
			//Add scrollbars to jscrollpane elements
			if( $.jScrollPane ){

				$('DIV.scroll-pane').jScrollPane({ scrollbarWidth:16, scrollbarMargin:0 });
			}
		}
	}
	function doBlockUI(){
		// Initialise lightbox: (For games and some image previews)
		if($.blockUI){
			$.extend($.blockUI.defaults.overlayCSS, { backgroundColor:'#000', opacity:'0.8', cursor:"default" });
			$.extend($.blockUI.defaults.pageMessageCSS, { color:"#fff", backgroundColor:"#000", top:100, width:800, margin:0, marginLeft:-250, border:"solid 5px #000", cursor:"default" });
			$.blockUI.defaults.pageMessage = '<div id="lightbox"><div id="lightbox-header"><a href="#" class="close" title="Close">Close</a><h2>Game</h2></div><div id="lightbox-content"></div></div>';
		}
	}
	
	function doHijax(){
		// HIJAX LINKS to images, videos and games etc:
		$("#bg").click(function(e,test){

			var $link = $(test || e.target);
			
			
			if( $link.is("A") && $link.attr("rel")=="external"){
				window.open( $link.attr('href') );
				return false;
			}else if( $link.is("A") || ( $link=$link.filter("IMG").parent("A") ).is("A") ){	// Note: The extra ||condition allows for target returned as the <img> within the link in some browsers.
				return handleLinkClick($link);
			}

		});

	}

	
	function doAccordianInit(){

		$accordions	= $("DL.accordian_nav");
			
		// Modify wallpaper title text for users with javascript:
		$accordions.filter('.nav_280').find("A[title^='Open image in new window:']").each(function(){ $(this).attr({ title: $(this).attr("title").replace('Open image in new window:','Image:') }); });


	}

	function doDeepLinking(){
		
		url			= getHashOfQueryParams(window.location.href);

		// DEEP LINK: Automatically play Audio/Video specified in incoming link url:
		if( (url.playlist && url.playlist.split(".").pop() == "xml") ){

			// Look for links (on this page's rhn) to this same playlist so we can use its title text etc:
			var $matchingLinkOnPage	= $("#rhn A[href*='playlist=']")
				.filter("[href*='video=1'],[href*='audio=1']")
				.filter(function(){
					var lnk = getHashOfQueryParams( $(this).attr("href") );
					return (!lnk.pid && lnk.playlist && lnk.playlist == url.playlist) || (url.pid && url.pid == lnk.pid);
				}).eq(0);

			if( !$matchingLinkOnPage.length ){	// We can't be clever and display title etc from an existing link so make up a generic one:
				url.title = url.title || ( url.video ? "Video" : url.audio ? "Audio" : "Play-clip");	// Derive title param.
				if( !url.video && !url.audio ){ url[url.pagename == "audio" ? "audio" : "video"] = 1 };	// Derive audio/video param.
				$matchingLinkOnPage = $('<a></a>').attr({ href:$.param(url) });
			}
			
			handleLinkClick( $matchingLinkOnPage );

		// Otherwise default to show/play FIRST media-item on the images/videos/audio/confidential pages:
		}else if( /images|video|audio|features/.test(url.pagename) ){

			// Try to find a link containing a "default" url param:
			var $link = $("A[href *= 'action='][href *= '&default']");

			// Otherwise look for links in the RHS nav panel:
			if( $link.length == 0 )
				$link = $accordions.filter("DL.nav_280:not(.series)").children("DD:first").find("LI:not(.series) A:not([@href*='/radio/podcasts']):first");

			handleLinkClick( $link );

		}else if( url.episode_id || url.character ){

		}
	
	}

	function doDeepLinkingGames(){
		
		url			= getHashOfQueryParams(window.location.href);
		
		if(url.gameid){			
			var matchingLinkOnPage	= $("A[href*='" +url.gameid +"']");			
			var link=$(matchingLinkOnPage)[0];
			
			//var l=$($matchingLinkOnPage[0]);
			//alert($(link).attr('href'));
			handleLinkClick($(link));
		}
	
	}	
	
	
	function doRelatedStuff(){
		// Activate related-stuff panel:
		$("DIV.related-stuff").each(function(){

			// Closures to improve responsiveness:
			var $links	= $(this).find(">.related-links>UL"),
				$images	= $(this).find(">.link-preview >UL"),
				cycleID = null;

			// Handler to animate images and links-selector as mouse moves over links:
			$links
				.css({ backgroundPosition: "0px -132px" })	// Set style explicitly to workaround a bug in Mozilla.
				.children("LI")
					.eq(0).addClass("selected").end()
					.mouseover(function(){

						var listLen	= $(this).siblings().length,
							selIndex= $(this).prevAll().length,
							offset	= -5 + (listLen - selIndex) * -42;

						$links.stop()
							.children().removeClass("selected").eq(selIndex).addClass("selected").end().end()
							.animate({ backgroundPosition: "(0px " + offset + "px)" }, 300);
						$images.stop()
							.animate({ marginTop: selIndex * -172 }, 1000);//, "easeInOutBack");

						//window.setTimeout( function(){ $images.stop().animate({ marginTop: selIndex * -172 }, 1000, "swing"); },200)
						//$images.stop().animate({ marginTop: "-=20" }, 200, "swing", function(){ $images.animate({ marginTop: selIndex * -172 }, 1000, "swing"); });
						//window.setTimeout( function(){ $images.stop().animate({ marginTop: selIndex * -172 }, 1000, "swing"); }, 200)
						//$images.stop().animate({ marginTop: selIndex * -172 }, 1500, "easeInOutBack");
					})
				.end()
			.end();

			// Auto-cycle the links after the mouse moves away:
			//$(this).hover(function(){ cycleLinks(false) }, cycleLinks);
			//cycleLinks();

			function cycleLinks(cancel){
				if(cycleID){ window.clearInterval(cycleID); };
				if(cancel!=false){ cycleID = window.setInterval(function(){ $links.find(">LI.selected+LI, >LI:first").eq(0).mouseover(); },5000); };
			};

		});
	}
	
	
	function doAccordianLHN(){

		// Activate accordion menus...
		if($.fn.accordion ){

			//determine if nav DT already has .selected
			var $preSelectedNavGroup = $('.nav_167 ').find("DT.selected");


			// Generate IDs for DT elements that don't already have an id: (Eg: "Ships & Gadgets" DT is set as "#shipsgadgets")
			$accordions.find(">DT").each(function(){
				this.id = this.id || $(this).text().toLowerCase().replace(/[^a-z0-9]*/g,"");
				$(this).children("SPAN").wrapInner('<a href="#' + this.id + '"></a>');
			});

			var $lhn = $accordions.filter('.nav_167'),
				
				//$games = $accordions.filter('.acc_647'),
				lhnNavGroupID = $lhn.find("LI." + (url.character || "doctor10")).parents("DD:first").prev("DT").attr("id");



			//if in video,images or audio then do not force to be alwaysOpen
			var alwaysOpen=$('#blq-content.episodes , #blq-content.confidential , #blq-content.videos , #blq-content.audio , #blq-content.images, #blq-content.characters, #blq-content.features').length>0 ? false : true;
			var active;
			if($preSelectedNavGroup.length) active=$preSelectedNavGroup.length ? 'dt.selected' : 'td:first';
			else active="";
			$lhn.accordion({		// LHN
				fillSpace: false,
				alwaysOpen:alwaysOpen,
				autoheight:false,
				clearStyle:true,
				navigation:true,
				header: "dt",
				active: active
			});
			//active: "DT:first"	//(url.character ? "#" + lhnNavGroupID : "DT:first" )
		
		}

		$accordions.children("DD")

			// Remove temporary style from default <dd> in each accordion. (Was only there to reduce FOUC during page load)
			.filter(".selected").removeClass("selected").end()

			// Add style to the last <li> in every accordian_nav:
			.find(">DIV>UL>LI:last-child, >UL>LI:last-child").addClass("last");
			
	}
	
	
	
	var accordionItemsToOpen=2;
	var accordionItemLIsToShow=2;

	
	function prepareRHN(){
		$rhn = $accordions.filter('.nav_280');
		
		var listHeaders=$rhn.find('DT');
		var lists=$rhn.find('DD');
		var lis,link;
		
		var pageType=$('div#blq-content.episodes , div#blq-content.characters');
		if(!pageType.length || listHeaders.length<2){
			doAccordianRHN();
			return;
		}
		

		//display first 2 items in first 2 right nav accordion sections
		for(i=0;i<accordionItemsToOpen;i++){
			var header=$(listHeaders[i]);
			var list=$(lists[i]);
			
			var id=header.attr('id');
			var label="item";			
			switch(id){
				case "videos":
					label="video";
					break;
				case "sounds":
					label="sound";
					break;	
		
							
			}
			
			lis=list.find("LI.video , LI.audio, LI.image");
			var hiddenItems=lis.length-accordionItemLIsToShow;
			if(hiddenItems>1) label+="s";
			$(header).addClass('selected');
			
			
			for(j=accordionItemLIsToShow;j<lis.length;j++){
				var li=$(lis[j]);
				li.hide();
			}		
			if(lis.length>accordionItemLIsToShow){			
				var showAll="<li class=\"show_all_items\"><p>Show " +(lis.length-accordionItemLIsToShow) +" other " +label +"</p></li>";
				li.after(showAll);			
				list.find('li.show_all_items').bind('click',function(){					
					$rhn.find('DT.selected').unbind('click',clickSelectedRHNDT);
					var dt=$(this).parents('dd').prev('dt');
					var id=dt.attr('id');
					revealHiddenRHNItems();
					doAccordianRHN($(dt).attr('id'));					
					$(dt).trigger('click');						
				});
			}			

		}
		//hide other RHN accordion sections
		for(i=accordionItemsToOpen;i<lists.length;i++){
			var list=$(lists[i]);
			list.css('display','none');
		}	
		
		listHeaders=$rhn.find('DT').not('.selected');
		listHeaders.bind('click',handleRHNDDClick);
		
		listHeaders=$rhn.find('DT.selected');
		listHeaders.bind('click',clickSelectedRHNDT);		
	}
	function clickSelectedRHNDT(){
		//close the following DD
		$(this).removeClass('selected').next('DD').css('display','none');
		//bind click to handleRHNDDClick
		$(this).unbind('click',clickSelectedRHNDT).bind('click',handleRHNDDClick);	
		
		$('dl.nav_280 li.show_all_items').remove();	
		$rhn.find('DD').find("LI.video , LI.audio , LI.image").show();
		
	}	
	function revealHiddenRHNItems(){
		$rhn.find('DT.selected').removeClass('selected');
		var lists=$rhn.find('DD');
		for(i=0;i<accordionItemsToOpen;i++){
			var list=$(lists[i]);
			var lis=list.find("LI");
			for(j=accordionItemLIsToShow;j<lis.length;j++){
				var li=$(lis[j]);
				li.show();
			}		
		}
		$('dl.nav_280 li.show_all_items').remove();	
		$rhn.find('DT').unbind('click',handleRHNDDClick);
	}
	
	function handleRHNDDClick(){	
		revealHiddenRHNItems();			
		
		//$('dl.nav_280').find('DD').css('display','block');					
		
		
		doAccordianRHN();//$(this).attr('id'));	
		
	}
	function doAccordianRHN(activeDTID){
	
		
		
		// Activate accordion menus...
		if($.fn.accordion ){
		
			$rhn = $accordions.filter('.nav_280');
			
			if($.browser.msie && $rhn.find('DT').length==1){
			
			}else{
				$rhn.accordion({		// RHN
					fillSpace: false,
					alwaysOpen:false,
					autoheight:false,
					clearStyle:true,
					navigation:true,
					header: "dt",
					active: (activeDTID ? "DT#" +activeDTID : url.bookmark ? "DT#" + url.bookmark : $rhn.children("DT").length < 3 ? "DT:first" : "")
				});
			}
			
		


			

		}

		$accordions.children("DD")

			// Remove temporary style from default <dd> in each accordion. (Was only there to reduce FOUC during page load)
			.filter(".selected").removeClass("selected").end()

			// Add style to the last <li> in every accordian_nav:
			.find(">DIV>UL>LI:last-child, >UL>LI:last-child").addClass("last");
	
	}

	function handleLinkClick($link){

		// Break down the href's query params (the "name=value" pairs) into a handy hash object: (We also give it a "pathname" property that is the url left of the "?")
		var lnk = getHashOfQueryParams( $link.attr("href") );
		
		

		lnk.title				= lnk.title   || $link.attr("title") || $link.attr("alt");
		lnk.summary				= unescape( lnk.summary || lnk.title );
		lnk.isInMainContent		= $link.parents().is("#maincontent");
		lnk.isInRelatedLinks	= $link.parents().is("#related-stuff");
		lnk.isInRhsNav			= $link.parents().is("DIV.right_280");

		if(lnk.isInRelatedLinks){ return true; }	// RelatedLinks must open in target page so don't hijax them.

		
		// Reset default html in maincontent:
		if(!lnk.pid && lnk.isInRhsNav && !lnk.gametype && !lnk.gameid){ $("#maincontent").html( $("#mainpromo_template").html() ) };

		// Handle click on IMAGE LINK:
		if( /((.jpg|.png|.gif)$)/.test(lnk.pathname) &&  $("#mediapanel").length ){


			// Any link not inside the maincontent panel:
			if( !lnk.isInMainContent ){
				

				$("<img/>").attr({ src:lnk.promo||lnk.href, alt:lnk.title, title:lnk.title }).appendTo("#mediapanel");	// Always use promo image if available!

				var links = "";
				var $links = $link.clone().text(lnk.size)						// Make a new copy of the thumbnail link.
					.add( $link.siblings("UL").find(">LI>A").clone() )			// Make one list of the thumbnail link and all the variations that follow it.
					.attr({ target:"download" })								// Set the target window.
					.filter(":contains(wide-screen)").text(" widescreen").end();	// Remove hyphen from the word "wide-screen"! Also prefix with space to FIX OVERLAPING EDGE OF BCX

				// Special treatment for non-art images, to group them by purpose:
				if( lnk.purpose && lnk.purpose.toLowerCase() != "art" ){

					var purposeGroups = {}; links = "View in new window: <br/>"; //+ ($links.outerHtml() || lnk.info);

					// Arrange links into groups according to purpose: (eg "Computer wallpaper" and "Mobile wallpaper")
					$links.each(function(){
						var purpose = getHashOfQueryParams( $(this).attr("href") ).purpose || "Image";
						purposeGroups[purpose] = ( purposeGroups[purpose] || $([]) ).add(this);
					});

					// Build html for each purpose-group, prefixed by its purpose name:
					$.each(purposeGroups, function(groupPurpose,$groupLinks){
						links += groupPurpose + "<br/>" + ($groupLinks.outerHtml() || lnk.info) + "<br/>";
					})

				// Add a lightbox-preview link if image url is different from promo image:
				}else if( lnk.promo && lnk.promo != lnk.pathname && $links.length == 1 && $.blockUI ){
					links = "View: " + '<a href="' + lnk.pathname + '?preview=1" title="' + lnk.title + '">Full size</a><br/>' + links;
				}

				// Only use summary if different from title:
				lnk.summary = ( lnk.title != lnk.summary ? lnk.summary || "&nbsp;" : "&nbsp;" );

				$("#th1").html(lnk.title);
				$("#th2").html("&nbsp;");
				$("#td1").html(lnk.summary);
				$("#td2").html(links);

				// Add an extra row for info if necessary:
				if(lnk.info){
					lnk.info=unescape(lnk.info);
					$("<tr></tr>").append( $('<td colspan="2"></td>').html(lnk.info) ).appendTo("#mediainfo TBODY");
				}

				if(isPageInitialised){ window.scrollTo(0,140) };
				return false;		// Stop the default link action.


			// PREVIEW the image in a lightbox:
			}else if( lnk.preview && $.blockUI ){

				
				
				$('#swfTitle0-container,#swfTitle1-container').hide();
				
				
				$.blockUI();
				$("#lightbox-header H2").text(lnk.title||"Preview");

				$("<img/>").attr({ src:lnk.pathname, alt:lnk.title, title:lnk.title }).bind("load",function(){

					// Customise lightbox for the image size:
					var $img = $(this).appendTo("#lightbox-content");
					$("#lightbox").parent().css({ width:$img.width(), height:$img.height()+30, marginLeft:-$img.width()/2 });
					$img.css({visibility:"visible"});

				}).css({visibility:"hidden"});

				// Handle Click or Escape to close lightbox:
				$("#lightbox A.close").click( function(){ removeBlockUI();} );
				$("#lightbox").parent().prev().click( function(){ removeBlockUI();}  ).css({ cursor:"pointer", title:"Click to close" });
				$(window).one("keydown",function(e){ if(e.keyCode==27){ removeBlockUI(); } });

				return false;		// Stop the default link action.
			}

		}


		// Handle click on iPlayer PID VIDEO LINK:
		else if(lnk.pid && lnk.action && lnk.action=="iplayer" && $("#mediapanel").length){

			// Do nothing. iPlayer EMP requires a page refresh.

			/*
			var url = "/doctorwho/s4/ajax/episodes.shtml" + lnk.querystring;

			if(!$.browser.msie){
				$("#mediapanel").load(url);
			}else{
				$.get(url, function(html){ $("#mediapanel")[0].innerHTML = html });
			}

			// Only use summary if different from title:
			lnk.summary = ( lnk.title == lnk.summary ? "&nbsp;" : lnk.summary || "&nbsp;" );

			$("#th1").html(lnk.title);
			$("#td1").html(lnk.summary);
			$("#th2").html("&nbsp;");
			$("#td2").html("&nbsp;");

			if(isPageInitialised){ window.scrollTo(0,140) };
			return false;		// Stop the default link action.
			*/
		}


		// Handle click on EMP VIDEO LINK:
		else if(lnk.video && lnk.playlist && $("#mediapanel").length){
			
			
			
			writeVideoEMP( lnk.playlist,null,null,'mediapanel' );

			
			//update features video info			
			if(lnk.title != "Video"){
				$("#maincontent .media_info h2").html(lnk.title || "Video");
				$("#maincontent .media_info .media_info_description").html(lnk.title == lnk.summary ? "&nbsp;" : lnk.summary || "&nbsp;" );
			}

			
			
			$("#mediainfo TABLE").each(function(){

				$("#th1",this).html(lnk.title || "Video");
				$("#td1",this).html(lnk.title == lnk.summary ? "&nbsp;" : lnk.summary || "&nbsp;" );

				$("#th2",this).html("(Only available in the UK)").attr({ title:"This video is only available in the UK" });
				$("#td2",this).html(lnk.info);

			});

			if(isPageInitialised){ window.scrollTo(0,140) };
			return false;		// Stop the default link action.
		}


		// Handle click on AUDIO LINK:
		else if(lnk.audio && lnk.playlist && $("#mediapanel").length){

			writeAudioEMP( lnk.playlist,null,null,'mediapanel' );
			if(lnk.promo){ $('<img/>').attr({ src:lnk.promo, alt:lnk.title, title:lnk.title }).prependTo("#mediapanel") };

			if(lnk.fileext == "mp3"){
				lnk.info += '<br/>Download: <a href="' + lnk.pathname + '" target="download">' + lnk.fileext + '</a>';
			}

			$("#mediainfo TABLE").each(function(){
				//$("#th1",this).html(lnk.title || "Audio");
				//$("#td1",this).html(lnk.title == lnk.summary ? "&nbsp;" : lnk.summary || "&nbsp;" );
				$("#th2",this).html("&nbsp;");
				$("#td2",this).html(lnk.info);
			});


			if(isPageInitialised){ window.scrollTo(0,140) };
			return false;		// Stop the default link action.
		}


		// Handle click on GAME LINK: (Show game in lightbox)
		else if(lnk.gameid){
		
			

			if(isFlashAvailable){
				
				

				with( lnk.gameid.split("/") ){ pop(); lnk.gamebase = join("/"); };
				lnk.w=parseInt(lnk.w)||750; lnk.h=parseInt(lnk.h)||450; lnk.v=parseInt(lnk.v)||7;	// Fix any missing params.
				var gameHost = lnk.gameid.indexOf('downloads.bbc.co.uk')>0 ? "http://downloads.bbc.co.uk/doctorwho/games/game.shtml" : lnk.gameid.indexOf('cf.bbc.co.uk')>0 ?  "http://www.cf.bbc.co.uk/doctorwho/s4/games/game.shtml" : "http://www.bbc.co.uk/doctorwho/s4/games/game.shtml";				
				lnk.gameViewerUrl = gameHost + '?w=' +lnk.w + '&h=' +lnk.h +'&gametype=' +lnk.gametype + '&episodeid=' +lnk.episodeid + '&gameswf=' +lnk.gameid + '&gamebase=' + lnk.gamebase + '" frameBorder=0 width="' +lnk.w + '" height="' + lnk.h;
				
				$('#swfTitle0-container,#swfTitle1-container').hide();
				
				if(lnk.h <= 550){

					$.blockUI.defaults.pageMessage = '<div id="lightbox"><div id="lightbox-header"><a href="#ignore" class="close" title="Close">Close</a><h2>Game</h2></div><div id="lightbox-content"><iframe scrolling="no" class="" src="' + lnk.gameViewerUrl + '"></iframe></div></div>';

					//var html="<div id=\"lightbox\">";
					//html+="<a class=\"close\" href=\"#\">close game</a>";
					//html+="<iframe scrolling=\"no\" class=\"\" src=\"/doctorwho/s4/games/game.shtml?w=" +lnk.w +"&h=" +lnk.h +"&gametype=" +lnk.gametype +"&episodeid=" +lnk.episodeid +"&gameswf=" +lnk.gameid +"&gamebase=" +lnk.gamebase +"\" frameBorder=0 width=\"" +lnk.w +"\" height=\"" +lnk.h +"\"></iframe>";
					//html+="</div>";
					$.extend( $.blockUI.defaults.pageMessageCSS, { width:lnk.w, height:lnk.h+30, marginLeft:-lnk.w/2, top:10 } );
					$.blockUI.defaults.fadeOut=0;
					$.blockUI.defaults.fadeOutTime=0;
					$.blockUI();

				}else{

					$.blockUI.defaults.pageMessage = '<div id="lightbox"><div id="lightbox-header"><a href="#close" class="close" title="Close">Close</a><h2>Game</h2></div><div id="lightbox-content"></div></div>';
					$.extend($.blockUI.defaults.pageMessageCSS, { width:400, marginLeft:-200 });
					$.blockUI();
					$("#lightbox-header H2").text(lnk.title||"Play game");
					$('<p id="lightbox_prompt_msg">This game requires more space that most, would you like to open it in a new window?</p>').appendTo("#lightbox-content");
					$('<a id="lightbox_response_yes" href="' + lnk.gameViewerUrl + '" target="game">Yes, open a new window</a>').appendTo("#lightbox-content");
					$('<a id="lightbox_response_no"  href="#close">No, take me back</a>').appendTo("#lightbox-content");

					$("#lightbox_response_yes").click(function(){
						// Open game in a new window:
						window.open(this.href,this.target,'status=no,scrollbars=no,resizable=no,width=770,height=630')
					});
				}
				//$.extend($.blockUI.defaults.pageMessageCSS, { width:lnk.w, marginLeft:-lnk.w/2 });
				//$.blockUI();
				//$("#lightbox-header H2").text(lnk.title||"Play game");
				//var swf = new SWFObject(lnk.gameid, "swf-game", lnk.w, lnk.h, lnk.v, "#000");
				//swf.addParam("loop", lnk.l||false);
				//swf.write("lightbox-content");

			}else{
				$("#lightbox-content").html( lnk.no || "You will need Flash " + lnk.v + " to play this game." );	// noPluginMsg
			}

			// Handle Close or Excape to close lightbox:
			$("#lightbox A").click( removeBlockUI );
			$(window).one("keydown",function(e){ if(e.keyCode==27){ removeBlockUI();  } });

			return false;		// Stop the default link action.
		}


		// Handle click on OTHER LINKS:
		else if(lnk.action && /iplayer|photostory|quiz|screensaver|factfile|fearfactor|credits|musiclist|profile/.test(lnk.action) && $("#mediapanel").length && (!lnk.iplayer || lnk.pid) ){

			//var url = "/doctorwho/s4/ajax/episodes.shtml" + lnk.querystring;
			var url = "/doctorwho/s4/ajax/" +lnk.action +"/";
			var container = "#" + ( lnk.container || "maincontent" );
			
			if(lnk.character) url+=lnk.character +"/";
			else{			
				if(lnk.episode) url+=lnk.episode +"/";
				else if(lnk.episode_id) url+=lnk.episode_id.toLowerCase() +"/";
			}			
			if(lnk.type) url+=lnk.type +"/";//?type=" +lnk.type;
			if(lnk.itemnum) url+="?itemnum=" +lnk.itemnum;

			if(!$.browser.msie){
				$(container).load(url);
			}else{
				$.get(url, function(html){ $(container)[0].innerHTML = html; });	// IE needs special treatment to cope with some complex content.
			}

			if(isPageInitialised){ window.scrollTo(0,140) };
			return false;		// Stop the default link action.
		}


		else{

			//alert( $link.outerHtml() )

		}


		// Otherwise remove the no-javascript (nojs) param from the link so that the target page knows what to display:
		if( $link.attr("href") ){ $link.attr({ href: $link.attr("href").replace(/[\?&]nojs(=([^?&#=]*))?/,"") }); };

	}


});


















// Common functions and variables:

	var replacedTitleIndex=0;//index used to give id's to elements created to contain swf text replacement

	function getHashOfQueryParams(href){

		if(href){
			var prm = { href		:href, pathname:href.split("?").shift(),			// Everything before ?
						querystring	:(/\?([^#$]*)/.exec(href) || [''])[0],				// Everything after  ? (but before #)
						bookmark	:href.indexOf("#") > 0 ? href.split("#").pop() : "",// Everything after  #
						fileext		:href.split("?").shift().split(".").pop()
				};
				//href.replace(/^([^?]+)\??([^#]*)\#?(.*)$/, function($0,$1,$2,$3){ prm.href=$1; prm.querystring=$2, prm.bookmark=$3; });
				prm.href.replace(/[\?&]([^?&#=]+)(=([^?&#=]*))?/g, function($0,$1,$2,$3){ prm[$1]=$3||'' });
				prm.pathname.replace(/(doctorwho\/s4\/(episodes|characters|games|videos|images|audio|confidential|news|features))/, function($0,$1,$2){ prm.pagename=$2 });
				prm.pathname.replace(/(?:episodes|characters|games|videos|images|audio|confidential|news|features)\/(([sS][1-9]_[a-zA-z0-9]+)|([^\/\?#]+))[\/\?$]?/, function($0,$1,$2,$3){ prm.episode_id = prm.episode_id || prm.episode || prm.episodeid || $2; prm.character = prm.character || $3 });	// Or: if( !prm.character ){ with( prm.href.split("?").shift().split("/") ){ prm.character = pop() || pop() }};
				if( prm.playlist && prm.playlist.indexOf("http") != 0 ){ prm.playlist = "http://" + document.location.hostname + (prm.playlist.indexOf("/") != 0 ? "/" : "") + prm.playlist };
			return prm;
		}else{
			return {};
		}

	}
	
	
	function removeBlockUI(){		
		$.unblockUI();
		$('#swfTitle0-container,#swfTitle1-container').show();
	}



	function writeSWFHeading($textToReplace,swf,bg_image,fontSize,letterSpacing,convertToUppercase, forceLabel,colour){

		if(!isFlashAvailable){ return false; }
				
		var replacedTitleID="swfTitle" +replacedTitleIndex++;
		var label=forceLabel ? forceLabel : ($textToReplace.html());
		
		var containerID=replacedTitleID +'-container';


		var width=$textToReplace.css('width');
		var height=$textToReplace.css('height');
		width=width.replace("px","");
		height=height.replace("px","");
		
		if(isNaN(width) || isNaN(height) ){
			return;
		}
		
		var position=$textToReplace.css('position');
		var top=parseInt($textToReplace.css('top'));
		var left=parseInt($textToReplace.css('left'));
		
		if(isNaN(top) || isNaN(left) ){
			return;
		}
		
		fontSize=label.length>42 ? fontSize-4 : fontSize;
		
		
		var $s=$textToReplace.before('<div id="' +containerID +'"></div>');
		//$textToReplace.css('text-indent','-9999px');
		$textToReplace.addClass('replaced_text');


		$('#'+containerID).css({
			position: 'absolute',
			top: top ,
			left: left,
			width: width ,
			height: height
		});
		
		


		if(convertToUppercase) label=label.toUpperCase();
		label=escape(label);
		
		

		var swf = new SWFObject(swf, replacedTitleID,width,height, 8, "#000");
		swf.addVariable('label',label);
		swf.addVariable('size',fontSize);
		swf.addVariable('letter_spacing',letterSpacing);
		swf.addVariable('bg_image',bg_image);
		if(colour) swf.addVariable('colour',colour);
		swf.write(containerID);

	}

	function writeVideoEMP(playlist, width, height, domid){
		config="http://www.bbc.co.uk/doctorwho/s4/emp/config_video.xml";
		writeEMP(config,playlist,width,height,domid);
	}

	function writeAudioEMP(playlist, width, height, domid){
		height=106;
		config="http://www.bbc.co.uk/doctorwho/s4/emp/config_audio.xml";
		writeEMP(config,playlist,width,height,domid);
	}

	function writeEMP(config, playlist, width, height, domid){
		// Assume defaults where params not specified:
		config	= config 	|| "http://www.bbc.co.uk/doctorwho/s4/emp/config_video.xml";
		playlist= playlist	|| "";
		width	= width		|| "512";
		height	= height	|| "323";
		domid	= domid		|| "emp-container";

		if( $("#"+domid).length ){
			var emp = new bbc.Emp();
			emp.setWidth(width);
			emp.setHeight(height);
			emp.setDomId(domid);
  			emp.setConfig(config);
			emp.setPlaylist(playlist);
			emp.write(domid);
		}
	}

	function embedInlineEMP(){
		var emp = new bbc.Emp();
		emp.setDomId("inline-emp");
		emp.setWidth("512");
		emp.setHeight("323");
		emp.set("config_settings_skin", "black");	
		emp.set("config_settings_showShareButton","true");		
		emp.setPlaylist(inlineEmpPlaylist);
		emp.write();
	};
	
	$.fn.embedInlineEMP = 	function (){
		var emp = new bbc.Emp();
		emp.setDomId("inline-emp");
		emp.setWidth("512");
		emp.setHeight("323");
		emp.set("config_settings_skin", "black");
		emp.set("config_settings_showShareButton","true");
		emp.setPlaylist(inlineEmpPlaylist);
		emp.write();
	};
	
	// Simple jQuery plugin to return the outerHtml of the selected element(s):
	$.fn.outerHtml = function(){ return $("<div>").append( this.clone(true) ).html(); };

	// Custom fx to animate css backgroundPosition:
	$.extend($.fx.step,{ backgroundPosition: function(fx) {

		if ( !fx.state && typeof(fx.end) == 'string' ) {

			function getXY(bg){
				bg = bg.replace(/left|top/g,'0px').replace(/right|bottom/g,'100%').replace(/([0-9.]+)(\s|\)|$)/g,"$1px$2")
					.match(/(-?[0-9.]+)(px|\%|em|pt)\s(-?[0-9.]+)(px|\%|em|pt)/);
				return { xy:[ parseInt(bg[1]) || 0, parseInt(bg[3]) || 0 ], unit:[ bg[2], bg[4] ] };
			}

			var	end			= getXY(fx.end);
			fx.start		= getXY($.curCSS(fx.elem,'backgroundPosition')).xy;
			fx.end			= end.xy;
			fx.unit			= end.unit;
			fx.startOffset	= [ fx.end[0]-fx.start[0], fx.end[1]-fx.start[1] ];	// Pre-calculate to improve performance.
		}
		fx.elem.style.backgroundPosition = (fx.startOffset[0] * fx.pos + fx.start[0]) + fx.unit[0]
								   + ' ' + (fx.startOffset[1] * fx.pos + fx.start[1]) + fx.unit[1];
	}});


	$.extend($.easing, {
		easeInBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.20158;
			return c*(t/=d)*t*((s+1)*t - s) + b;
		},
		easeInOutBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return ((t/=d/2) < 1) ? c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b : c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
		}
	})


	

})(jQuery.noConflict()) }




function writeSWFPromo(swf_content,width,height,domid,swfid,variables){
	
	
	if(!isFlashAvailable) return false;

	var swf="/doctorwho/s4/includes/swf/promo_loader.swf";
	swf = new SWFObject(swf, swfid, width, height, 8, "#000000");
	swf.addVariable('content_path',swf_content);
	swf.addVariable('hide_edge','true');
	if(variables!=null){
		for(var i=0;i<variables.length;i++){
			var pair=variables[i];
			swf.addVariable(pair[0],escape(pair[1]));
		}
	}
	swf.write(domid);
}