// JavaScript Document
//		The JS
// 		Author TWB, BL, e3 2009-2010
/* Javascript stylesheet */
var mobile;
$(document).ready(function() {

	var mobile = fnDetectMobile();// check mobile
	
	// txt boxes
	fnInputTxtSwitch();
	
	oldWidth = $('body').width();
	oldHeight = parseInt((typeof window.innerHeight != 'undefined' ? window.innerHeight : document.documentElement.clientHeight));
	
	// when the window is resized
	$(window).resize(function() {
		// check if it's wide enough to be the wide layout
		fnWidthChange();		
		// TO DO adjust slider to nearest whole video thumbnail
		fnNewsList();
		fnShowreelsList();
	});
			
	
	// Preload all images with 'roll' class
	$('.roll').each(function() {
		$(this).preloadImg();
	});
	
	// Apply hover to image with class 'roll' via their parent anchor.
	$('a').each(function() {
		oFirstChild = $(this).children(':first');
		if (oFirstChild.is('img')) {
		  if (oFirstChild.attr('class') == 'hov') {
		    $(this).hover(
		      function () {
		        $(this).children(':first').swapImg();
		      }, 
		      function () {
		        $(this).children(':first').swapImg();
		      }
		    );
		  }
		}
	});
	
	//Apply hover to image without wrapping anchors (e.g. form input image)
	$('input.hov').hover(
		function () {		
		  $(this).swapImg();
		}, 
		function () {
		  $(this).swapImg();
		}
	); 
	
	fnWidthCheck();
	fnLoadToolsDivs();
	fnResize();
	//fnTabs();
	//fnFooterClocks();
	//fnWrkCats();
	fnHomeSlide(); //
	/*fnSectShowHide(true);
	fnPeopleList();
	fnNewsList();
	fnShowreelsList();
	fnEmailForm();
	fnVideoPlayer();
	fnSubNav();
	fnPagerSlider();
	fnShowReels();  
	fnColourists();  
	mobileColourists();
	fnWhoWeAre();
	fnBindPlaylistEvents();
	fnPlaylistSave(); // saving playlist - deals with dummy cookie too
	fnPlaylistSend(); // Sending playlist
	fnPlaylistEmpty();*/ //empty playlist
	
	//fnFormDefaultText(); // init form placeholder text swapouts
	//fnGallery();

}); // end onload/ready

// mobile checkinitially looking for iphone/ipod touch and iPad

var bIphone,bIpod,bIpad;
function fnDetectMobile(){	
	var mobCheck;	
	var agent=navigator.userAgent.toLowerCase();
	bIphone = ((agent.indexOf('iphone')!=-1));
	bIpod = ((agent.indexOf('ipod')!=-1));
	bIpad = ((agent.indexOf('ipad')!=-1));
	if (bIphone || bIpod || bIpad) {
		mobCheck = true;
	}
	else{		
		mobCheck = false;	
	}	
	return mobCheck;	
}

// Global Variables
var wide,enhanced;

var oldWidth,oldHeight;

var fsclerkLight = {src: "/theMillAssets/flash/fsclerkenwell-light.swf"};
var fsclerk = {src: "/theMillAssets/flash/fsclerkenwell.swf"};

/*var screenWidth = 1263;
var screenHeight = 860;
*/
var screenWidth = 960;
var screenHeight = 345;

// Find width of body, if it's big enough, serve the wider layout
function fnWidthCheck(){
	
	h = (typeof window.innerHeight != 'undefined' ? window.innerHeight : document.documentElement.clientHeight);
	w =	$('body').width();
	
	
	if(w > screenWidth /*&& h>screenHeight*/){
		$('body').addClass('wide');
		wide=true;		
		fnImageSwap();
		fnFlashSwap();
		fnPlaylistSlider();	
		$.cookie('theMillWidth', 'wide', { path: '/' }); // remember that we're wide - server writes class of wide on body
		
		
	}else{
		$('body').removeClass('wide');
		wide=false;	
		fnImageSwap();
		fnFlashSwap();
		fnPlaylistSlider();
		$.cookie('theMillWidth', '', { path: '/' }); // wipe the wide cookie
		
	}
}

function fnWidthChange(){
	
	newWidth = $('body').width();

	if((newWidth > screenWidth /*&& newHeight>screenHeight*/) &&  (oldWidth<= screenWidth /*|| oldHeight<=screenHeight*/)){	
		
		$('body').addClass('wide');
		wide=true;		
		fnImageSwap();
		fnFlashSwap();
		fnPlaylistSlider();
		launchVidInPage();
		fnHomeSlideStop();
		//fnHomeSlide();
		oldWidth = $('body').width();
		//oldHeight = parseInt((typeof window.innerHeight != 'undefined' ? window.innerHeight : document.documentElement.clientHeight));		
		
		$.cookie('theMillWidth', 'wide', { path: '/' }); // remember that we're wide - server writes class of wide on body
		
	} else if((newWidth<=screenWidth && oldWidth>screenWidth) /*|| (newHeight<=screenHeight && oldHeight>screenHeight)*/){
		
		$('body').removeClass('wide');
		wide=false;		
		fnImageSwap();
		fnFlashSwap();
		fnPlaylistSlider();
		launchVidInPage();
		fnHomeSlideStop();
		//fnHomeSlide();
		oldWidth = $('body').width();
		//oldHeight = parseInt((typeof window.innerHeight != 'undefined' ? window.innerHeight : document.documentElement.clientHeight));
		
		$.cookie('theMillWidth', '', { path: '/' }); // wipe the wide cookie
		
	}
}

function fnLoadToolsDivs() {
	// dont ajax in on the non-js pages - redundant logic?
	if($('#eCont').length>0 || $('#ePlay').length>0 || $('#eFollow').length>0 ){		
		fnPlaylistSlider();
		return false;		
	}
	else{	
		// add a loading div - delete it later & a feedback div used by add to playlist functionality
		$('#e').append('<div id="loader" class="hide"></div>');		
		
		// load the contact page in to the loader div
		if ($('#tContact').length>0) {
      $('#loader').load($('#tContact').attr('href').replace('#',' #'), function(){
        //add it to the expanding content div
        $('#e').append($('#eCont'));
        fnContacts();
      });
		}
		
		// load the contact page in
    if ($('#tFollowUs').length>0) {
      $('#loader').load($('#tFollowUs').attr('href').replace('#',' #'), function(){
        $('#e').append($('#eFollow').hide());
      });
		}
		
		// load the contact page in
    if ($('#tPlaylist').length>0) {	
    	
			// caching issue - add a random number to the querystring - unix timestamp as an integer will do.
			var time = Math.round(new Date().getTime() / 1000); 		
			pUrl = $('#tPlaylist').attr('href').replace('#','?ajax=true&refresh='+time+' #'); // url with unix timestamp attached
			
			$('#loader').load(pUrl, function(){
        $('#e').append($('#ePlay'));
        fnImageSwap($('#ePlay'));
        fnPlaylistSlider(); // must go before fnPrepToolsDivs()
        fnPrepToolsDivs();
      });		
		}
		
		// add stuff to handle feedback messages
		$('#e').append('<div id="feedBack" class="panel cfx"><div class="inr"><p><a href="#" class="showPL"></a></p></div></div>');
		$('#tools').append('<a id="tFeedback" href="#feedBack" class="hide"></a>');
		//$('#feedBack').hide();
		
	}	
}

