
jQuery(document).ready(function(e) {

    recaptchaStyles();
    latestPodcastExpando();
    bannerScroller();
    expando();
    audioPlayer();    
    
});

//Recaptcha Style Overrides
function recaptchaStyles() {

    jQuery("head").append('<link id="Link3" rel="stylesheet" href="/StyleSheets/Default/reCAPTCHA-overrides.css" type="text/css" />');  
          
}

//Latest Podcast Expando
function latestPodcastExpando() {

    var latestPodcast = jQuery(".latestPodcastArea", "div.rightContentContinued");
    
    if (latestPodcast.length > 0) {
        
        //Delay and Speeds
        var expandDelay = 1250,
            expandSpeed = 200,
            fadeInSpeed = 900;
            
        var latestPodcastSoundburst = jQuery(".latestPodcastSoundburst", latestPodcast),
            pushLine = jQuery("span.pushLine", latestPodcast),
            expandoArea = jQuery("div.expandoArea", latestPodcast),
            expandoAreaChildren = expandoArea.children();
        
        //Wait for page content to load
        jQuery(window).load(function() {
            
            //Pushline
            pushLine.animate({
                width: '100%'
            }, {
                duration: expandDelay,
                easing: 'linear',
                complete: function () {
                    if (expandoAreaChildren.length > 0) {
                        expandoArea.slideDown(expandSpeed, 'swing',
                            function () {
                                expandoAreaChildren.css("visibility","visible");
                                latestPodcastSoundburst.fadeIn(fadeInSpeed);
                            });
                    } else {
                        latestPodcastSoundburst.fadeIn(fadeInSpeed);
                    }
                }
            });
            
        });     
               
    }

}

