$(function() {
	creditsAnimation();
});

function creditsAnimation() {
	
	var ua = navigator.userAgent,
		ua = ua.toLowerCase();
		isFirefox = ua.match('firefox');
		isMobile = (ua.match('ipad') || ua.match('iphone') || ua.match('android') || ua.match('blackberry')) ? true : false,
		isIE = (ua.match('msie 9.0') || ua.match('msie 8.0')) ? true : false;
		
	var body = $('body');
	
	//Stop Credits Animation
	function stop() {
		$('#credits').delay(200).fadeOut(400, function() {
			$('.move').removeClass('move');
			$('.in').removeClass('in');
			$('.out').removeClass('out');
			clearTimeout(t);
			stopAudio();
			$('.credits-overlay').fadeOut(200);
		});
	}	
	
	//Audio Control Functions
	function playAudio() {
		var audio = document.getElementById('song');
		try {
			if(audio) {
				if(!isMobile) { audio.currentTime = 0; }
				audio.play();
			}
		}
		catch(e) {
			
		}
	}
	
	function stopAudio() {
		var audio = document.getElementById('song');
		audio.pause();
	}
	
	function muteAudio() {
		var audio = document.getElementById('song');
		if(audio.muted == false) {
			audio.muted = true;
		}
		else {
			audio.muted = false;
		}
	}
	
	//Play Credits Animation
	function play() {
		var nameEls = $('.name'),
			titleEls = $('.title'),
			creditsEl = $('#credits'),
			cnt = nameEls.length,
			inc = 0;
		
		creditsEl.fadeIn(400, function() {
			playAudio();
			if(!isMobile && !isIE) {
				$('#credits .outer').addClass('move');
				$('#credits .stage').addClass('move');
			}
		});
		
		$('.credits-overlay').fadeIn(400);
			
					
		(function loop() {
			$('.idx-' + inc).addClass('in');
			if(inc > 0) {
				var x = inc-1;
				$('.idx-' + x).addClass('out');
			}
			t = setTimeout(loop, 4000);
			if(inc >= cnt) {
				stop();
			}
			inc++;
		})();
	}
	
	function wireButtons() {
		$('.mute').click(function() {
			var $this = $(this);
			if($this.text() == 'mute') {
				$this.text('unmute');
			}
			else {
				$this.text('mute');
			}
			muteAudio();
			if(isMobile) {
				stopAudio();
			}
			return false;
		});
		
		$('.close-credits').click(function() {
			stop();
			return false;
		});
	}
	
	$('a[href=#credits]').click(function() {
		if($('#credits').length <= 0) {
			body.append('<div id="loading">loading…</div>');
			$.get('wp-content/themes/fullcontact-consumer/assets/includes/credits/credits.php',{}, function(data) {
				body.append(data);
				$('#loading').remove();
				play();
				wireButtons();
				if(isMobile) { playAudio(); }
			}, 'html');
		}
		else {
			play();
			if(isMobile) { playAudio(); }
		}
		return false;
	});
}