function fnPrepToolsDivs() {		
	
	// declare the variables
	var $targ,$wrap;
	$wrap = $('#eW');
	
	// hide the panels
	$('#eW .panel').hide();
	fnTabs(); // apply the tabs in the ajaxed 
	// bind the event functionality
	$('#tools a').live('click', function() {
		
		$('#ePlay:hidden').find('div.panel').hide(); // try to fix bug where panels arent all hidden
		
		// set target panel
		$targ = $($(this)[0].hash);	
	
		// if the expanding nav wrapper is currently being animated 
		if($('#eW,#eW div').is(':animated')){			
			return false; // prevent halting mid-animation
		}		
		// if not animating
		else{
			
			// there's only one div now						
			$wrap.addClass('open');
			// the panel we want is already open - close it
			if($targ.hasClass('open')){ 
				$targ.slideUp(600,"easeInOutQuad",function(){
					$wrap.removeClass('open');
				}).removeClass('open');				
				$(this).removeClass('selected');
			}
			
			// the panel we want is not open			
			// - slideUp current panel
			// - slideDown target panel			
			
			else if($('#e div.open').length>0){				
				//$wrap.addClass('open');
				$('#e div.open').slideUp(600,"easeInOutQuad").removeClass('open');	
				//$targ.delay(600).slideDown(600, "easeInOutQuad").addClass('open');		
				$targ.delay(600).slideDown( {
					duration:600,
					easing:"easeInOutQuad",
					complete:function(){
						fnOpened($(this));						
					}					
				}).addClass('open');		
				$('#tools a').removeClass('selected');
				$(this).addClass('selected');
			}
			
			// OR
			// all panels are closed
			// - open the target one			
			else{				
				$wrap.addClass('open');
				//$targ.slideDown(600,"easeInOutQuad").addClass('open');	
				$targ.slideDown({
					duration:600,
					easing:"easeInOutQuad",
					complete:function(){
						fnOpened($(this));						
					}					
				}).addClass('open');				
				$('#tools a').removeClass('selected');			
				$(this).addClass('selected');
			}		
			return false;
		}							
		return false;
		
	});
	$('#eW .panel').hide();
}

function fnOpened($obj) {	
	
	// this is for playlist opening animation only
	if($('#vid').length>0){		
		$('#vid')[0].respond('pause'); // pause the video in the page if there is one				
	}
	
	if($('#plScroll ul li').length>0){
		$('#plScroll ul li:first a.vid').click(); // click the first playlist thumbnail if it's there, to add the flash to the  - should it autoplay?			
	}
	
	setTimeout(function() {
		if($('#ePlay.open').length>0){			
			if($('#ePlayVidHolder').length>0){			
				$('#ePlayVidHolder')[0].respond('pause'); // pause the video in the page if there is one	
			}		
		}		
		if($('#vid').length>0){		
			$('#vid')[0].respond('pause'); // pause the video in the page if there is one				
		}				
	}, 500);	
			
}

// hide the expanding nav wrapper, but allow the children to have layout
function fnHideEW() {
	$('#eW').css({display: 'block', height: 0, oveflow: 'hidden',padding:0});	
}
// show the expanding nav wrapper
function fnShowEW() {
	$('#eW').css({height: 'auto', oveflow: 'visible',padding: '0 0 20px 0'});	
}

// swap flash from med to lrg or vice versa
function fnFlashSwap($obj) {
	if($obj){
		// set to the passed in object
		//$target = $obj.find("img");
	}
	// find the flash on the page and swap it
	
	// find sifr and re-draw?	
}

// swap images from med to lrg or vice versa
function fnImageSwap($obj) {
	var $target;
	if($obj){
		$target = $obj.find("img");
	}
	else{
		$target = $("img");
	}
	$target
		.each(function() {
			
			//for flat build			
			/*
			if(wide){
				$(this).attr("src",$(this).attr("src").replace("_med","_lrg"));									
	        }else{
				$(this).attr("src",$(this).attr("src").replace("_lrg","_med"));				
			}					
			*/
			
			// for live	- uses rel not _med/_lrg			
			// Umbraco CMS resizable images have the widths in a rel tag (like rel="resize=281,233") and in the image src (like width=288&)
			if($(this).attr("rel") && $(this).attr("rel").indexOf("resize=")==0){					
				var largeWidth = $(this).attr("rel").substr(7).split(',')[0]; // strip the resize= and split by , to get large and small
        var smallWidth = $(this).attr("rel").substr(7).split(',')[1];
      }
	        
			if(wide){
        // going from small to large, or large on load			
        $(this).attr("src",getResizedVideoImageURL($(this).attr("src"), largeWidth ,"_lrg"));
			}
			else{				
        // going from large to small, or small on load
        $(this).attr("src",getResizedVideoImageURL($(this).attr("src"), smallWidth ,"_med"));
			}
			
		});	
}

function fnPlaylistSave() {
	// save playlist only when clicked - so store temp copy of playlist as per when loaded
	
	// bind
    $('#plSaveBtn input.btn').live('click', function() {
        var confirmSave = '<div id="emailForm" class="confirmSave"><h2 class="irt"><span style="background: url(/umbraco/TigerLive.aspx?tid=2&amp;text=Save+Playlist) no-repeat scroll 0 0 #fff;"></span>Save Playlist</h2><div id="confirmSaveMessage"><p>Are you sure you want to save this Playlist?</p><p>Any previous Playlists will be lost.</p><p><a href="#" id="confirmSave">Yes</a><a href="#" id="cancelSave">No</a></p></div></div>';
        var close = '<a href="#" title="Close" class="close">Close</a>';        
        $.blockUI({ css: {
            'background': 'none',
            'border': '0',
            'top': '30%',
            'width': '570px',
            'left': '50%',
            'margin-left': '-275px',
            'cursor': 'default'
        }, overlayCSS: {
            backgroundColor: '#000',
            opacity: 0.9
        }, message: confirmSave + close
        });
        function unBlock() {
            $.unblockUI();
            //$('#vidHolder').html('<div id="vid"></div>');
            $('body').removeAttr('style');
            launchVidInPage();
        }
        $('.blockOverlay, .close').click(function() {
            unBlock();
            return false;
        });
        $(document).keyup(function(e) {
            if (e.keyCode == 27) {
                unBlock();
            }
        });
        $('#confirmSave').live('click', function() {
                  	
        		// when a user has just created a playlist and wants to name it
        		// just save the playlist title - leave the playlist cookie alone, its handled by adding the videos
        		// when a user has reordered, deleted or changed name
        	
        		/*
            // overwrite main cookie with temp one            
            $.cookie('theMillPlaylist', tempCookie, { expires: 10000, path: '/' });            
            */
            
            var plName = $('#playlist_name').val();
            var emailAdd = $('#your_email').val();            
            
            // submit the form via ajax with the cookie value (cookie should be passed automatically)
            $.get('/my-playlist.aspx?txtSavePlaylistName='+escape(plName)+'&txtSavePlaylistEmail='+escape(emailAdd)+'&sendsavedplaylist=true', {}, function(res, status) {
                // ASPX returns OK if it sent OK.
                if ((status == "success" || status == "notmodified") && res == 'OK') {
                	
                		// set the playlist name on the screen
				            $('#ePlayShare h2 strong').text(plName);
				            $('#ePlayShare h2 span').css('background', '#fff url(/umbraco/TigerLive.aspx?tid=2&text=' + escape(plName) + ') 0 0 no-repeat');
										// save playlist title as 
				            $.cookie('theMillPlaylist-title', plName, { expires: 10000, path: '/' }); 
				            $.cookie('theMillPlaylist', getPlaylistValues(), { expires: 10000, path: '/' }); 
										
				            // return success message
                    $('#confirmSaveMessage').html('<p>Your playlist has been saved and sent to your email address.</p>');                    
                } else {
                    $('#confirmSaveMessage').html('<p>Sorry, there was a problem sending your playlist: ' + res + '. Please try again.</p>');
                }
            });
            return false;
        });
        $('#cancelSave').live('click', function() {           
            $('a.close').click(); // submit the form
        });
        return false;
    });	
	
	// if there's a cookie, copy it to temp version - session cookie
	if($.cookie('theMillPlaylist') != null){	
		var curCookie = $.cookie('theMillPlaylist');
		$.cookie('theMillPlaylist-temp', curCookie, { path: '/' }); 
	}
	
}