//Banner Scroller
//Use class of 'full' on a listItem if whole background should move off
function bannerScroller() {
	
	var bannerContainer = jQuery("div.bannerContainer", "div.billboard"),
		bannerList = bannerContainer.children().last();
			
    if (bannerList.length > 0) {

        	//Speed of animations
        var backgroundSpeed = 700,
            contentSpeedOut = 600,
            contentSpeedIn = 600,
            initialContentSpeedIn = 800,

            //Delay on interval
            intervalDelay = 7000,
            timeoutDelay = 1500;

        	//Easing Styles
        	backgroundEasing = 'easeOutQuart', 
			contentEasingIn = 'easeOutExpo', 
			contentEasingOut = 'easeInExpo';

        var listItem = bannerList.children(),
            firstItem = listItem.eq(0),
            numberOfListItems = listItem.length;
		
        //Sets state of initial item
        var firstItemChildLeft = firstItem.children().css("left");
        firstItem.css('left', '0%').children().css('left', '100%');
        if (firstItem.children().length > 0) {
            firstItem.children().animate({
                left: firstItemChildLeft
            }, {
                duration: initialContentSpeedIn,
                easing: contentEasingIn,
                complete: function () {
                    listItem.addClass('complete');
                }
            });
        } else {
            listItem.addClass('complete');
        }

        //Interval and Timeouts
        var interval, 
            timeout, 
            scrollerTimer = function () {
                                scroller();
                            };
        function runInterval() {
            if (numberOfListItems > 1) {
                if (listItem.hasClass('interaction')) {
                    listItem.removeClass('interaction');
                    if (listItem.hasClass('complete')) {
                        if (listItem.hasClass('navClick')) {
                            listItem.removeClass('navClick');
                            timeout = setTimeout(scrollerTimer, 0);
                        } else {
                            timeout = setTimeout(scrollerTimer, timeoutDelay);
                        }
                    }
                }
				interval = setInterval(scrollerTimer, intervalDelay);
            }
        }
        runInterval();

        //Next and Previous Buttons
        if (numberOfListItems > 1) {
            bannerList.before('<div class="bannerNavLinks"><a class="bannerNav bannerFeaturePrev" href="#"><span class="bg"></span><span class="arrow"></span></a><a class="bannerNav bannerFeatureNext" href="#"><span class="bg"></span><span class="arrow"></span></a></div>');
            var bannerNavLinksContainer = bannerContainer.find("div.bannerNavLinks"),
                bannerNavLinks = bannerNavLinksContainer.children(),
                prevLink = bannerNavLinks.eq(0),
                nextLink = bannerNavLinks.eq(1);
            bannerNavLinks.hide();
		    var navTimeout;
		    bannerContainer.hover(
            function () {
			    clearTimeout(navTimeout);
			    bannerNavLinks.stop(true, true).fadeIn();
            }, function () {			
			    navTimeout = setTimeout(function () {
				    bannerNavLinks.stop(true, true).fadeOut();
			    }, 600);
            });		
		    bannerNavLinks.hover(
            function () {
                clear();
            });
		    prevLink.click(function () {				
				if (listItem.hasClass('complete')) {
					listItem.addClass('prevClick');
                	navClick();
				}
				else {
					navClickIncomplete();
				}
            });
            nextLink.click(function () {           	    
				if (listItem.hasClass('complete')) {
					navClick();
				}
				else {
					navClickIncomplete();
				}
		    });		
		    function navClick() {
				listItem.addClass('interaction');
			    listItem.addClass('navClick'); 
				clear();
			    runInterval();
			    return false;
		    }
		    function navClickIncomplete() {
				clear();
			    runInterval();
			    return false;
		    }
        }

        //On Mouse hover
        listItem.hover(
        function () {
            clear();
            listItem.addClass('interaction');
        }, function () {
            runInterval();
        });
		
		//Clear Intervals and Timeouts
		function clear() {
			clearInterval(interval);
            clearTimeout(timeout);
		}

        //Function for Scrolling Items
        function scroller() {
            var listItem = bannerList.children(),
                currentItem = listItem.eq(0),
                currentItemChildLeft = currentItem.children().css("left"),
                next = listItem.eq(1),
                prev = listItem.filter(":last"),
                nextChildLeft = next.children().css("left"),
                prevChildLeft = prev.children().css("left"),
                contentWidthCurrent = currentItem.children().outerWidth(),
                moveOffLeft = '-100%',
                moveOffRight = '100%';
            listItem.removeClass('complete');
            if (listItem.hasClass('prevClick')) {
                prev.css('left', '-100%');
                prev.children().css('left', '-100%');
                if (currentItem.children().length != 0) {
                    currentItem.children().animate({
                        left: '100%'
                    }, {
                        duration: contentSpeedOut,
                        easing: contentEasingOut,
                        complete: function () {
                            itemScroller(moveOffRight, currentItem, prev, currentItemChildLeft, prevChildLeft);
                        }
                    });
                } else {
                    itemScroller(moveOffRight, currentItem, prev, currentItemChildLeft, prevChildLeft);
                }
            } else {
                next.children().css('left', '100%');
                if (currentItem.children().length != 0) {
                    currentItem.children().animate({
                        left: '-' + contentWidthCurrent + 'px'
                    }, {
                        duration: contentSpeedOut,
                        easing: contentEasingOut,
                        complete: function () {
                            itemScroller(moveOffLeft, currentItem, next, currentItemChildLeft, nextChildLeft);
                        }
                    });
                } else {
                    itemScroller(moveOffLeft, currentItem, next, currentItemChildLeft, nextChildLeft);
                }
            }
        }
        function itemScroller(moveOffPosition, currentItem, itemToShow, currentItemChildLeft, itemToShowChildLeft) {
            currentItem.animate({
                left: moveOffPosition
            }, {
                duration: backgroundSpeed,
                easing: backgroundEasing,
                complete: function () {
                    if (itemToShow.hasClass("full")) {
                        appendCurrentItem(currentItem, currentItemChildLeft);
                    } else {
                        newItem(itemToShow, itemToShowChildLeft);
                        appendCurrentItem(currentItem, currentItemChildLeft);
                    }
                }
            });
            if (itemToShow.hasClass("full")) {
                newItem(itemToShow, itemToShowChildLeft);
            }
        }

        function appendCurrentItem(currentItem, currentItemChildLeft) {
            if (listItem.hasClass('prevClick')) {                
            } else {
                currentItem.appendTo(bannerList);
            }
            currentItem.css('left', '100%');
            currentItem.children().css('left', currentItemChildLeft);
        }

        function newItem(itemToShow, itemToShowChildLeft) {
            itemToShow.animate({
                left: '0%'
            }, {
                duration: backgroundSpeed,
                easing: backgroundEasing,
                complete: function () {
                    if (itemToShow.children().length > 0) {
                        itemToShow.children().animate({
                            left: itemToShowChildLeft
                        }, {
                            duration: contentSpeedIn,
                            easing: contentEasingIn,
                            complete: function () {
                                if (listItem.hasClass('prevClick')) {
                                    itemToShow.prependTo(bannerList);
                                    listItem.removeClass('prevClick');
                                }
                                listItem.addClass('complete');
                            }
                        })
                    } else {
                        if (listItem.hasClass('prevClick')) {
                            itemToShow.prependTo(bannerList);
                            listItem.removeClass('prevClick');
                        }
                        listItem.addClass('complete');
                    }
                }
            });
        }

    }

}

