/*-----------------------------------------------------
Site Specific
-------------------------------------------------------*/

// Check to see if the user is an iPhone user with naughty user agent sniffing, and a bit of method detection
_iphone = ( ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) && typeof window.orientation != 'undefined' ) ? true : false;

// Disable sIFR for IE / Firefox 2 / Safari 2, as it's causing layout issues
var _safari2 = ($.browser.safari && parseInt($.browser.version) < 500) ? true : false;
var _firefox2 = ($.browser.mozilla && parseFloat($.browser.version) < 1.9) ? true : false;

if(!$.browser.msie && !_firefox2 && !_safari2 ) {

	var helvetica = { src: '/media/site/fonts/helveticastbold.swf' };

	sIFR.activate(helvetica);
	
	/* Ignore the homepage with the if statement */
	sIFR.replace(helvetica, {
		selector: 'h1.sifr',
		offsetTop: 1,
		wmode: 'transparent',
		css: [
		    '.sIFR-root { letter-spacing: -1; leading: -7; }'
		]
	});

}

// Add a class of 'js' to the html element for styling hook
$('html').addClass('js');

// Document load
jQuery(function(){
	
	Shadowbox.init({
		skipSetup: true
	});
	
	// EXTERNAL SITE LINKS //////////////////////////////////////////
	/////////////////////////////////////////////////////////////////
	$('a.external, body#credits #helpers a').attr('target', '_blank');
	
	// HOME DROP DOWN DOCUMENTARY LINK
	/////////////////////////////////////////////////////////////////
	setTimeout(
		function(){
			$('#video-docu').animate({
				top: 0
			}, 500);
		},
		
		5000 // 5 seconds
	);

	// HOME (VIDEO) PAGE ////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////
	if( $('body').attr('id') == 'home' && $('#content').hasClass('video') && typeof(_speakers) != 'undefined' && _speakers.length != 0 ){
		
		$('#home #content.video .column.col1 div.intro').after('<div id="video-filter"></div>');
		
		
		// Set homepage video to play from one random speaker
		if( typeof _speakers != 'undefined' && !_iphone ){
			
			var totalSpeakers = _speakers.length;
			
			/* Get a random speaker */
			var randSpeaker = _speakers[Math.floor( Math.random() * totalSpeakers )];
			
			/* Add a wrapper around the video player */
			$('#homepage-player').wrap('<div id="homepage-player-wrapper"></div>');
			
			/* Embed flash player */
			var flashVars = { speakerName: randSpeaker.videoUrl, skinPath: "/media/video/skin.swf", posterframeURL: randSpeaker.posterframe };

			var params = { allowfullscreen: true };
			
			var attributes = { id: "homepage-player" };
			
			swfobject.embedSWF("/media/video/HomeHowiesPlayerApplication.swf", "homepage-player", "432", "278", "9.0.115", "/media/video/expressInstall.swf", flashVars, params, attributes );
			
			/* Add link to for linking through to speakers page */
			$('#homepage-player-wrapper').append('<a href="#" id="speaker-pagelink"></a><div id="speaker-embed"><span id="speaker-embed-handle">Share this video on your website</span> <span id="speaker-embed-wrap"><input type="text" id="speaker-embed-input" value="" /></span></div>');
			$('#homepage-player-wrapper').append('');
			
			// Add the slide down handler
			$('#speaker-embed-handle').bind('click', function(){
				$('#speaker-embed-wrap').slideToggle('fast', function(){
				});
			});
			
			// Initally hide the embed code in case the random speaker has embedded disabled, and this will prevent a flash of content
			$('#speaker-embed').hide();
			
			/* Set the video title - above the video */
			setVideoTitle(randSpeaker.speakerName);
			setVideoSpeakerLink(randSpeaker.speakerName, randSpeaker.speakerUrl);
			setVideoEmbed(randSpeaker.ref);
		}
		
		// Speaker dropdown
		(function(){
		
			var listItems = '';
			
			for(var i = 0; i < _speakers.length; i++){
				
				listItems += '<li class="'+_speakers[i]['ref']+'"><a href="#"><span>'+_speakers[i]['speakerName']+'</span> '+_speakers[i]['lectureTitle']+'</a></li>';
			}
				
			$('#video-filter').append('<div id="speaker-dropdown" class="js-dropdown"><h2>Choose a speaker</h2><ul>'+listItems+'</ul></div>');
			
			var target = '#speaker-dropdown';
			
			$(target).find('ul').hide();
						
			$(target).find('h2').toggle(
				function(){
					$(this).siblings('ul').slideDown();
				},
				function(){
					$(this).siblings('ul').slideUp();
				}
			);
			
			$(target).find('li a').bind('click', function(){
				var targetClass = $(this).parent('li').attr('class');
				
				highlightSpeakers( Array( targetClass ) );
				
				$(target).find('h2').trigger('click');
				return false;
			});
								
		})();
		
		// Theme dropdown
		(function(){
			
			var themes = new Array();
			
			for(var i = 0; i < _speakers.length; i++){
				
				/* Reference the speakers allocated themes */
				var sThemes = _speakers[i].themes;
				
				/* If the speaker has allocated themes, loop through them and if one doesn't
				   appear in the 'themes' array created at the start of the script, add it to it. */
				if( sThemes.length != 0 ){
					
					for(var x = 0; x < sThemes.length; x++){
						if( !inArray(themes, sThemes[x]) ){
							themes.push(sThemes[x]);
						}
					}
					
				}
								
			}
			
			/* If we have some themes from the speakers object, lets create the theme drop-down :) */
			if( themes.length != 0 ){
				var listItems = '';
				
				/* Create our list of themes and add it to the page */
				for(var i = 0; i < themes.length; i++){
					listItems += '<li class="'+themes[i].toLowerCase()+'"><a href="#">'+themes[i]+'</a></li>';
				}
				
				$('#video-filter').append('<div id="theme-dropdown" class="js-dropdown"><h2>Choose a theme</h2><ul>'+listItems+'</ul></div>');
				
				/* Get theme drop down, set the initial visibility, and then set the event handler to slide it up and down */				
				var target = '#theme-dropdown';
				
				$(target).find('ul').hide();
							
				$(target).find('h2').toggle(
					function(){
						$(this).siblings('ul').slideDown();
					},
					function(){
						$(this).siblings('ul').slideUp();
					}
				);
				
				/* Set event handler for the theme anchors */
				$(target).find('li a').bind('click', function(){
					var targetClass = $(this).parent('li').attr('class');
					
					var speakers = new Array();
					
					for(var i = 0; i < _speakers.length; i++){
						if( $.inArray( targetClass, _speakers[i]['themes'] ) != -1 )
							speakers.push(_speakers[i]['ref']);
					}
					
					highlightSpeakers( speakers );
					
					$(target).find('h2').trigger('click');
					
					return false;
				});
			}
	
		})();
		
		// Most popular
		(function(){
			
			if(typeof(_mostPopular) != 'undefined'){
				
				$('#video-filter').append('<a href="#" id="most-popular">Show most watched</a>');	
				
				$('#most-popular').click(function(){
					
					highlightSpeakers( new Array( _mostPopular ) );
					
					return false;
				});
			}
			
		})();
		
		function highlightSpeakers(speakers){
			
			var allSpeakers = new Array();
			
			$('#speaker-dropdown li').each(function(){
				allSpeakers.push($(this).attr('class'));
			});
			
			for( var i = 0; i < allSpeakers.length; i++ ){
				$('.video #'+allSpeakers[i] ).parent('div.video').css('z-index', 1+i);
			}
			
			if(speakers.length > 0){
				for( var i = 0; i < speakers.length; i++ ){
					$('.video #'+speakers[i] ).parent('div.video').css('z-index', 101+i);
				}				
			}
			
			
			$('#videos-wrapper #overlay:hidden').show().css({'z-index': '100', 'opacity': '0', 'height': $('#videos-wrapper').height()}).fadeTo('fast', 0.8);
			
			
			if( $('#speaker-reset').length == 0 ){
				$('#home #content.video #video-filter').append('<a href="#" id="speaker-reset">Show all speakers</a>');
				
				$('a#speaker-reset').click(function(){
					speakerReset();
					return false;
				});
			}
		}
		
		function speakerReset(){
			$('#videos-wrapper #overlay').fadeTo('fast', 0, function(){
				$(this).css({'z-index': '0'}).hide();
			});
			$('#speaker-reset').remove();
		}
		
		// Video swapping	
		(function(){
			
			$('#videos-wrapper').append('<div id="overlay"></div>');
			
			$('#overlay').hide();
			
			$('.video-wrapper').each(function(){
				// Set background image to that of default image
				$(this).css('background-image', 'url("'+$(this).find('img').attr('src')+'")');
				$(this).css('background-position', 'top left');
				$(this).css('background-repeat', 'no-repeat');
				
				var content = $(this).find('img').attr('title');
				content = content.split(':');
				
				// Replace the default image with a div of the same id
				// We'll use this div for the swfobject replacement
				$(this).find('a').replaceWith('<div class="controller"></div><div class="desc"><span>'+content[0]+'</span>'+content[1]+'</div>');
				
				$(this).find('div.desc').hide();
			});
			
			var controllers = $('.video-wrapper .controller');
			
			controllers.mouseover(function(){				
				$(this).parent().find('div.desc:hidden').slideDown(200);
			});
			
			controllers.mouseout(function(){
				$(this).parent().find('div.desc:visible').slideUp(200, function(){
					$(this).hide();
				});
			});
			
			/* When clicked, load speakers video into the homepage player, update the title, and the link to the speakers page.
			 * If the user is on an iPhone, simply link through to the speakers page
			 */ 
			controllers.click(function(){
				var speaker = getSpeakerDetails( $(this).parent().attr('id') );
				
				if( speaker ){
					if(!_iphone){					
						setVideoTitle( speaker.speakerName );
						setVideoSpeakerLink(speaker.speakerName, speaker.speakerUrl);
						setVideo( speaker.videoUrl, speaker.posterframe );
						setVideoEmbed(speaker.ref);
					} else {
						window.location = speaker.speakerUrl;
					}
				}
			});
	
		})();
	}
	

	// DROP DOWN SELECTORS //////////////////////////////////////////
	/////////////////////////////////////////////////////////////////
	// Note: HIDE FROM SAFARI 2 AS IT HAS ISSUES MAN!
	
	if($('form.dropdown-select').length > 0 && !_safari2){
		
		$('form.dropdown-select').each(function(){
			
			// Dropdown requires the form to have an id in order to work
			if($(this).attr('id')) {
				
				var selOptions = $(this).find('select option');
				
				if(selOptions.length > 0) {
					var dropdownOptions = '';
					
					selOptions.each(function(){
						dropdownOptions += '<li><a href="'+$(this).val()+'">'+$(this).html()+'</a></li>';
					});
					
					var dropdown = '<div class="js-dropdown" id="'+$(this).attr('id')+'"><span>'+$(this).find('label[for="dropdown-select"]').html()+'</span><ul>'+dropdownOptions+'</ul></div>';
					
					$(this).replaceWith(dropdown);
					
					var target = '#'+$(this).attr('id');
					
					$(target).find('ul').hide();
								
					$(target).find('span').toggle(
						function(){
							$(this).siblings('ul').slideDown();
						},
						function(){
							$(this).siblings('ul').slideUp();
						}
					);
					
					// Close dropdown after anchor click
					/*
					$(target).find('a').bind('click', function(){
						$(target).find('span').trigger('click');
					});
					*/
					
				}
			
			}
		});
			
	}
	
	// MAILTO LINKS /////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////
	$('a.mailto').each(function(){
		var text = $(this).text();
		
		var href = $(this).attr('href');
		$(this).attr('href', href.replace(/\[at\]/i, '@'));
		
		// Due to an IE bug which replaces the contents of the anchor
		// if the href is updated to contain the '@' symbol, we replace
		// the text AFTER the 'href' has been updated
		$(this).text(text.replace(/\[at\]/i, '@'));
	});
	
	
	// AJAX FUNCTIONS ///////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////
	_ajaxFlag = false;
	
	// Global AJAX settings
	$.ajaxSetup({
		beforeSend: function(){
			// Set a flag to indicate a ajax call is being made, useful for not making conflicting calls
			_ajaxFlag = true;
		},
	  	success: function(){
	  		_ajaxFlag = false;
	  	}
	});
	
	function clearAjaxLoading(target){
		if(typeof target == 'undefined') target = '';
		
		// Clear the loading overlay timer
		clearTimeout(ajaxTimer);
					
		// Remove just in case they've been added by the timeout
		$(target+' #ajax-loading-overlay, '+target+' #ajax-loading').remove();		
	}
	
	function setAjaxLoading(target){
		// Set global variable of ajaxTimer
		ajaxTimer = setTimeout(function(){
			$(target).append('<div id="ajax-loading-overlay"></div><img src="/media/site/images/front-end/branding/ajax-loading.gif" width="32" height="32" id="ajax-loading" alt="loading..." />');
			$(target+' #ajax-loading-overlay').width($(target).width());
			$(target+' #ajax-loading-overlay').height($(target).height());
		}, 500);	
	}
	
	
	// ATTENDEE PAGE ////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////
	if($('body').attr('id') == 'attendees'){
		
		GMapsInitialize();
		
		// Add and alt class on every 3rd item for styling
		var i = 2;
		while(i < 75) {
			$('#attendee-select.js-dropdown ul li:eq('+i+')').addClass('alt');
			i += 3;
		}
		
		// Set the form's default values into an array;
		formDefaultValues = new Array();
		formDefaultValues['contact-email'] = $('#contact-form #contact-email').val();
		formDefaultValues['contact-message'] = $('#contact-form #contact-message').val();
		
		function assignEvHandlers(){
			
			formInputs = new Array('contact-email', 'contact-message');
			
			for(var i=0; i < formInputs.length; i++){
				
				// Self executing anonymous function to induce scope
				(function(){
					// Remember value within this scope
					var x = i;
					
					$('#contact-form #'+formInputs[x]).focus(function(){
						if($(this).val() == formDefaultValues[formInputs[x]])
							$(this).val('');
					});
					
					$('#contact-form #'+formInputs[x]).blur(function(){
						if($(this).val() == '')
							$(this).val(formDefaultValues[formInputs[x]]);
					});
				})();
				
			}
						
			$('#contact-form').submit(function(){
				// Check to see if another ajax call is in process, if it's not let's rock...
				if(!_ajaxFlag){
				
					var args = {
						frm_useremail: $(this).find('#contact-email').val(),
						frm_usermessage: $(this).find('#contact-message').val(),
						ajax_cmd: 'ajx_att_form'
					};
				
					var url = window.location+'/Ajax/';
					
					$.ajax({
						type: 'POST',
						url: url,
						data: args,
						dataType: 'json',
						cache: false,
						beforeSend: function(){
							setAjaxLoading('#attendee-details');
						},
						success: function(data){
							clearAjaxLoading('#attendee-details');
													
							// Update html
							$('#contact-form').replaceWith(data.html);
												
							assignEvHandlers();
						},
						complete: function(){
							// Run this again, just in case :)
							clearAjaxLoading('#attendee-details');
						},
						error: function(){
							clearAjaxLoading('#attendee-details');
							
							$('#contact-form').replaceWith('<p class="error">Sorry. An error has occured retrieving your form submission from the server. Please refresh the page and try again.</p>');
						}
					});
					
				}
				
				return false;
			});
		}
		
		assignEvHandlers();
	}
	
	
	// SPEAKER PAGE /////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////
	if($('body').attr('id') == 'speaker' || $('body').attr('id') == 'speaker-archive'){
		
		// Handle showing and hiding of comment form
		if( !_safari2 )
		{
			// Use for css class switch to change background image
			$('#postcomment-title').addClass('js-form');
		
			$('#comment-form').hide();
			
				$('#postcomment-title').toggle(
				function(){
					$('#comment-form').slideDown();
				},
				
				function(){
					$('#comment-form').slideUp();
				}
			);
		}
		
		// Set the form's default values into an array;
		formDefaultValues = new Array();
		formDefaultValues['comment-name'] = $('#comment-form #comment-name').val();
		formDefaultValues['comment-email'] = $('#comment-form #comment-email').val();
		formDefaultValues['comment-message'] = $('#comment-form #comment-message').val();
		formDefaultValues['comment-captcha'] = $('#comment-form #comment-captcha').val();
		formDefaultValues['sendfriend-yourname'] = $('#sendfriend-form #sendfriend-yourname').val();
		formDefaultValues['sendfriend-youremail'] = $('#sendfriend-form #sendfriend-youremail').val();
		formDefaultValues['sendfriend-friendname'] = $('#sendfriend-form #sendfriend-friendname').val();
		formDefaultValues['sendfriend-friendemail'] = $('#sendfriend-form #sendfriend-friendemail').val();
		
		function assignEventHandlers(){
			
			formInputs = new Array(
				'comment-name', 
				'comment-email', 
				'comment-message', 
				'comment-captcha', 
				'sendfriend-yourname', 
				//'sendfriend-youremail', 
				'sendfriend-friendname', 
				'sendfriend-friendemail'
			);
			
			for(var i=0; i < formInputs.length; i++){
				
				// Self executing anonymous function to induce scope
				(function(){
					// Remember value within this scope
					var x = i;

					$('#'+formInputs[x]).focus(function(){
						if($(this).val() == formDefaultValues[formInputs[x]])
							$(this).val('');
					});
					
					$('#'+formInputs[x]).blur(function(){
						if($(this).val() == '')
							$(this).val(formDefaultValues[formInputs[x]]);
					});
				})();
				
			}
			
			// ADD COMMENT FORM
			$('#comment-form').submit(function(){
				// Check to see if another ajax call is in process, if it's not let's rock...
				if(!_ajaxFlag){
				
					var args = {
						frm_username: $(this).find('#comment-name').val(),
						frm_useremail: $(this).find('#comment-email').val(),
						frm_comment: $(this).find('#comment-message').val(),
						frm_captcha: $(this).find('#comment-captcha').val(),
						ajax_cmd: $(this).find('input[name="ajax_cmd"]').val()
					};
									
					var url = window.location+'/Ajax/';
					
					$.ajax({
						type: 'POST',
						url: url,
						data: args,
						dataType: 'json',
						cache: false,
						beforeSend: function(){
							setAjaxLoading('#comment-form');
						},
						success: function(data){
							clearAjaxLoading('#comment-form');
							
							switch(data.code){
								
								// Comment form has errors
								case 0:
									$('#comment-form').replaceWith(data.form);
								break;
								
								// Comment contains naughty words, submit and show comments as normal
								case 1:								
									$('#comments').replaceWith(data.comments);
																
									$.scrollTo($('#comments-title'), 500);
									
									$('#postcomment-title').remove();
									
									$('#comment-form').replaceWith('<p>'+data.status+'</p>');
									break;
								break;
								
								// Everything ok, post nice new post and highlight it
								case 2:								
									$('#comments').replaceWith(data.comments);
									
									$('#comments').children('div:first-child').hide();
									
									$.scrollTo($('#comments-title'), 500);
									
									$('#comments').children('div:first-child').effect('highlight', { color: '#000000' }, 3000);
									
									$('#postcomment-title').remove();
									
									$('#comment-form').replaceWith('<p>'+data.status+'</p>');
									
									break;
							}
							
							assignEventHandlers();
						
						},
						
						complete: function(){
							// Run this again, just in case :)
							clearAjaxLoading('#comment-form');
						},
						
						error: function(){
							clearAjaxLoading('#comment-form');
							
							$('#comment-form').replaceWith('<p>Sorry. An error has occured retrieving your form submission from the server. Please refresh the page and try again.</p>');
						}
					});
				}
				
				return false;
			});
			
			// SEND TO A FRIEND FORM
			$('#sendfriend-form').submit(function(){
				// Check to see if another ajax call is in process, if it's not let's rock...
				if(!_ajaxFlag){
				
					var args = {
						frm_yourname: $(this).find('#sendfriend-yourname').val(),
						//frm_youremail: $(this).find('#sendfriend-youremail').val(),
						frm_friendname: $(this).find('#sendfriend-friendname').val(),
						frm_friendemail: $(this).find('#sendfriend-friendemail').val(),
						ajax_cmd: $(this).find('input[name="ajax_cmd"]').val()
					};
									
					var url = window.location+'/Ajax/';
					
					$.ajax({
						type: 'POST',
						url: url,
						data: args,
						dataType: 'json',
						cache: false,
						beforeSend: function(){
							setAjaxLoading('#sendfriend-form');
						},
						success: function(data){
							clearAjaxLoading('#sendfriend-form');
							
							$('#speaker-email').replaceWith(data.form);
							
							assignEventHandlers();
						
						},						
						complete: function(){
							// Run this again, just in case :)
							clearAjaxLoading('#sendfriend-form');
						},
						error: function(){
							clearAjaxLoading('#sendfriend-form');
							
							$('#sendfriend-form').replaceWith('<p>Sorry. An error has occured retrieving your form submission from the server. Please refresh the page and try again.</p>');
						}
					});
				}
				
				return false;
			});

			
			
			// Pagnation AJAX handler
			$('#comment-pagnation ul li a').click(function(){
			
				// Check to see if another ajax call is in process, if it's not let's rock...
				if(!_ajaxFlag){
				
					var args = {
						page: $(this).attr('href').split('=')[1],
						ajax_cmd: 'ajx_get_comments'
					};
					
					var url = window.location+'/Ajax/';
					
					$.ajax({
						type: 'GET',
						url: url,
						data: args,
						dataType: 'json',
						cache: false,
						beforeSend: function(){
							setAjaxLoading('#comments');
						},
						success: function(data){
							clearAjaxLoading('#comments');
							
							$('#comments').replaceWith(data.comments);
							
							assignEventHandlers();
						},
						complete: function(){
							// Run this again, just in case :)
							clearAjaxLoading('#comments');
						},
						error: function(){
							clearAjaxLoading('#comments');						
						}
					
					});
				}
												
				return false;
			});
		}
		
		// Big Do, Little Do
		
		/*
		 * bigDo object set in the speaker header, contains boolean to control view and relevant HTML to inject
		 */
		if( typeof bigDo != 'undefined' && bigDo.show == true ){
			alert(bigDo.html);
			/* Inject the html for big do in the relevant place */
			$('#speaker-details h3').after(bigDo.html);
			
			$('#speaker-do a').bind(
				'click keypress',
				
				function(){
					// SWAP VIDEO
					return false;
				}
			);
		
		}
		
		assignEventHandlers();
		
	}
	
	// DONATE PAGE //////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////
	$('body#donate').each(function(){
		
		$('.donate-msg').each(function(){
					
			Shadowbox.open({
		        player:       'html',
		        content:      '<div id="'+$(this).attr('id')+'">' + $(this).html() + '</div>',
		        height:       200,
		        width:        350
		    });
		});
						
	});
	
	// SUBSCRIBE TO NEWSLETTER //////////////////////////////////////
	/////////////////////////////////////////////////////////////////	
	$('#nav-subscribe a').click(
		function(){
			
			// Check to see if somehow the user has managed to navigate their way to the newsletter-subscribe page
			// If they have cancel all ajax stuff
			var location = window.location.href;
			
			if( location.indexOf('newsletter-subscribe') > -1 ){
				return true;
			}
			
			// Otherwise...
			
			// Check to see if another ajax call is in process, if it's not let's rock...
			if(!_ajaxFlag){		
			    
			    // Set url to use
				var url = '/newsletter-subscribe/newsletter-subscribe-index/AjaxRequest';
			    
			    // Set some default arguments for the ajax calls
			    var defaultArgs = { 
			    	ajax_cmd: 'ajx_get_subscribe' 
			    }
			    
			    // Open shadowbox
			    Shadowbox.open({
			        player:  'html',
			        content:  '<div id="shadowbox_inner_content" class="subscribe">Loading...</div>',
			        height:   380,
			        width:    450,
			        options:  {
			        	onFinish: function(){
			        		// Make the ajax call once shadowbox has opened
			        		ajaxRequest(url, defaultArgs);
			        	},
			        	enableKeys: false
			        }
			    });
			    
			    var ajaxRequest = function(url, args){
			    	$.ajax({
						type: 'POST',
						url: url,
						data: args,
						dataType: 'json',
						cache: false,
						
						// Keep beforeSend and complete, do NOT remove as global ajax events do not fire
						beforeSend: function(){
						},
						
						complete: function(){
						},
						
						success: function(data){
							var content = $('#shadowbox_inner_content');
							
							content.html(data.output);
						
							$('#shadowbox_inner_content #subscribe-form').submit(function(){
						    	var name = $('#subscribe-name').val();
						    	var email = $('#subscribe-email').val();
						    	
						    	var args = jQuery.extend(defaultArgs, {
						    		name:     name,
									email:    email,
									validate: true
						    	});
								
								// Make ajax call to get updated html			
								ajaxRequest(url, args);
								
								return false;
							});							
						},
						
						error: function(){
							$('#shadowbox_inner_content').html('<p>Sorry, an error has occurred, please <a href="/newsletter-subscribe/">click here to use an alternative signup form.</a></p>')			
						}
					});
			    }
			    
			}
			
			return false;
		}
	);

});