// loop 
function getPlaylistValues() {
	// loop playlist LI As and pull out the wId
	var newCookieValue = 'delete';
	$('#plScroll li a.vid').each(function() {
		var plVidJSON = getVidObjectsFromURL($(this).attr('href'));		// get JSON object from URL 
		newCookieValue += ','+plVidJSON.wId;		
	});
	newCookieValue = newCookieValue.replace('delete,','');	
	return newCookieValue;		
}

function fnPlaylistSend() {
	// save playlist only when clicked - so store temp copy of playlist as per when loaded	
	// bind
    $('#plSendBtn input.btn').live('click', function() {
        var confirmSave = '<div id="emailForm" class="confirmSend"><h2 class="irt"><span style="background: url(/umbraco/TigerLive.aspx?tid=2&amp;text=Send+Playlist) no-repeat scroll 0 0 #fff;"></span>Send Playlist</h2><div id="confirmSendMessage"><p>Sending...</p></div></div>';
        var close = '<a href="#" title="Close" class="close">Close</a>';
        // comeback
        $.blockUI({ css: {
            'background': 'none',
            'border': '0',
            'top': '30%',
            'width': '570px',
            'left': '50%',
            'margin-left': '-275px',
            'cursor': 'default'
        }, overlayCSS: {
            backgroundColor: '#000',
            opacity: 0.9
        }, message: confirmSave + close
        });
        
        // dont need to confirm this time
        
        // Get form values.
        var txtPlaylistName = $('#txtPlaylistName').val();
        var txtRecipientEmail = $('#txtRecipientEmail').val();
        var txtYourName = $('#txtYourName').val();
        var txtYourEmail = $('#txtYourEmail').val();
        
        // overwrite main cookie with temp one
        //var tempCookie = $.cookie('theMillPlaylist-temp') ? $.cookie('theMillPlaylist-temp') : '';
        //$.cookie('theMillPlaylist', tempCookie, { expires: 10000, path: '/' });

        // TODO: Show a spinner or something while this loads.

        // submit the form via ajax with the cookie value (cookie should be passed automatically)
        $.get('/my-playlist.aspx?txtPlaylistName='+escape(txtPlaylistName)+'&txtRecipientEmail='+escape(txtRecipientEmail)+'&txtYourName='+escape(txtYourName)+'&txtYourEmail='+escape(txtYourEmail)+'&sendplaylist=true', {}, function(res, status) {
            // ASPX returns OK if it sent OK.
            if ((status == "success" || status == "notmodified") && res == 'OK') {
                $('#confirmSendMessage').html('<p>Your playlist has been sent to the recipients entered.</p>');
            } else {
                $('#confirmSendMessage').html('<p>Sorry, there was a problem sending your playlist: ' + res + '. Please try again.</p>');
            }
        });

        function unBlock() {
            $.unblockUI();
            $('#vidHolder').html('<div id="vid"></div>');
            $('body').removeAttr('style');
            launchVidInPage();
        }
        $('.blockOverlay, .close').click(function() {
            unBlock();
            return false;
        });
        $(document).keyup(function(e) {
            if (e.keyCode == 27) {
                unBlock();
            }
        });

        return false;
    });	
	
}

function fnAdjustScrollDiv() {
	var $scrollDiv = $("#plScroll");
	var vids = $('#ePlayList ul li').length;
	var x = wide ? 14 : 34; // gutter between thumbnails - logic for wide layout or not	
	var w = 208; // width of thumbnail	
	var thumbW = w + x; // width of thumbnail	
	$("ul:first",$scrollDiv).width((thumbW*vids));		
	fnPlaylistSlider();
	//fnUpdateSlider(); // adjust slider
}
function fnPlaylistSlider() {	
	
	if($("#cW #ePlay").length > 0){ // if we're on the standalone playlist page		
		if($("#plScroll li a").length > 0){
			$("#plScroll li:first a.vid").click(); // click the first thumb so it puts the flash in the page (and plays)
		}
	}
		
	// if browser is resized, then re-write the video 
	if($("#plScroll li.nowPlaying").length > 0){
		$("#plScroll li.nowPlaying a.vid").click()
			.parent().addClass('nowPlaying');//default click will toggle off the nowplaying class
	}
	
	//hide the scrollbar
	$('#plScroll').css('overflow','hidden');
	$('#ePlayList input,#ePlayList label').remove();
	$('#ePlayVid').wrapInner('<div id="ePlayVidHolder" />');
	
	// wide is set in fnWidthCheck()
	var x = wide ? 14 : 34; // gutter between thumbnails - logic for wide layout or not	
	var w = 208; // width of thumbnail	
	var thumbW = w + x; // width of thumbnail	
	var vids = $('#ePlayList ul li').length;
	
	// scrolling div
	var $scrollDiv = $("#plScroll");
	var handleWidth = 99;
	
	// $.slider vars
	//var myMax = wide ? 984: 822;
	var trackW = $('#track').width();
	var perPage = wide ? 5 : 4;	
	var slideStep = Math.floor(trackW/(vids-perPage+1));
	var pages = Math.ceil(vids / perPage);
	var scrollStep = thumbW;	
	var targPoint=0;
	
	// adjust scrolling div	
	$scrollDiv.find("ul:first").width((thumbW*vids));
	//fnAdjustScrollDiv();
	
	
	//var ul = $scrollDiv.find("ul:first");
	
	// track the slider's value
	var stopped=false;
	var coeff = trackW / vids; // this is the value you need to figure out "how many videos" the handle slider moved	
	var curVid = 0;	
	var minVids = wide ? 5 : 4;
	
	if(vids > minVids){			
		//$('#trW').attr('style','');		
		$("#track").css('pointer','default');				
		$('#plScroll').scrollLeft(0);
		$("#track").slider({
			value:0,
			min: 0,
			max: trackW-handleWidth,
			step: slideStep, // number of steps = number of videos - videos shown in 1 page
			animate: true,			
			slide: function(event, ui) {						
				x = wide ? 14 : 34; // recalc in case resized window to wide/narrow
				thumbW = w + x; // recalc if resized
				var xx =  Math.round(ui.value/coeff);						
				//calc which vid you're on and use vid number to move along scrolling div
				if(xx!=curVid){$('#plScroll').stop().animate({"scrollLeft": getTargetPoint(ui,thumbW,coeff)}, 400, 'easeInOutQuad');}							
				curVid = xx;
			}				
		});	
	}else{		
		$('#plScroll').scrollLeft('0'); // reset scrolling div
		//$('#trW').css('background','none'); // remove bg of track
		$("#track").slider("destroy");		
		$("#track").css('cursor','default');		
	}

	if(vids > 1){
		var $playAllBtn = '<a href="#" class="all hov" id="plPlayAll">Play all</a>';	
		$('#ePlayShare div.dots').append($playAllBtn);
	}
		
	// show-hide the move and delete btns
	$("#plScroll ul li").hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	})
	.find("a").focus(function() {
		$(this).parents("li:first").addClass('hover');		
	})
	.blur(function() {
		$(this).parents("li:first").removeClass('hover');
	});	

	// click to play first video - find thumbnail with 
	// same vid id in href and click it - functionality already done (a.vid)
	$("#ePlayVid a").live('click',function(){
		var toFind = $(this).attr('href').split('/file/')[1].split('/')[0];
		$('#plScroll a:first[href*="'+ toFind +'"]').click();		
		return false;
	});
	
	$("#plScroll a.vid").click(function() {		
	
			$(this).parents("ul").find("li.nowPlaying").removeClass("nowPlaying");
			$(this).parents("li:first").addClass("nowPlaying");
			fnPlayVideo($(this));
			return false;
	
	});
	
	// sort functionality
	$("#plScroll a.right").click(function() {		
		$(this).parents('li:first').removeClass("hover").moveLeft();
		return false;
	});
	// sort functionality
	$("#plScroll a.left").click(function() {
		$(this).parents('li:first').removeClass("hover").moveRight();
		return false;
	});
	
	// Delete functionality
	$("#plScroll a.del").click(function() {	
				
		var $parLI = $(this).parents('li:first');
		
		var vidJSON = getVidObjectsFromURL($('a.vid',$parLI).attr('href'));		// get wId 
		fnRemoveFromPlaylist(vidJSON.wId);// remove from cookie
		
		//
		var iPos = $("#plScroll ul li").index($parLI); // zero index 
		iPos++; // increase to match length calcs later
						
		$parLI
			.css({width: thumbW, padding: 0})
			.animate({"opacity":"0"}, 300,
				function() {
					// remove items - allows smoother width animation					
					$(this)
						.animate({"width":"0"},400,
							function() {
								$(this).remove();
								vids = $('#ePlayList ul li').length;
								$scrollDiv.find("ul:first").width((thumbW*vids));								
							});
			});			
						
							
		fnUpdateSlider();
		fnUpdateSliderPages(); // required? There is no concept of pagination as the slider moves 1-by-1		
		//fnReplaceCurrentVideo(iPos);		
		//fnUpdatePlaylistTitle(sTitleReplace);		
		return false;
	});
			
	
	$("#plPlayAll") .live('click', function(){		
		// play first 
		$('#plScroll li:first a.vid').click();
		return false;
	});
	
	
}