//AUDIO PLAYER
function audioPlayer() {

	if(!!document.createElement('audio').canPlayType) {
		
		var audioTag = jQuery('div.audioPlayer audio').get(0);
		
		if(audioTag) {
			
			var audioControls = jQuery('div.audioControls');
			
			if(audioControls) {
				
				//Check if play and pause are supported
				if((audioTag.play != undefined) && (audioTag.pause != undefined)) {

					audioControls.addClass('supported');
					
					// Add supportedControls area to audio player
					audioControls.prepend('<div class="supportedControls" ></div>');
					var supportedControls = jQuery('div.supportedControls');
					
					//Insert Play/Pause Button
					supportedControls.append('<p><a href="#" class="playPauseButton buttonLink">Play/Pause<span class="button"><span class="buttonBot"></span></span><span class="icon"></span></a></p>');
					var	playPauseButton = jQuery('a.playPauseButton');
					
					//Check if muted is supported
					if(audioTag.muted != undefined) {						
						//Volume Button inserted
						playPauseButton.parent().after('<p><a href="#" class="volumeControl buttonLink">Mute/Unmute<span class="button"><span class="buttonBot"></span></span><span class="icon"></span></a></p>');
						var	volumeControl = jQuery('a.volumeControl');
						// Volume Function
						volumeControl.click(function () {
							if (audioTag.muted = !audioTag.muted) {
								volumeControl.addClass('muted');
								audioTag.muted=true;
								return false;
							} else {
								volumeControl.removeClass('muted');
								audioTag.muted=false;
								return false;
							}
						});
					}
					
					//Check if currentTime is supported
					if((audioTag.currentTime != undefined) && (audioTag.duration != undefined)) {
					    
					    //Force load of audio
						audioTag.load();
						
						audioControlsWidth = '360px';
						
						//Timeline inserted
						supportedControls.append('<span class="timeLine"></span>');
						var timeLine = jQuery('span.timeLine');
						//Timeline - handle inserted
						timeLine.prepend('<span class="handle ui-slider-handle"></span>');
						var positionIndicator = jQuery('span.handle');
						//Timeline - played bar inserted
						timeLine.prepend('<span class="played" ></span>');
						var playedIndicator = jQuery('span.played');
						
						//Time Figure inserted
						timeLine.after('<span class="timeFigure"></span>');
						var timeFigure = jQuery('span.timeFigure');
										
						//Calculation variables declared outside of playTimes function 
						var dur, durInt, durIntMins, durIntSecs, durTime,
							cur, curInt, curIntMins, curIntSecs, curTim,
							rem, pos, remMins, remSecs, remTime;
						//Calculation for time figures
						function playTimes() {
							// Audio Duration
							dur = audioTag.duration,
							durInt = parseInt(dur, 10),
							durIntMins = Math.floor(durInt / 60, 10),
							durIntSecs = durInt - durIntMins * 60,
							durTime = durIntMins + ':' + (durIntSecs > 9 ? durIntSecs : '0' + durIntSecs);				
							//Current Time
							cur = audioTag.currentTime,
							curInt = parseInt(cur, 10),
							curIntMins = Math.floor(curInt / 60, 10),
							curIntSecs = curInt - curIntMins * 60,
							curTime = curIntMins + ':' + (curIntSecs > 9 ? curIntSecs : '0' + curIntSecs);				
							//Remaining Play time
							rem = parseInt(dur - cur, 10),
							pos = (cur / dur) * 100,
							remMins = Math.floor(rem / 60, 10),
							remSecs = rem - remMins * 60,
							remTime = '-' + remMins + ':' + (remSecs > 9 ? remSecs : '0' + remSecs);
						}
						
						//Timeline
						var loaded, manualSeek;						
						function timeLineFunction() {							
							if (!manualSeek) {
								//Sets position of handle
								positionIndicator.css({left: pos + '%'});
								//Sets width of played amount
								playedIndicator.css({width: pos + '%'});
							}
							if (!loaded) {
								loaded = true;
								timeLine.slider({
									value: 0,
									step: 0.01,
									orientation: "horizontal",
									range: "min",
									max: dur,
									animate: true,
									slide: function () {
										manualSeek = true;
									},
									stop: function (e, ui) {
										manualSeek = false;
										audioTag.currentTime = ui.value;
									}
								});
							}
						}
						
						jQuery(audioTag).bind('loadeddata',function() {
						
							//Calculates play time data
							playTimes();
							
							//Check if buffered is supported
							if ((audioTag.buffered != undefined) && (audioTag.buffered.length != 0)) {
								//Buffer Bar is inserted
								timeLine.addClass('bufferSupported').prepend('<span class="buffer" ></span>');
								var bufferIndicator = jQuery('span.buffer');								
								var endBuf = 1;
								var fullyBuffered = false;
								
								if (fullyBuffered == false) {
									jQuery(audioTag).bind('timeupdate', function() {
										if (endBuf >= durInt) {
											fullyBuffered = true;
											bufferIndicator.css({width: '100%'});
										} else {
											endBuf = parseInt(audioTag.buffered.end(0), 10);
											var amountLoaded = (endBuf / dur) * 100;
											bufferIndicator.css({width: amountLoaded + '%'});
										}
									});
								}
							}
							
							//Sets Initial Time Figure State - use 'current' 'remaining' or 'duration'
							var timeFigureState = 'remaining';
							//Updates Time Figure Text
							timeUpdate();
													
							jQuery(audioTag).bind('timeupdate', function () {							    
								playTimes();
								timeLineFunction();
								timeUpdate();
	                        });
																				
							//Time Switch
							timeFigure.click(function () {
								timeSwitch();
								return false;
							});
							function timeSwitch() {
								switch(timeFigureState)
								{
								case 'remaining':
									timeFigure.text(curTime);
									timeFigureState = 'current';
									break;
								case 'current':
									timeFigure.text(durTime);
									timeFigureState = 'duration';
									break;
								case 'duration':
									timeFigure.text(remTime);
									timeFigureState = 'remaining';
									break;
								default:
									timeFigure.text(curTime);
									timeFigureState = 'current';
								}
							}
							function timeUpdate() {								
								switch(timeFigureState)
								{
								case 'remaining':
									timeFigure.text(remTime);
									break;
								case 'current':
									timeFigure.text(curTime);
									break;
								case 'duration':
									timeFigure.text(durTime);
									break;
								default:
									timeFigure.text(curTime);
									timeFigureState = 'current';
								}
							}						
						});
						
					} else {
						audioControlsWidth = '128px';
					}					
					
					//Play/Pause Functionality
					var audioControlsWidth = '360px';
					var audioControlsSpeed = 300;
					
					jQuery(audioTag).bind('play',function() {
						//Check for onLoad, if not present, player animates out to show controls
						if (!audioControls.hasClass('onLoad')) {
							audioControls.animate({
								width: audioControlsWidth
							}, {
								duration: audioControlsSpeed,
								easing: 'swing',
								complete: function () {
									audioControls.addClass('onLoad');
								}
							})
						}
						// When playing - adds class of playing to playPauseButton
						playPauseButton.addClass('playing');
					});
				
					jQuery(audioTag).bind('pause',function() {
						//When paused - removes class of playing from playPauseButton
						playPauseButton.removeClass('playing');
					});	
						
					jQuery(audioTag).bind('ended',function() {
						//When playing ends - removes class of playing from playPauseButton and resets time to 0
						playPauseButton.removeClass('playing');
						audioTag.currentTime = 0;
						audioTag.pause();
					});
						
					// Play/Pause Button - Click
					playPauseButton.click(function () {
						playPause();
						return false;
					});
					//Play/Pause Toggle Function
					function playPause() {
						if (audioTag.paused) {
							audioTag.play();
						} else {
							audioTag.pause();
						}
					}
				}
			}
		}
	}

}