// Externally viewable functions - for flash and others


/* Expects video-url style name passed i.e. paul_deegan */
function setVideo(speakerName, posterframeURL){
	// Get the flash player
	var hpPlayer = document.getElementById('homepage-player');
	
	// Set flash to play speakers video							
	if( hpPlayer ) hpPlayer.setVideo(speakerName, posterframeURL);
}

/* Expects normal name style passed i.e. Paul Deegan */
function setVideoTitle(speakerName){
	var title = $('#video-title');
	
	title.text(speakerName + "'s Do Lecture:");
}

/* Expects normal name style passed i.e. Paul Deegan, and full url */
function setVideoSpeakerLink(speakerName, url){
	var pageLink = $('#speaker-pagelink');
	pageLink.text('Read more about '+speakerName+'\'s Do Lecture');
	pageLink.attr('href', url);
}

/* Expects seo/url name passed i.e. paul-deegan */
function setVideoEmbed(speakerName){
	var embed = $('#speaker-embed');
	var embedInput = $('#speaker-embed-input');
	var embedWrap = $('#speaker-embed-wrap');
	
	var url = '/speakers/speakers-index/AjaxRequest';
	var args = { 
		ajax_cmd: 'ajx_speaker_embed_homepage',
		speaker: speakerName
	}
	
	embedWrap.hide();
	
	var timeOut;
		
	$.ajax({
		type: 'POST',
		url: url,
		data: args,
		dataType: 'json',
		
		beforeSend: function()
		{
			// Set a timeout incase data takes a while
			timeOut = setTimeout(function(){
				embedInput.val('Loading...');
			}, 100);
		},
		
		success: function(data)
		{
			clearTimeout(timeOut);
			
			// If speakers profile has embedded disabled, hide embed option
			if( data.embed == false )
			{
				embed.hide();
			}
			// Otherwise display it...
			else
			{
				embed.show();
				embedInput.val(data.embed);
			}
		},
		
		error: function(data)
		{
			embedInput.val('Error loading embed code');
		}
	});

}

/* Expects seo name style passed i.e. paul-deegan */
function getSpeakerDetails(target){
	var speakerDetails = new Array();
	
	for(var i = 0; i < _speakers.length; i++){
		if(_speakers[i]['ref'] == target){
			return _speakers[i];
		}
	}
	
	return false;
}

function inArray( arr, val ){
	for( var i=0; i < arr.length; i++ ){
		if( arr[i] == val ) return true;
	}
	
	return false;
}

/* Embed quicktime movie on speaker page for users viewing on an iPhone */
function iphoneVideoEmbed(videoSrc){
	jQuery(function(){
		var qtCode = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="396" width="704" id="speaker-video">';
		qtCode += '<param name="src" value="'+videoSrc+'">';
		qtCode += '<param name="autoplay" value="true">';
		qtCode += '<param name="type" value="video/quicktime" height="396" width="704">';
		qtCode += '<embed src="'+videoSrc+'" height="396" width="704" autoplay="true" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/">';
		qtCode += '</object>';
	
		$('#speaker-video').replaceWith(qtCode);	
	});
}