function fnPlaylistEmpty() {
	// save playlist only when clicked - so store temp copy of playlist as per when loaded
	
	// bind
    $('a#emptyList').live('click', function() {
        var confirmEmpty = '<div id="emailForm" class="confirmEmpty"><h2 class="irt"><span style="background: url(/umbraco/TigerLive.aspx?tid=2&amp;text=Empty+Playlist) no-repeat scroll 0 0 #fff;"></span>Empty Playlist</h2><div id="confirmEmptyMessage"><p>Are you sure you want to empty this Playlist?</p><p><a href="#" id="confirmEmpty">Yes</a><a href="#" id="cancelEmpty">No</a></p></div></div>';
        var close = '<a href="#" title="Close" class="close">Close</a>';        
        $.blockUI({ css: {
            'background': 'none',
            'border': '0',
            'top': '30%',
            'width': '570px',
            'left': '50%',
            'margin-left': '-275px',
            'cursor': 'default'
        }, overlayCSS: {
            backgroundColor: '#000',
            opacity: 0.9
        }, message: confirmEmpty + close
        });
        function unBlock() {
            $.unblockUI();
            //$('#vidHolder').html('<div id="vid"></div>');
            $('body').removeAttr('style');
            launchVidInPage();
        }
        $('.blockOverlay, .close').unbind().click(function() {
            unBlock();
            return false;
        });
        $(document).keyup(function(e) {
            if (e.keyCode == 27) {
                unBlock();
            }
        });
        $('#confirmEmpty').live('click', function() {
            
        	//empty playlist message        	
        	var emptyMsg ='<div class="cfx" id="plEmpty"><h4>Your playlist is currently empty</h4><p>To make a playlist simply select a piece of work and click the "add to playlist" button. <em>You can then save for later viewing or share with a friend.</em></p></div>';
        	
        	//wipe the cookies.
			$.cookie('theMillPlaylist-temp',null, {path: '/'});
			$.cookie('theMillPlaylist',null, {path: '/'});
			
        	//set the message to the empty message and close the playlist
        	$('#ePlay .inr:first').html(emptyMsg);
        	$('a.close').click();
        	$('a#tPlaylist').click();
        	//replace the added button with add button.
        	fnReplaceWithAdd();
        	return false;

        });
        $('#cancelEmpty').live('click', function() {
            $('a.close').click(); // close the form
            return false;
        });
        return false;
    });	
	
}

function fnReplaceCurrentVideo(i) {
	/* @param i: integer denoting array position in list of LI thumbnails */
	var $aLis = $("#plScroll li");
	if($aLis.length == i){
		// deleting the last one		
		i--;		
		$aLis.eq(i);
	}else{
		// deleting any but the last one
		// use the i as it will be replaced by the next one
		// dont need to do anything		
	}
	// either get the flash video player to display the video for li>a at position i
	// or display an image placeholder for the video	
	sTitleReplace = $aLis.eq(i).find('a.vid').attr('href');
	return sTitleReplace;
}

// unused?
function fnPauseVideo(oObj) {
	// pause flash video player	
	//document.getElementById(mymovie).PausePlay(); 	
	oObj.PausePlay();	
	
}

function fnPlayVideo($a) {
	var vidInfo = getVidObjectsFromURL($a.attr('href')); // for testing	

	if(fnDetectMobile() == false)
	{
		launchPlaylistInPage(vidInfo);							
	}
	else if(bIpad == true)
	{		
		// function for ipad specifically atm
		fnHTML5Video(vidInfo);		
	}// other devices could go after this, or do a switch
	
	// Update now playing text
	var sTitle = $("strong",$a).text();	
	fnUpdatePlaylistTitle(sTitle);
	
	// Update find out more link
	$("#ePlayShare a.arr").attr('href', vidInfo.wUrl);	
}

function fnUpdatePlaylistTitle(sText){	
	$("#ePlayShare p.now strong").text(sText);	
}

function fnUpdateSliderPages() {
	var sVids = $('#ePlayList ul li').length;	
	$('#items').text(sVids-1);
}

function fnUpdateSlider() {
	var uVids = $('#ePlayList ul li').length;
	var uTrackW = $('#track').width();
	var uPerPage = wide ? 5 : 4;	
	var uSlideStep = Math.floor(uTrackW/(uVids-uPerPage));		
	$("#track").slider('option', 'step', uSlideStep);		
}



// return calculated targetPoint - x axis value the scrolling div needs to go to
function getTargetPoint(ui,thumbW,coeff) {		
	// place to scroll to = width of video thumb incl gutter * number of steps(videos) we've moved - slider handle position / step value;
	var targetPoint = thumbW * ui.value/($('#track').slider( 'option' , 'step' ));
	
	return targetPoint;
}

// add move left/right to jquery - extend
$.fn.moveRight = function() {
    before = $(this).prev();
    $(this).insertBefore(before);
};	
$.fn.moveLeft = function() {
    after = $(this).next();
    $(this).insertAfter(after);
};

/*
Cookie control for playlist
*/

function fnBindPlaylistEvents() {	
	$('a.addToPL').live('click',function(){	
		$('#eW div.panel').not('.open').hide();
		fnAddToPlaylist($(this).attr('href').split('wid=')[1]);
		fnReplaceWithAdded();
		return false;
	});

	$('#wrkLst a.add').live('click',function(){
		$('#eW div.panel').not('.open').hide();
		fnAddToPlaylist($(this).attr('href').split('wid=')[1]);
		fnReplaceWithAddedWork($(this));
		return false;
	});	
	
	$('#wrkLst .box').live('mouseenter',function(){
			$(this).find('a.add').show();
		}).live('mouseleave',function(){
			$(this).find('a.add').hide();
		});
	
	$('a.addedToPL').live('click',function(){
		$('#tPlaylist').click();
		return false;
	});
}

function fnReplaceWithAdded() {
	href = $('a.addToPL').attr('href');	
	$('a.addToPL').replaceWith('<a class="addedToPL" href="'+href+'">Added to My Playlist</a>');
}