// Expando
function expando() {

    var expandoContent = jQuery("div#expando");
    
    if (expandoContent.length > 0) {
    
        var expandoTrigger = jQuery("a#expandoTrigger"),
            scrollToTrigger = jQuery("a.scrollToForm"),
            expandoContainer = jQuery("div#callToActionContainer"),
            expandoState = expandoContent.next();

        if(expandoState.val() == 'open') {
            expandoContent.show();
            expandoContainer.addClass('open');
        }
        
        expandoTrigger.click(function(){            
            expandoContent.slideToggle(400, 'easeOutExpo');
            if(expandoState.val() == '' || expandoState.val() == 'closed') {
                expandoState.val('open');
                expandoContainer.addClass('open');
            } else {
                expandoState.val('closed');
                expandoContainer.removeClass('open');
            }                    
            return false;
        });
        
        scrollToTrigger.click(function(){
           expandoContent.show();
           expandoState.val('open');
           expandoContainer.addClass('open');
        });

    }
}

/* USEFUL */

function activateURLs(stringToConvert){
	var rx = new RegExp(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig);
	return stringToConvert.replace(rx, "<a href='$1' target='_blank'>$1</a>");
}


/* TWITTER API */

//	function getTweets
//	returns string containing <tweetCount> tweets from @<screenname> in a specified <outputTemplate>
//	outputTemplate:			default benaviour, output all tweets in a string	
//	p 		wraps each tweet in <p> & </p> tag. URLs are output as hyperlinks
//	li		wraps each tweet in <li> & <li> tags. URLs are output as hyperlinks
//	ul		as li, but outputs list items within unordered list tags
//	ol		as li, but outputs list items within ordered list tags
//	outputLocation	ID of the container where HTML should be output
//	uses Twitter's API: GET statuses/user_timeline
//	https://dev.twitter.com/docs/api/1/get/statuses/user_timeline
function getTweets(screenName, tweetCount, outputTemplate, outputLocation)
{
	var destinationObject = jQuery("#"+outputLocation);
	if (destinationObject.length == 0){
		return false;
	}
	
	var apiURL = "http://twitter.com/statuses/user_timeline/" + screenName + ".json?callback=?";
	jQuery.getJSON(apiURL, function(data) {
		
		var carryOn = true;
		var i = 0;
		var output = ""; 
		var total = data.length;
		
		if (i == data.length){
			carryOn = false;
		}
		
		while ((i < tweetCount)&&(carryOn)){
			
			var tweet = data[i].text;
			var tweetDate = data[i].created_at;
			
			switch (outputTemplate){
				case "li":
				case "ul":
				case "ol":
					//output = output + "<li class='getTweetsTweet" + i + "'>" + activateURLs(tweet) + "<span class='getTweetsTweetDate'>" + data[i].created_at + "</span></li>";
					output = output + "<li class='getTweetsTweet" + i + "'>" + activateURLs(tweet) + "</li>";
					break;
				case "p":
					output = output + "<p class='getTweetsTweet" + i + "'>" + activateURLs(tweet) + "</p>";
					break;
				case "span":
					output = output + "<span class='getTweetsTweet" + i + "'>" + activateURLs(tweet) + "</span>";
					break;
				default:
					output = output + tweet;
			}
			
			i++;
			if (i == data.length){
				carryOn = false;
			}
		}
		
		switch (outputTemplate){
			case "ul":
				output = "<ul>" + output + "</ul>"
				break;
			case "ol":
				output = "<ol>" + output + "</ol>"
				break;
		}
		
		jQuery(destinationObject).html(output);
	});
}

 //Previous Banner Scroller
 //Banners
