jQuery(document).ready(function($) {
	
	/***************************************************************************
	 * Global
	 */
	
	var BIG = window.BIG = window.BIG ? window.BIG : {};
	
	$('html').addClass('js');
	
	if($("#newsticker").length) {
		
		$().newsTicker({
			newsList:'#newsFader',
			tickerRate:30, 
			loopDelay:6000,
			startDelay: 10,
			placeHolder1:'_'
		});
		
		$("#newsticker").css({display:"block"});
	}
	
	// Setup style switcher
	(function() {
		
		var $_cookie_name = "contrast",
			$_cookie = $.cookie($_cookie_name),
			$_date = new Date(),
			$_selected = $_cookie;
		
		if ($_cookie) switchstyle($_cookie);
		
		$_date.setTime($_date.getTime() + 2419200000);//28 days
		
		$('#text-contrast a').bind("click", function(){
			var $_rel = $(this).attr("rel");
			switchstyle($_rel);
			return false;
		});
		
		function switchstyle($_style) {
			
			$('link[@rel*=style][title]').each(function(i) {
				this.disabled = true;
				if (this.getAttribute('title') != $_selected) {
					if (this.getAttribute('title') == $_style) this.disabled = false;
					$.cookie($_cookie_name, $_style, { expires : $_date });
					$_selected = $_style;
					$('#text-contrast a').children("img").attr("src", "img/text-contrast-reset.gif");
				} else {
					this.disabled = true;
					$.cookie($_cookie_name, null);
					$_selected = "";
					$('#text-contrast a').children("img").attr("src", "img/text-contrast-high.gif");
				 }
			});
		}
	})();
	
	$('.module .tabs').tabs();
	
	$('.date-pick').datepicker({showOn:'both', buttonImage:'img/calendar.gif', buttonImageOnly:true, dateFormat:'dd/mm/yy'});
	
	// Setup tooltips with explicit handles
	$('.has-tooltip').each(function(){
		
		var $trigger = $(this),
			$tooltip = $trigger.next('.tooltip'),
			timeoutId,
			delay = 500;
		
		$tooltip.addClass('js-tooltip').css('position', 'relative');
		
		if(!$.browser.msie) {
			$tooltip.css('opacity', 0);
		}
		
		$trigger.bind("mouseenter focus", function(){
			
			$trigger.css();
			
			timeoutId = setTimeout(function() {
				
				$tooltip.css({display:'block', cursor:'help'});
				
				if(!$.browser.msie) {
					$tooltip.animate({opacity: 1}, 300, 'swing');
				}
				
			}, delay);
			
		}).bind("mouseleave blur", function(){
			
			clearTimeout(timeoutId);
			
			if(!$.browser.msie) {
				$tooltip.animate({opacity: 0}, 100, 'linear', function(){$tooltip.css('display', 'none');});
			} else {
				$tooltip.css('display', 'none');
			}
			
		});
	});
	
	if($.browser.msie && parseInt($.browser.version) == 6) {
		$('*').each(function() {
			var $el = $(this), cssClassAttr = $el.attr('class');
			if(cssClassAttr && cssClassAttr.indexOf(' ') != -1) {
				var allCssClasses = cssClassAttr.split(' '), newAllCssClasses = allCssClasses.slice(0);
				while(allCssClasses.length > 1) {
					newAllCssClasses.push(allCssClasses.join('-'));
					allCssClasses.pop();
				}
				$el.attr('class', newAllCssClasses.join(' '));
			}
		});
	}
	
	// Create audio players
	(function() {
		
		var audioPlayers = [
			{
				id:'London1', // id of the <div> on the page (note must also have the "audio-player" class)
				xmlPath:'xml/player-london-podcast.xml', // Audio player settings xml (contains colours and mp3 file url)
				width:226, // Width of flash movie
				height:60 // Height of flash movie
			},
			{
				id:'London2',
				xmlPath:'xml/player-london-podcast-2.xml',
				width:226,
				height:60
			},
			{
				id:'se1',
				xmlPath:'xml/player-se-podcast-.xml',
				width:226,
				height:60
			},
			{
				id:'se2',
				xmlPath:'xml/player-se-podcast--2.xml',
				width:226,
				height:60
			}
		];
		
		for(var i = 0; i < audioPlayers.length; ++i) {
			
			var $container = $('#' + audioPlayers[i].id + '.audio-player');
			
			if(!$container.length) continue;
			
			swfobject.embedSWF(
				"swf/audioPlayer.swf",
				audioPlayers[i].id,
				audioPlayers[i].width,
				audioPlayers[i].height,
				'9.0.0',
				'swf/expressInstall.swf',
				{xmlPath: audioPlayers[i].xmlPath},
				{bgcolor:'ffffff'}
			);
		}
		
	})();
	
	// Media tooltips
	function addMediaTooltipEvents(containerSelector) {
		var $container = $(containerSelector);
		$container.children('.media').bind('mouseenter', function() { 
			$(this).parent().css({"position":"relative"}); 
			$(this).next(".toolTip").animate({"opacity":"toggle"}); 
		});
		$container.children('.toolTip').bind('mouseleave', function() { 
			$(this).css({"display":"none"}); 
			$(this).parent().css({"position":"static"}); 
		});
	}
	
	function removeMediaTooltipEvents(containerSelector) {
		var $container = $(containerSelector);
		$container.children('.media').unbind('mouseenter');
		$container.children('.toolTip').unbind('mouseleave');
	}
	
	/***************************************************************************
	 * Homepage
	 */
	 
	 
	 /*****************
	  * Ask BIG module
	  */
	  
	  	// Functions
		function askDeny()
		{
			$("#askbtn").hide('slow');
			$('#askmsg').show('slow');
		}
		function askAllow()
		{
			$('#askmsg').hide('slow');
			$("#askbtn").show('slow');
		}		
				
	  
	 	// Default
		askDeny();
		
		var minAskLength = 4
		$("#modulehelpformq").keyup(function(evt) {
			if($(this).val().length > minAskLength)
			{
				if($('#modulehelpformregion').val() != "null")
				{
					// Good
					askAllow();
				}
				else
				{
					// Bad
					askDeny();
				}
			}
			else
			{
				askDeny();
			}
			
		});
		
		$("#modulehelpformregion").change(function(evt) {
			if($(this).val() != "null")
			{
				if($('#modulehelpformq').val().length > minAskLength)
				{
					// Good
					askAllow();
				}
				else
				{
					// Bad
					askDeny();
				}
			}
			else
			{
				askDeny();
			}
			
		});
	
	$("#accordion1").accordion();
	$("#accordion1 .ui-accordion-header").attr("tabindex","");
	//if you want to collapse all sections use code below
	//$("#accordion1").accordion({collapsible:true});
	
	$("#heroTabs").css({display:"block"});

	$("#heroArea").tabs();
	
	$("#heroArea .btn.toggle-watch").click(function(evt) {
		
		var $visible = $(this).parent();
		var $hidden;
		
		$visible.css({display:'none'});
		
		if($visible.hasClass('video')) {
			$hidden = $visible.siblings('.content');
		} else {
			$hidden = $visible.siblings('.video');
		}
		
		$hidden.css({display:'block'});
		
		evt.preventDefault();
	});
	
	// Setup community projects tooltips and image switcher
	(function() {
		
		$('#module-community-tab-1 .page li > .toolTip a').each(function() {
			
			var link = $(this);
			var displayContent = link.parent('.toolTip').siblings('.display-content');
			
			link.click(function(evt) {
				
				// Remove tooltip events for the content that will be replaced
				removeMediaTooltipEvents('#module-community-tab-1 .display .display-content');
				
				// NOT WORK IE8 
				//$('#module-community-tab-1 .display .display-content').replaceWith(displayContent.clone());
				// $('#module-community-tab-1 .display .display-content').replaceWith(displayContent);
				$('#module-community-tab-1 .display .display-content').html(displayContent.clone());
				
				
				// Add tooltip events for new display content
				addMediaTooltipEvents('#module-community-tab-1 .display .display-content');
				
				evt.preventDefault();
			});
		});
		
		// Setup toolTips for thumbnails
		addMediaTooltipEvents('#module-community-tab-1 .page li');
		
		// Setup tooltip for initial display content
		addMediaTooltipEvents('#module-community-tab-1 .display .display-content');
		
	})();
	
	// Setup community projects carousel
	(function() {
		
		var $current = $('#module-community-tab-1 .page:first');
		
		$('#module-community-tab-1 .page').each(function(i) {
			if(i > 0) $(this).css({display:'none'});
		});
		
		$('#module-community-tab-1 .pagination-next').click(function(evt) {

			var $next = $current.next('#module-community-tab-1 .page');
			
			if(!$next.length) {
				$next = $('#module-community-tab-1 .page:first');
			}
			
			$current.css({display:'none'});
			$next.css({display:'block'});
			
			$current = $next;
			
			evt.preventDefault();
		});
		
		$('#module-community-tab-1 .pagination-previous').click(function(evt) {

			var $previous = $current.prev('#module-community-tab-1 .page');
			
			if(!$previous.length) {
				$previous = $('#module-community-tab-1 .page:last');
			}
			
			$current.css({display:'none'});
			$previous.css({display:'block'});
			
			$current = $previous;
			
			evt.preventDefault();
		});
		
	})();
	
	// Setup community youtube video switcher
	$('#module-community-tab-4 .scroll-content li > .media').each(function() {
	
		var $media = $(this);
		var $displayContent = $media.siblings('.display-content');
		
		$media.click(function(evt) {
		
		var outerHTML = $displayContent.attr('outerHTML'),
		replacement = outerHTML ? outerHTML : $displayContent.clone();
		
		$('#module-community-tab-4 .display .display-content').replaceWith(replacement);
		
		evt.preventDefault();
		});
	});
	
	// Setup community youtube scroll bar
	(function() {
		
		//scrollpane parts
		var scrollPane = $('#module-community-tab-4 .scroll-pane'),
			scrollContent = $('#module-community-tab-4 .scroll-content');
		
		//build slider
		var scrollbar = $('#module-community-tab-4 .scroll-bar').slider({
			slide:function(event, ui) {
				if (scrollContent.width() > scrollPane.width()) {
					scrollContent.css('margin-left', Math.round(
						ui.value / 100 * (scrollPane.width() - scrollContent.width())
					) + 'px');
				} else {
					scrollContent.css('margin-left', 0);
				}
			}
		});
		
		scrollPane.css('overflow', 'hidden');
		
		scrollbar.wrap('<div class="scroll-bar-helper-parent"></div>');
		
		var handle = scrollbar.find('.ui-slider-handle');
		
		var handleHelper = handle.wrap('<div class="ui-handle-helper-parent"></div>')
			.mousedown(function() {
				scrollbar.width(handleHelper.width());
			})
			.mouseup(function() {
				scrollbar.width('auto');
			})
			.parent()
			.width(scrollbar.width() - handle.width());
	})();
	
	// Create tabs after scroller measuring has taken place
	$('#module-community .content').tabs();
	
	/***************************************************************************
	 * Funding finder
	 */
	
	// JavaScript users get automatic ajax submit
	$('#module-funding-finder-form .controls').css('display', 'none');
	
	$('#module-funding-finder .accordion').accordion({autoHeight:false});
	
	(function() {
		
		var $finderModule = $('#module-funding-finder'),
			$finderForm = $('#module-funding-finder-form'),
			$moduleResults = $('#module-funding-finder-results'),
			$moduleCaseStudies = $('#module-finding-finder-case-studies'),
			fetchTimeoutId,
			resultsXhr,
			caseStudiesXhr;
		
		/**
		 * Wrap the labels with an anchor so they look like a link and, attach
		 * onclick event handler so that when clicked, they get new results,
		 * and open the next pane.
		 */
		$finderForm.find('label').each(function() {
			
			var $link = $(this).wrap('<a href="' + window.location.pathname + '#"/>').parent(),
				$radio = $link.find('input[type="radio"]'),
				$title = $('#module-funding-finder-form-title-' + $radio.attr('name')),
				$accordion = $link.parents('.ui-accordion'),
				accordionIndex;
			
			// Hide the radio
			$radio.addClass('visuallyhidden');
			
			// Save the default heading text
			$title.data('module-funding-finder-form-title', $title.text());
			
			// Figure out what index of the accordion this link is in
			accordionIndex = $accordion.children('.ui-accordion-content').index($link.parents('.ui-accordion-content'));
			
			$link.click(function(event) {
			
				//event.preventDefault()
				
				clearTimeout(fetchTimeoutId);
				
				$finderModule.addClass('loading');
				
				// Set the title (using the default title we saved earlier)
				$title.text($title.data('module-funding-finder-form-title') + ': ' + $link.text());
				
				fetchTimeoutId = setTimeout(function() {
					
					if(resultsXhr) resultsXhr.abort();
					if(caseStudiesXhr) caseStudiesXhr.abort();
					
					//alert($finderForm.serialize())
					
					resultsXhr = $.ajax({
						url:$finderForm.find('#module-funding-finder-form-ajax-url-results').attr('value'),
						type:'POST',
						data:$finderForm.serialize(),
						dataType:'html',
						success:resultsFetchSuccessListener,
						error:resultsFetchErrorListener
					});
					
					// Load case studies for this combination
					caseStudiesXhr = $.ajax({
						url:$finderForm.find('#module-funding-finder-form-ajax-url-case-studies').attr('value'),
						type:'POST',
						data:$finderForm.serialize(),
						dataType:'html',
						success:caseStudiesFetchSuccessListener,
						error:caseStudiesFetchErrorListener
					});
					
					
					
					// Open the next pane of the accordion
					if(accordionIndex + 1 < $accordion.children('.ui-accordion-content').length) {
						$accordion.accordion('activate', accordionIndex + 1);
					}
					
					
				}, 750);
				
				
				
			});
			
			function resultsFetchSuccessListener(data, status, xhr) {
				
				$finderModule.removeClass('loading');
				
				$moduleResults.find('.content').html(data);
				
				
				$moduleResults.find('h2 span').text('(' + $moduleResults.find('.content li').length + ' Programmes)');
				
				Cufon.replace($moduleResults.find('h2 span'));
			}
			
			function resultsFetchErrorListener(xhr, status, error) {
				
				$finderModule.removeClass('loading');
				
				$moduleResults.find('.content').html('<p><br/>Failed to fetch results. Please try again.</p>');
				
				$moduleResults.find('h2 span').text('(0 Programmes)');
				
				Cufon.replace($moduleResults.find('h2 span'));
			}
			
			function caseStudiesFetchSuccessListener(data, status, xhr) {
				
				$moduleCaseStudies.find('.content').html(data);
			}
			
			function caseStudiesFetchErrorListener(xhr, status, error) {
				
				$moduleCaseStudies.find('.content').html('<p><br/>Failed to fetch case studies. Please try again.</p>');
			}
       });

       // If a location radio is selected, invoke the click handler for the item
       $('#module-funding-finder-form-content-loc :checked', $finderForm).closest('a').trigger('click');

})();

	
	/***************************************************************************
	 * Community
	 */
	
	// Setup the twitter scroller
	(function() {
		
		if(!$('#community').length) return;
		
		var $scroller = $('#module-twitter-feed-scroller'),
			$widgets = $scroller.find('.twtr-widget'),
			current = 0,
			step = 3,
			$pages = $('<div id="module-twitter-pagination-pages"></div>'),
			$pageLinks = $([]);
		
		if($widgets.length < step) {
			throw new Error('At least ' + step + ' accounts are needed in the twitter scroller');
		}
		
		function setCurrent(c) {
			
			current = c;
			
			// No less than 0
			if(current < 0) {
				
				current = 0;
				
			// No more than "step" less than total 
			} else if(current >= $widgets.size() - step) {
				
				current = $widgets.size() - step;
			}
			
			$pageLinks.removeClass('selected');
			
			$pageLinks.slice(current, current + step).addClass('selected');
			
			$scroller.scrollTo($widgets.get(current), 1000, {easing:'swing'});
		}
		
		$('#module-twitter .top').append($pages);
		
		// Create the pagination page links
		$widgets.each(function(i) {
			
			var $widget = $(this),
				$pageLink = $('<a href="#"><span></span></a>');
			
			if(i < 3) {
				$pageLink.addClass('selected');
			}
			
			$pageLink.click(function(event) {
				
				setCurrent(i - 1);
				
				event.preventDefault();
			});
			
			// Twitter doesn't add content to the widget until later
			var delayedUsernameUpdateOnMouseEnter = function() {
				
				var username = $widget.find('h4 a').text();
				
				if(username) {
					$pageLink.children('span').text(username);
					$pageLink.unbind('mouseenter', delayedUsernameUpdateOnMouseEnter);
				}
			}
			
			$pageLink.mouseenter(delayedUsernameUpdateOnMouseEnter);
			
			$pages.append($pageLink);
			
			$pageLinks = $pageLinks.add($pageLink[0]);
		});
		
		// Add pagination next/prev click events
		$('#module-twitter .pagination-prev').click(function(event) {
			
			setCurrent(current - step);
			
			event.preventDefault();
		});
		
		$('#module-twitter .pagination-next').click(function(event) {
			
			setCurrent(current + step);
			
			event.preventDefault();
		});
		
	})();
	
	// Setup the flickr lightboxes
	(function() {
		
		$('#module-flickr li .toolTip a').lightBox();
		
		addMediaTooltipEvents('#module-flickr li');
		
	})();
	
	// Setup youtube video switcher
	$('#module-youtube .scroll-content li > .media').each(function() {
	
		var $media = $(this);
		var $displayContent = $media.siblings('.display-content');
		
		$media.click(function(evt) {
		
		var outerHTML = $displayContent.attr('outerHTML'),
		replacement = outerHTML ? outerHTML : $displayContent.clone();
		
		$('#module-youtube .display .display-content').replaceWith(replacement);
		
		evt.preventDefault();
		});
	});
	
	// Setup the youtube scroll bar
	(function() {
		
		//scrollpane parts
		var scrollPane = $('#module-youtube .scroll-pane'),
			scrollContent = $('#module-youtube .scroll-content');
		
		//build slider
		var scrollbar = $('#module-youtube .scroll-bar').slider({
			slide:function(event, ui) {
				if (scrollContent.width() > scrollPane.width()) {
					scrollContent.css('margin-left', Math.round(
						ui.value / 100 * (scrollPane.width() - scrollContent.width())
					) + 'px');
				} else {
					scrollContent.css('margin-left', 0);
				}
			}
		});
		
		scrollPane.css('overflow', 'hidden');
		
		scrollbar.wrap('<div class="scroll-bar-helper-parent"></div>');
		
		var handle = scrollbar.find('.ui-slider-handle');
		
		var handleHelper = handle.wrap('<div class="ui-handle-helper-parent"></div>')
			.mousedown(function() {
				scrollbar.width(handleHelper.width());
			})
			.mouseup(function() {
				scrollbar.width('auto');
			})
			.parent()
			.width(scrollbar.width() - handle.width());
	})();
	
	// Community page hero area
	$('.hero-areas').each(function(container_index){
		var container = $(this)
		
		// generate tabs
		var tabs = []
		container.find('.areas li').each(function(area_index){
			var unique_id = 'area-'+container_index+'-'+area_index
			this.id = unique_id
			
			var title = $(this).find('h3').text()
			var src = $(this).find('img').attr('src')
			var alt = $(this).find('img').attr('alt')
			var lnk = $(this).find('a').attr('href')
			if(src)
			{
				src = src.replace('.jpg', '_small.jpg')
				src = src.replace('.gif', '_small.gif')
				src = src.replace('.png', '_small.png')
				var img = '<img alt="Thumbnail: '+alt+'" src="'+src+'" style=""/>'
				tabs.push('<li data-target="#'+unique_id+'">'+'<a href="'+lnk+'">'+img+'<span style="">'+title+'</span></a></li>');
			}
		})
		container.prepend('<ul class="tabs">'+tabs.join('')+'</ul>')
		
		// make tabs interactive
		container.delegate('.tabs li', 'mouseover', function(){ // notify Damian changing from mouse hover to match iTunes
			
			$(".herochev").eq(container.find('.selected').index()).hide();
			
			container.find('.selected').removeClass('selected')
			
			$(".herochev").eq($(this).index()).show();
			
			//alert("select: " + $(this).index());
			
			$(this).addClass('selected')
			var target = $(this).data('target')
			$(target).addClass('selected')
		})
		
		
		// insert video wrapper
		container.append('<div class="video-player-wrapper"></div>')

		// clear previous video, add placeholder
		var video_player_id = 'video-player'
		container.delegate('.tabs li', 'mouseover', function(){ 
			container.find('.video-player-wrapper').html('<div id="'+video_player_id+'"></div>') // remove previous video
		})

		// play video
		container.find('.youtube').bind('click', function(e){
			e.preventDefault()
			
			var href = this.href
			href = href.replace('watch?v=', 'v/') // convert url to embed url
			
			var params = { allowScriptAccess: "always" }
			swfobject.embedSWF(href+'&enablejsapi=1&playerapiid=ytplayer&autoplay=1', video_player_id, '480', '270', '8', null, null, params)
		})
		
		// init
		container.find('.tabs li:first').trigger('mouseover') // trigger first tab as selected
	});
		


	
	
});


	/***************************************************************************
	* Show Closed Programs
	*/
	
	var close_input = $('.closed-programs-input input')
	var show_text = 'Switch to show only closed programmes'
	var hide_text = 'Switch to show only open programmes'
	
	default_text = show_text;
	if (close_input.attr('checked')){
		default_text = hide_text;
	}

	$('#module-funding-finder-results .top').append('<span class="show-closed-programs-button">'+default_text+'</span>')
	$('.show-closed-programs-button').bind('click', function(){
		
		// change checkbox value, update button text
		if (close_input.attr('checked')){
			close_input.attr('checked', false)
			$(this).text(show_text)
			
		} else {
			close_input.attr('checked', true)
			$(this).text(hide_text)
		}
		// trigger ajax
		/*
		close_input.parent().trigger('click');
		*/
				var $finderModule = $('#module-funding-finder'),
					$finderForm = $('#module-funding-finder-form'),
					$moduleResults = $('#module-funding-finder-results'),
					$moduleCaseStudies = $('#module-finding-finder-case-studies'),
					fetchTimeoutId,
					resultsXhr,
					caseStudiesXhr;
				
				clearTimeout(fetchTimeoutId);
				
				$finderModule.addClass('loading');
				
				// Set the title (using the default title we saved earlier)
				//$title.text($title.data('module-funding-finder-form-title') + ': ' + $link.text());
				
				fetchTimeoutId = setTimeout(function() {
					
					if(resultsXhr) resultsXhr.abort();
					if(caseStudiesXhr) caseStudiesXhr.abort();
					
					resultsXhr = $.ajax({
						url:$finderForm.find('#module-funding-finder-form-ajax-url-results').attr('value'),
						type:'POST',
						data:$finderForm.serialize(),
						dataType:'html',
						success:resultsFetchSuccessListener,
						error:resultsFetchErrorListener
					});
					
					// Load case studies for this combination
					caseStudiesXhr = $.ajax({
						url:$finderForm.find('#module-funding-finder-form-ajax-url-case-studies').attr('value'),
						type:'POST',
						data:$finderForm.serialize(),
						dataType:'html',
						success:caseStudiesFetchSuccessListener,
						error:caseStudiesFetchErrorListener
					});
									
					
				}, 750);
				

			
			function resultsFetchSuccessListener(data, status, xhr) {
				
				$finderModule.removeClass('loading');
				
				$moduleResults.find('.content').html(data);
				
				if (close_input.attr('checked'))
				{
					$moduleResults.find('h2 span').text('(' + $moduleResults.find('.content li').length + ' Closed programmes)');
				}
				else
				{
					$moduleResults.find('h2 span').text('(' + $moduleResults.find('.content li').length + ' Open programmes)');
				}
				
				Cufon.replace($moduleResults.find('h2 span'));
			}
			
			function resultsFetchErrorListener(xhr, status, error) {
				
				$finderModule.removeClass('loading');
				
				$moduleResults.find('.content').html('<p><br/>Failed to fetch results. Please try again.</p>');
				
				$moduleResults.find('h2 span').text('(0 Programmes)');
				
				Cufon.replace($moduleResults.find('h2 span'));
			}
			
			function caseStudiesFetchSuccessListener(data, status, xhr) {
				
				$moduleCaseStudies.find('.content').html(data);
			}
			
			function caseStudiesFetchErrorListener(xhr, status, error) {
				
				$moduleCaseStudies.find('.content').html('<p><br/>Failed to fetch case studies. Please try again.</p>');
			}
				
			
			
	})
	
	
	
	
	
	

	