function fnReplaceWithAddedWork(obj) {
	obj.replaceWith('<span class="added">Added to My Playlist</span>');
}

function fnReplaceWithAdd() {
	href = $('a.addedToPL').attr('href');
	$('a.addedToPL').replaceWith('<a class="addToPL hov" href="'+href+'" rel="nofollow">Add to my playlist</a>');
}

// for development only
function createDummyCookie(){
	$('#ePlay').append('<a href="#" id="cookieTest">ADD DUMMY COOKIE</a>');	
	$('#cookieTest') .click(function() {
		$.cookie('theMillPlaylist-temp','1111,2222,3333,4444,5555,6666,7777,8888,9999,0000', { path: '/' });		
		return false;
	});
}

function fnPlaylistTitle() {
	var playlistTitle = ''; // get value of "title" input box from save form
	$.cookie('theMillPlaylist-title', title, {expires: 10000, path: '/'}); // create or set cookie
}

function fnAddToPlaylist(wId) {	
	// get value of playlist cookie, split string and get wIds (videos)
	var curCookieVal = $.cookie('theMillPlaylist');				
	if(curCookieVal == null){curCookieVal = '';};
	var wIds = curCookieVal.split(',');	
	var msg = '';		
	if(curCookieVal == ''){		
		$.cookie('theMillPlaylist', wId, {expires: 10000, path: '/'}); // create and set cookie
		msg = 'Content added. You currently have <strong>1</strong> item in your playlist.';
		updatePlaylistDivContent();
		fnFeedbackSlide(msg);
	} 
	else{				
		if(wIds.length >= 20){
			msg = 'You have reached the maximum number of playlist clips allowed. To add new content, please remove one from your playlist.';			
		}		
		else if($.inArray(wId, wIds) != -1){
			// feedback "already added"
			msg = 'Content is already added to your playlist. You currently have <strong>'+(wIds.length)+'</strong> items in your playlist.';			
		}
		else{			
			// add it to end
			$.cookie('theMillPlaylist',curCookieVal+","+wId, {expires: 10000, path: '/'});
			// feedback "added"
			msg = 'Content is added to your playlist. You currently have <strong>'+(wIds.length+1)+'</strong> items in your playlist.';			
		}		
				
		// reload the playlist div with new set of videos based on new cookie value
		updatePlaylistDivContent();
		fnFeedbackSlide(msg);
	}
	
	$('#feedBack').delay(2500).slideUp(600,"easeInOutQuad").removeClass('open');
}
function updatePlaylistDivContent() {
	
	// close the div, then clear out the content, then load it in
	if($('#ePlay.open').length > 0){
		$('#tPlaylist').click(); // close the div
	}
	
	// caching issue - add a random number to the querystring - unix timestamp as an integer will do.
	var time = Math.round(new Date().getTime() / 1000); 	
	
	url = $('#tPlaylist').attr('href').replace('#','?'+time+' #')+' > *'; // url with unix timestamp attached
	
	$('#ePlay').load(url, function(){	    
	  $('#ePlay').show(); // need to show it for the playlist slider to work correctly on ajax load (the wrapping div hides it)
		fnImageSwap($('#ePlay'));
	  fnPlaylistSlider();	
		fnTabs();		
		$('#ePlay').hide(); // hide it again
	});	
}

function fnRemoveFromPlaylist(wId) {
	var newCookieVal = $.cookie('theMillPlaylist-temp').replace(wId,'.').replace(',.','').replace('.,','');	
	$.cookie('theMillPlaylist-temp',newCookieVal, {path: '/'});	
	//fnFeedbackSlide("cookie = " +$.cookie('theMillPlaylist-temp'));
}

function fnFeedbackSlide(msg) {
	
	$('a.showPL').live('click',function(){
		$('#tPlaylist').click();
		return false;
	});
	
	//$('#feedBack a:first').html(msg);
	$('#feedBack p:first').html(msg);
	$('#tFeedback').click();
	
}

// configure sifr flash replacement
	// sifr 3
	/*sIFR.useStyleCheck = true;
	sIFR.activate();
	sIFR.replace(fsclerkLight, {selector: '.smlBlack', css: [ '.sIFR-root {leading: 6;}' ], wmode: "opaque"});	
	sIFR.replace(fsclerkLight, {selector: '#f h3', css: [ '.sIFR-root {color: #cecdcc;}'], wmode: "transparent" });	
	sIFR.replace(fsclerkLight, {selector: '#homeStrap,#strap', css:['.sIFR-root {color: #454544;leading:5;kerning:-2;font-weight:normal;}','.sIFR-root a{kerning:-2;color: #22AADC;text-decoration: none;}','.sIFR-root a:hover{ color: #22AADC; text-decoration: underline; kerning:-2; }'], wmode: "transparent" });	
*/


/*Preload images*/
$.fn.preloadImg = function() {
  var sExt = '.'+getExt($(this).attr('src'));
  var sCurSrc = $(this).attr('src');
  var img = new Image();
  img.src = sCurSrc.replace(sExt,'_hover'+sExt);
};
/* Swap image src attributes to add or remove '_hov' */
$.fn.swapImg = function() {
  var sExt = '.'+getExt($(this).attr('src'));
  var sCurSrc = $(this).attr('src');
  var sNewSrc;
  if (sCurSrc.indexOf('_hover'+sExt) != -1) {
    sNewSrc = sCurSrc.replace('_hover'+sExt,sExt);
  } else {
    sNewSrc = sCurSrc.replace(sExt,'_hover'+sExt);
  }
  $(this).attr('src',sNewSrc);
};
/*Find the extension of the supplied filename*/
function getExt(f) {
  var ext;
  var aF = f.split('.');
  if (aF.length > 1) {
    ext = aF[aF.length-1]; 
  }
  return ext;
}

/** jqEM to detect font size changes **/
//set the text size that the default body computes to
var fontSize = 13;

$.jqem.bind(function(a,b,c) {		
	fnResize();
});
function fnResize(){	
	if( $.jqem.current() == fontSize) {					
		$('body').addClass('enh').removeClass('def');
		enh=true;
	}else if($.jqem.current() != fontSize){		
		$('body').removeClass('enh').addClass('def');		
		enh=false;
	};
};

function fnHomeFlash() {
	
	// this is mostly for the rawhtml, will change once we get a proper flash movie in
	
	if($('#home #hero #imgHolder').length){
	
		var w,h; // width and height
		if(wide) {
			w = "1104";
			h = "429";	
			swfSize = 	"_lrg";
		}
		else{
			w = "942";
			h = "342";		
			swfSize = 	"";
		}
		var params = {wmode:"opaque"};
		var flashvars = {};
		var attributes = {};
		swfobject.embedSWF("/theMillAssets/flash/homeHero"+swfSize+".swf", "imgHolder", w, h, "9.0.0",null,flashvars,params,attributes);		
	}
	
}