jQuery(document).ready(function(){

	var bannersList = jQuery('.bannersList');
	var bannerListNavigation = jQuery('.bannerListNavigation');
	
	bannerListNavigation.children().first().addClass('current');
	
	var positionleft = 0;
	var bannersArray = [];
	
	bannersList.children().each(function(i)
	{	
		jQuery(this).css('left', function(j, val)
		{
			positionleft = positionleft+986;
			return(positionleft)+'px';
		});
		
		jQuery(this).attr('id','headerBanner'+i);
		bannersArray[('headerBanner'+i)] = i;
	});
	
	var currentBanner = bannersList.children().first().attr('id');
			
	function startInterval() {
	
		interval = setInterval(function()
		{
			bannerRotate(1000,1);
			
		}, 5000)
	}

	function bannerRotate(speed,requestedIndex){
				
		do {
			bannersList.children().animate(
			{
				left : '-=986',
				opacity : 1
				
			}, speed, 'swing');
							
			previousBanner = bannersList.children().first();
			previousBanner.appendTo(bannersList);
										
			previousBanner.animate(
			{
				left : positionleft,
				opacity : 0
				
			}, 0, 'linear');
			
			currentBanner = bannersList.children().first().attr('id');
			
			bannerListNavigation.children().removeClass();
			bannerListNavigation.children().eq(bannersArray[currentBanner]).addClass('current');
											
			requestedIndex--;
		}
		while (requestedIndex > 0);
	}
	
	bannerListNavigation.children().click(function() {
	
		var index = jQuery(this).index();
		bannerIndex = jQuery('#headerBanner'+index).index();

		if (bannersArray[currentBanner] != index) {
			bannerRotate(0,bannerIndex);
		}
	});
	
	bannerListNavigation.children().mouseover(function(){
	
		clearInterval(interval);
	});
	
	bannerListNavigation.children().mouseout(function(){
	
		startInterval();
	});
	
	startInterval();
	
	jQuery('.navPopup').hide();
	
	jQuery('#nav li').children().removeAttr('filter');

	
	jQuery('#nav li').hover(
		function()
		{
			jQuery(this).children().first().css({'background':'white','color':'black'});
			jQuery(this).children('.navPopup').stop(true,true).fadeIn(150);
		},
		function()
		{
			jQuery(this).children().first().css({'background':'none','color':'white'});
			jQuery(this).children('.navPopup').stop(true,true).fadeOut(50);
		}
	);
		
});