// Pagination (e.g. work, news) ajax slider  
function fnPagerSlider() {
	
	if($('div.scroller').length>0){
		
		//$panelW = wide ? 1104 : 942; // width of panel
		//$panelW = $('div.scroller').width(); // width of panel - now calc'd dynamically so the page can resize (wide/normal layout - still needs a fix to re[pso)
		
		//TODO wide/normal layout - still needs a fix to reposition the scroller panel upon page resize		
		
		//FOR TESTING ONE INTANCE $('div.scroller:first').each(function() {
		$('div.scroller').each(function() {
					
			// **Some Vars				
			var	$scroller 		= $(this), // main scroller
					$panelHolder  = $('div.panelsHolder',$scroller),						
					$pager   			= $('div.pager ',$scroller), // pager wrapper			
					sId 					= $scroller.attr('id'), // for use in creating ids of panels later									
					sTargId 			= $scroller.attr('id')+'-panel-'+ (($panelHolder.attr('scrollLeft')/$('div.scroller').width())+1), // build an id from the parent div and number of panels (e.g. parentId-panel-1)			
					pages 				= $("div.count div.left em",$pager);	 // number of pages	
					
			// **Prepare			
			// add required html
			$scroller.wrapInner('<div class="panelsHolder cfx"><div class="panels cfx"></div></div>').prepend('<div class="screen"></div>');			
			// move the pager to the end of the $scroller (inside)				
			$scroller.append($pager); 
			// add panels		
			for (var i = pages.text(); i >= 2; i--){
				$('#'+sId+'-panel-1').after('<div class="panel" id="'+sId+'-panel-'+i+'"></div>');			
			};
			$('div.panels',$scroller).css('width',$('div.scroller').width() * pages.text());
		});		
		
			
		
		// fade in screen
		function screenIn($par) {	
			$scr = $('div.screen',$par);									
			$scr.fadeTo("slow", 0.90);
		}
		// fade out screen
		function screenOut($par) {
			$scr = $('div.screen',$par);
			$scr.fadeOut('slow');
		}		
		// slide for "next"
		function slideRTL($par, content) {			
			fnWidthCheck();
			
			// for the smaller pager at the top;
			if(content =='page'||'work'){
				var btns = $('div.pager:first .btns',$par).clone();
				$('.pagerSml .btns').replaceWith(btns);
			}
			
			$panelHolder = $('div.panelsHolder',$par);
			$panelHolder.delay('500').stop().animate({'scrollLeft': ($panelHolder.scrollLeft() + $('div.scroller').width())}, 800, 'easeInOutQuint', // slide the panel into view
				function(){ // callback
					updateTitle();
					
					if($('#azW').length >0){
						$panelHolder = $('#azW #az');
					}
					
					if(content=="work" && $('#searchWrk').length>0){
						$panelHolder = $('#searchWrk');
					}
					
					if(content=="news" && $('#searchOther').length>0){
						$panelHolder = $('#searchOther');
					}
					
					$panelHolder.scrollToTarg({duration:500}); // scrollTo the results//screenOut($par);
				}); 
		}		
		// slide for "prev"
		function slideLTR($par, content) {			
			fnWidthCheck();
			
			// for the smaller pager at the top;
			if(content =='page'||'work'){
				var btns = $('div.pager:first .btns',$par).clone();
				$('.pagerSml .btns').replaceWith(btns);
			}
			
			$panelHolder = $('div.panelsHolder',$par);
			$panelHolder.delay('500').stop().animate({'scrollLeft': ($panelHolder.scrollLeft() - $('div.scroller').width())}, 800, 'easeInOutQuint' , // slide the panel into view
				function(){ // callback					
					//screenOut($par);
					updateTitle();
					
					if($('#azW').length >0){
						$panelHolder = $('#azW #az');
					}
					
					if(content=="work" && $('#searchWrk').length>0){
						$panelHolder = $('#searchWrk');
					}
					
					if(content=="news" && $('#searchOther').length>0){
						$panelHolder = $('#searchOther');
					}
					
					$panelHolder.scrollToTarg({duration:500}); // scrollTo the results
				}); 
		}
		
		//check if already loadded
		function alreadyLoaded(_id,$wrap){						
			sId = $wrap.attr('id');
			if($('#' + sId +'-panel-'+_id+'>*').length == 0)
			{
				return false;
			}
			return true;
		}
		
		function returnNext(_path){
			//e.g. search-results.aspx?q=lorem&other_page=2				
			var nextPage = _path.split('page=');				
			return nextPage[1];
		}
		function returnType(_path){
			//e.g. search-results.aspx?q=lorem&other_page=2		
			var type = '';
			if(_path.indexOf('work_page') != -1){
				type = 'work';
			}
			else if(_path.indexOf('news_page') != -1){
				type = 'news';
			}
			else if(_path.indexOf('other_page') != -1){
				type = 'other';
			}
			else{
				type = 'page';
			}
			return type;
		}
		
		function updateTitle(){
			var $title = $('#searchWrk h2');
			if($title.length>0){
				var txt = $('#searchWrk .count .right').text();
				txt = txt.replace("showing", "Showing");
				string = txt.replace(/ /g,"+");
				bg = '<span style="background:#fff url(\'/umbraco/TigerLive.aspx?tid=10&amp;text='+string+'+Results\') 0 0 no-repeat;"></span>';
				
				$title.html(bg +"Work. "+ txt +" Results");
			}
		}
		
		
		$('div.pager a.next').live('click', function() {	
			
			var $par = $(this).parents('div.scroller');
			var $screen = $par.find('div.screen');
			var link = $(this).attr("href");
			var nextPage = returnNext(link);
			var content = returnType(link);
			var targ = '';
			var sId = $par.attr('id');
			
			if(content == 'news'){
				targ = ' #tNews';
			}else if(content == 'other'){
				targ = ' #tOther';
			}else if(content == 'work'){
				targ = ' #wrkLst';
			}
			
			//check if already loadded
			if(!alreadyLoaded(nextPage,$par)){			
				screenIn($par);
				$('#' + sId +'-panel-'+nextPage).load(link + ' #'+sId+'-panel-1>*', function(data){													
					$newPager = $(data).find('#'+sId+' div.pager');
					$('div.pager:first',$par).replaceWith($newPager);		
					screenOut($par);		
					slideRTL($par, content);

					
						
										
				});
	 		}
	 		else{	 			
	 			$('#' + sId +' div.pager').load(link + ' #'+sId+' div.pager>*', function(){
					slideRTL($par, content);
				});
				
				
				
								
 			}
			
			
					
			// find target url from href
			// if the page isnt loaded
				// find type of content from href & decide target div			
				// find parent scroller - parents('div.scroller')
				// screenIn
				// load target content div into parent scroller
				// load target pager div into parent pager
				// scrollRTL
				// screenOut
			// else
			 	// screenIn				
				// scrollRTL
				// screenOut			
				
			return false;
		});
		$('div.pager a.prev').live('click', function() {
			var $par = $(this).parents('div.scroller');
			var $screen = $par.find('div.screen');
			var link = $(this).attr("href");
			var nextPage = returnNext(link);
			var content = returnType(link);
			var targ = '';
			var sId = $par.attr('id');
						
			if(content == 'news'){
				targ = 'tNews';
			}else if(content == 'other'){
				targ = 'tOther';
			}else if(content == 'work'){
				targ = 'wrkLst';
			}else{
				targ = 'ajaxPager';
			}
		
			//check if already loadded
			if(!alreadyLoaded(nextPage,$par)){			
				screenIn($par);
				//$('#' + sId +'-panel-'+nextPage).load(link + ' #'+sId+'-panel-1'+targ+'>*', function(){								
				$('#' + sId +'-panel-'+nextPage).load(link + ' #'+sId+'-panel-1>*', function(data){													
					
					$newPager = $(data).find('#'+sId+' div.pager');		
					$('div.pager:first',$par).replaceWith($newPager);
					screenOut($par);
					slideLTR($par, content);										
					//screenOut($screen);
				});
	 		}
	 		else{
				//screenOut($screen);
				$('#' + sId +' div.pager').load(link + ' #'+sId+' div.pager>*', function(){
					slideLTR($par, content);
				});
									
 			}
					
			// find target url from href
			// if the page isnt loaded
				// find type of content from href & decide target div			
				// find parent scroller - parents('div.scroller')
				// screenIn
				// load target content div into parent scroller
				// load target pager div into parent pager
				// scrollRTL
				// screenOut
			// else
			 	// screenIn				
				// scrollRTL
				// screenOut			
				
			return false;
		});
		
		

		$('.titleWithPager a.next').live('click',function(){
			$('#wrkLst div.pager:first a.next').click();
			return false;
		});
		
		$('.titleWithPager a.prev').live('click',function(){
			$('#wrkLst div.pager:first a.prev').click();
			return false;
		});
		
		
		
		
	}// .scroller if length	
}


function fnEmailForm(){
	var button = '<li><a href="#" class="email hov">Email</a></li>';
	var close = '<a href="#" title="Close" class="close">Close</a>';
	
	$('.shareLinks ul').append(button);
	
	$('#emailForm').hide();
	
	$('.shareLinks a.email').click(function(){
		$.blockUI({css: {
		'background':'none',
		'border':'0',
		'top': '30%',
		'width': '570px',
		'left': '50%',
		'margin-left':'-275px',
		'cursor': 'default'
		}, overlayCSS:  { 
        backgroundColor: '#000', 
        opacity: 0.9 
    	},message:$('#emailForm') });
		
		$('.blockMsg').prepend(close);
		
		// Move the block message div into the .NET form so submission will work.
		if ($('#aspnetForm').length > 0) {
      $('#aspnetForm').append($('.blockMsg')); 
		}
		
		$('.blockOverlay, .close').click(function(){
      
      // Move the block message back to where it usually is (under <body>) so blockUI works when hiding it.
      if ($('#aspnetForm').length > 0) {
        $('body').append($('.blockMsg')); 
      }

    	$.unblockUI();
    	return false;
    });
        
        //todo submit form ajax?
       	
        return false;
	});
}

//global variables for the video player
var $smlLnk,$medLnk,$hdLnk,vidPath,imagePath,sml,med,hd;
function fnVideoPlayer(){
	var $holder = $('#vidHolder');
	
	if($holder.length >0){			
		//butons		
		$smlLnk = $('#vidSmlLnk');
		$medLnk = $('#vidMedLnk');
		$hdLnk  = $('#vidHDLnk');	
		
		if(fnDetectMobile() == true){		
			//remove the buttons
			
			$smlLnk.remove();
			$medLnk.remove();
			$hdLnk.remove();
			//add play button overlay
			
			$playBtn = '<span class="play"></span>';
			$('#vid a').append($playBtn);
			$('#vid a span.play').click(function() {
				$(this).parents('a').click();
			});
			
			return false; // stop here, nothing else is required
		}else{
			
					
			//small
			sml = getWidthAndHeightFromURL($smlLnk.attr('href'));
			//medium
			med = getWidthAndHeightFromURL($medLnk.attr('href'));
			//hidef
			hd  = getWidthAndHeightFromURL($hdLnk.attr('href'));
			
			vidPath = $smlLnk.attr('href');
			imagePath = $('#vidHolder img:first').attr('src');
			if (imagePath == null) imagePath = '';  // work around JS error if no image		
			launchVidInPage();
			
			$hdLnk.click(function(){			
				// just to fullscreen - fFullScreen() on flash
				var vid = $(this).attr('href');			
				var img = escape(getResizedVideoImageURL(imagePath, hd.w ,"_hd", hd.h));
				//launchVidOverlay(hd.w,hd.h,vid,img,"true"); // pass in fullscreen parameter "true" to trigger fullscreen button in flash (still requires user interaction - Sandbox security)
				launchVidInPage($('#vidHolder'),vid,"false","true"); // pass in fullscreen parameter "true" to trigger fullscreen button in flash (still requires user interaction - Sandbox security)
				
				return false;
				/*
					
				if($(window).width()< 1255){
					return true;
				}else{
					var vid = $(this).attr('href');
					var img = getResizedVideoImageURL(imagePath, hd.w ,"_hd");
					launchVidOverlay(hd.w,hd.h,vid,img);
					return false;
				}			
				*/
			});
			
			if(wide){
				
				$('#smlMedHiDef a').removeClass('selected').filter('#vidMedLnk').addClass('selected').css({cursor:"default"});
				
				$smlLnk.click(function(){
					var vid = $(this).attr('href');
					var img = escape(getResizedVideoImageURL(imagePath, sml.w ,"_med", sml.h));
					launchVidOverlay(sml.w,sml.h,vid,img);
					return false;
				});
				
				$medLnk.click(function(){
					//should be in page?
					return false;
				});
			}else{
				
				$('#smlMedHiDef a').removeClass('selected').filter('#vidSmlLnk').addClass('selected').css({cursor:"default"});
				
				$smlLnk.click(function(){
					//should be in page?
					return false;
				});
				
				$medLnk.click(function(){
					var vid = $(this).attr('href');
					var img = escape(getResizedVideoImageURL(imagePath, med.w ,"_lrg", med.h));
					launchVidOverlay(med.w,med.h,vid,img);
					return false;
				});
			}
		}// else not mobile	
	}
}

function getWidthAndHeightFromURL(url) {
  if (url != null) {
    // Fallback values.
    var w = 480;
    var h = 270;
    var img = '';
    var vid = '';
    var mp4 = '';
    var link = url.split('?')[0];		
    // Extract width and height querystring from the URL.
    if (url != null) {
      var querystring = url.substr(url.indexOf('?') + 1);
      var params = querystring.split('&');
      for (i in params) {
        var name = params[i].split('=')[0];
        var value = params[i].split('=')[1];        
        if (name == 'width') w = value;
        if (name == 'height') h = value;
        if (name == 'image') img = value;
        if (name == 'vid') mp4 = value;
        if (name == 'url') url = value;
      }
    }	
    return {"h":h, "w":w, "img":img, "mp4":mp4, "vid":vid, "link":link, "url":url};	
	}
}


function launchVidInPage($targ,video,autoplay,fullScreen){
	
	var $holder = $targ != null ? $targ : $('#vidHolder');
	
	if($holder.length >0){	
	
    var fW = 0;
    var fH = 0;
    
    if(fullScreen){
			goFullScreen = fullScreen;
		}else{
			goFullScreen = "false";
		}
		
		if(autoplay){
			autoplay = autoplay;
		}else{
			autoplay = "true";
		}
    
    if (!wide && sml) {
      fW = sml.w;
      fH = sml.h;
      vidPath = $smlLnk.attr('href');
      imagePath = getResizedVideoImageURL(imagePath, fW ,"_med", fH); // include height to ensure image fills whole of flash
		}
		
		if(wide && med){
			fW = med.w;
			fH = med.h;
			vidPath = $medLnk.attr('href');
			imagePath = getResizedVideoImageURL(imagePath, fW ,"_lrg", fH);
		}
		if(video){
			vidPath = video;
		}
		if (fW > 0 && fH > 0) {
      var params = {wmode:"opaque", allowFullScreen: true, bgcolor:"000000"};  
      
    	var flashvars = {flv:escape(vidPath), nWidth:fW, nHeight:fH, image:escape(imagePath), autoplay:autoplay, goFullScreen:goFullScreen };
      var attributes = {};      
      //in-page player
      swfobject.embedSWF("/theMillAssets/flash/player.swf", "vid", fW, fH, "9.0.0", null,flashvars,params,attributes);
		}
	}
}

// Returns the URL to the correctly sized video player static image
// HEIGHT MIGHT BE UNDEFINED , if so then do not include in the image url
function getResizedVideoImageURL(imageURL, width, flatVer, height) {

  if (typeof(imageURL) != 'undefined') 
  {
  
    // If height specified (and its a resized image - has width param), add to image url
    if (typeof(height) != 'undefined' && imageURL.indexOf("width=") > 0) 
    {
      if(imageURL.indexOf("height=") > 0) 
      {								        
        // This is an image resized by Umbraco specifying width in the querystring. Replace that height with new one. 
        imageURL = imageURL.replace(/height=[0-9]+/, "height=" + height);		        
      }
      else 
      {
        // Add height to URL.
        imageURL += "&height=" + height;
      }
    }
  
    if(typeof(width) != 'undefined' && imageURL.indexOf("width=") > 0) 
    {								        
      // This is an image resized by Umbraco specifying width in the querystring. Replace that width with new one.
      imageURL = imageURL.replace(/width=[0-9]+/, "width=" + width);		        
    }
    else // flat build only
    {
      imageURL = imageURL.replace(/_lrg|_med/i, flatVer);
    }
  }

  return imageURL;

}

function launchVidOverlay(w,h,flv,img,fullScreen,autoplay){	
	
	//goFullScreen = fullScreen ? "true" : "false";
	
	if(fullScreen){
		goFullScreen = fullScreen;
	}else{
		goFullScreen = "false";
	}
	
	if(autoplay){
		autoplay = autoplay;
	}else{
		autoplay = "true";
	}
	
	var close = '<a href="#" title="Close" class="close">Close</a>';
	var params = {wmode:"opaque", allowFullScreen: "true", bgcolor:"000000"};
	var flashvars = {};
	var attributes = {};		
	flashvars.flv = flv;
	flashvars.nWidth = w;
	flashvars.nHeight = h;
	flashvars.image = img;	
	flashvars.autoplay = autoplay;	
	flashvars.goFullScreen = goFullScreen;	
	$.blockUI({
		css: {
			'background':'none',
			'border':'0',
			'top': '50%',
			'margin-top':'-'+(h/2)+'px',
			'width': w+'px',
			'height': h +'px',
			'left': '50%',
			'margin-left':'-'+(w/2)+'px',
			'cursor': 'default'
			},
		overlayCSS: { 
			backgroundColor: '#000',
			opacity: 1
			},
		message: close + '<div id="overlayVid">Video should be here?</div>'
	});	
	//$('body').css({'overflow':'hidden'});
	$('#vidHolder').html('');	
	swfobject.embedSWF("/theMillAssets/flash/player.swf", "overlayVid", w, h, "9.0.0",null,flashvars,params,attributes);
	
	function unBlock(){
		$.unblockUI();
		$('#vidHolder').html('<div id="vid"></div>');
		$('body').removeAttr('style');		
		launchVidInPage();		
	}	
	$('.blockOverlay, .close').click(function(){
		unBlock();
		return false;
	});	
	$(document).keyup(function(e) {
	  if (e.keyCode == 27) { 
	  		unBlock();
	  	 }  
	});
}



function fnSubNav(){
	if($('#subNav').length >0){		
		//hijack the links
		$('#subNav a').click(function(){			
			var $link = $(this);
			var content = $(this).attr('href'); 
			//content += ' #content';
			var h = $('.rightCol').height();			
			$('rightCol').html('').css('height',h).addClass('loading');			
			/* */
			//use the get method of returning content
			$.get(content,{},function(res, status){
				if ( status == "success" || status == "notmodified" ){
					//strip javascript and conditional comments
					var data =  $("<div/>").append(res.replace(/<script(.|\s)*?\/script>/g, "").replace("/<!--\[if.*?(?=-->)-->/g","")).find('.rightCol').html();					
					$('.rightCol').html(data);					
					$('.rightCol').removeClass('loading').removeAttr("style");					
					//TODO: any js functions that need to run again here one function or multiples?
					fnImageSwap();
					fnTabs();
					fnSectShowHide();
					fnNewsList();
					fnWhoWeAre();
					fnPagerSlider();
					fnPeopleList();
					//					
					// make the link selected
					$('#subNav a').removeClass('sel');
					$link.addClass('sel');					
				}
			});
			/* */ 				
			/* 
			$('.rightCol').load(content, function() {
				$('#content').removeClass('loading').removeAttr("style");
				//make the tabs function				
				$('#subNav a').removeClass('sel');
				$link.addClass('sel');				
			});
			 */			
			return false;
		});
	}
}



function fnInputTxtSwitch() {
	var txt;
	$('#ePlayShare input.txt')
		.focus(function() {						
			if($(this).val() != $(this).attr('value')){
				txt = $(this).val();
			}			
			if($(this).val()){
				$(this).val("");
			}			
		})
		.blur(function() {
			if((txt == $(this).val()) || ($(this).val()=='')){
				$(this).val(txt);				
			}
		});
}

var $slides, $controls, slideC, slideW, interval, count = 1;

function fnResetSlides(){
	$('#slides').scrollLeft(0);
}

function fnHomeSlide(){
	
	count = 1;
	
	playPause = '<div class="playPause"><a href="#" class="pause">Pause</a></div>';
	
	if ($('#slideCont .playPause').length == 0){
		$('#slideCont .inr ul').after(playPause);
		
		$('#slideCont a.pause').live('click', function() {
			fnHomeSlidePause();
			return false;
		});
		
		$('#slideCont a.play').live('click', function() {
			fnHomeSlidePlay();
			return false;
		});
		
	}
	
	$slides = $('#slides .slide');
	$controls = $('#slideCont .inr');
	slideC = $slides.length;
	slideW = $slides.width();
	
	
	//$('h4', $controls).html($('#slide-1 h4').html());
	$('ul li a', $controls).removeClass('sel').filter(':first').addClass('sel');
	
	//reset the slides position (again?)
	fnResetSlides();
	
	$('#slides').addClass('car').find('.slideWrap').width(slideC*slideW+"px");
	$('#slides .slide').removeClass('hide');
	
	
	$('#slideCont ul li a').unbind('click').click(function(obj){
		
		var num = $(this).text();
		var amt = (num-1) * slideW;
		var txt = $('#slide-'+num+' h4').html();
		count = num-1;
		
		//if the slideshow is playing and this is an original click (not a simulated one)
		if($('#slideCont a.pause').length>0 && obj.originalEvent){
			//$('#slideCont a.pause').click();
		}
		
		$('ul li a',$controls).removeClass('sel').filter($(this)).addClass('sel');
		//$('h4', $controls).html(txt);
		
				
		$('#slides').animate({scrollLeft: amt}, 800,"easeInOutQuint");
		
		return false;
	});
	
	
	$(window).load(function(){
		
		fnHomeSlidePlay();
	});
	
}

function fnClickSlide(){
	
	$list = $('#slideCont .inr ul');
	
	$list.find('li:eq('+count+') a').click();
	
	if(count>=($list.find('li').length -1)){
		count = 0;
	}else{
		count++;
	}
}

function fnHomeSlidePlay(){
	
	var seconds = 5;
	
	window.clearInterval(interval);
	$('.playPause a').removeClass('play').addClass('pause').text('Pause');
	interval = window.setInterval( "fnClickSlide()", seconds*1000 );
	
}

function fnHomeSlidePause(){
	$('#slides').stop(true, true);
	window.clearInterval(interval);
	$('.playPause a').removeClass('pause').addClass('play').text('Play');
	
}



function fnHomeSlideStop(){

	window.clearInterval(interval);
	$('#slides').stop(true, true);
	//do this again in half a second as it sometimes goes to the wrong position.
	setTimeout('fnResetSlides()', 500);
	fnResetSlides();
	$('.playPause a').removeClass('pause').addClass('play').text('Play');
	fnHomeSlide();
}

function fnNewsList(){
	if($('.newsList').length > 0){
		var x = 3;
		if($('body').hasClass('wide')){
			x = 4;
		}
		
		$('.newsList .sect ul li').removeClass('first');
		
		$('.newsList .sect ul li:nth-child('+x+'n+1)').addClass('first');

		
	}
}

function fnShowreelsList(){
	if($('.srList').length > 0){
		var x = 4;
		if($('body').hasClass('wide')){
			x = 5;
		}
		$('.srList .sect ul li').removeClass('first last');
		$('.srList .sect ul li:nth-child('+x+'n+1)').addClass('first');
		$('.srList .sect ul li:nth-child('+x+'n)').addClass('last');
		
	}
}


