/**
 * Welcome to the master Build Guild JavaScript file, it’s so kind of
 * you to join us. What you see in here is a combination of jQuery, 
 * some fantastic plugins, and a whole bunch of flair.
 *
 * Also, open- and -close mustaches ({’s and }’s)!
 *
 * Again, whatever it is that’s going on in this file probably isn’t
 * yours, and just taking it probably isn’t right. If you can take this
 * code and still sleep at night, well, shame on you.
 *
 * We hope you have fun, and please, enjoy your stay.
 *
 * Sincerely,
 * The Management
 */
var iterator = 0, autoPlay, creditRoll;

// on document ready
$(document).ready(function() {
	
	// used as shortcuts for next/previous functionality on jCarouselLite
	$('.footer')
		.append('<a href="#" class="ignore" id="next-social-media-service"></a><a href="#" class="ignore" id="previous-social-media-service"></a>');
	
	autoChooseSocialMediaIcon();
	selectSocialMediaIcon($('.selector img').get(0));
	
	
	
	// turn on javascript-only pieces
	// ------------------------------------------------------------
	$('.boring, .selector').show();
	$('.connections').css('paddingTop', '2em');
	
	
	
	// connections
	// ------------------------------------------------------------
	$('.selector img:not(.on)')
		.live('mouseover', 
			function() {  // enter
				$(this)
					.stop()
					.animate({
						opacity: [1.0, 'easeOutCubic'],
						scale: 0.8
					}, 1200, 'easeOutElastic');
			})
		.live('mouseout',
			function() {  // exit
				$(this)
					.stop()
					.animate({
						opacity: [0.6, 'easeOutCubic'],
						scale: 0.6
					}, 1200, 'easeOutElastic');
			}
		);
	
	$('.selector img').click(function(e) {
		e.preventDefault();
		clearTimeout(autoPlay);
		selectSocialMediaIcon(this);
		return false;
	});
	
	$('.connections').jCarouselLite({
		visible: 1,
		speed: 800,
		easing: 'easeOutQuint',
		btnGo: [ 'img.twitter', 'img.flickr', 'img.linkedin' ],
		btnNext: '#next-social-media-service',
		btnPrev: '#previous-social-media-service'
	});
	
	
	
	// credits
	// ------------------------------------------------------------
	$('#credits').click(function(e) {
		e.preventDefault();
		clearTimeout(autoPlay);
		
		// append the overlay and credits holder, block mousewheel from
		// doing anything and then position the credits holder so that
		// it's near the bottom of the screen
		$('body')
			.append('<div class="overlay" id="magic-overlay"></div>')
			.append('<div class="credits"></div>')
			.find('#magic-overlay')
				.click(function(e) {
					e.preventDefault();
					$('.credits').trigger('endscroll');
					return false;
				})			
				.bind('mousewheel.overlay', function(e, delta) {
					e.preventDefault();
					return false;
				})
				.bind('fadein.overlay', function() {
					$(this).animate({ opacity: 0.9 }, 600, function() {
						playSong(document.audiofile);
						$('.credits').trigger('startscroll');
					});
				})
				.bind('fadeout.overlay', function() {
					fadeAndStopSong(document.audiofile);
					
					//$('#audio-embed').get(0).Stop();
					$('#magic-overlay').stop().unbind('mousewheel').delay(1000).animate({ opacity: 0 }, 1200, function() {
						$(this).remove();
					});
				})
				.end()
			.find('.credits')
				.click(function(e) {
					e.preventDefault();
					$(this).trigger('endscroll');
					return false;
				})			
				.css('top', $(window).height() + 'px')
				.bind('startscroll.credits', function() {					
					$(this).animate({ opacity: 1 }, 600, function() {
						creditRoll = setInterval(function() {
							var newTop = parseInt($('.credits').css('top'), 10) - 2;
							$('.credits').css('top', newTop + 'px');

							if (newTop < 0 && Math.abs(newTop) > $('.credits').height()) {
								// fade out credits
								$('.credits').trigger('endscroll');
							}
						}, 50);
					});
				})
				.bind('endscroll.credits', function() {
					$(this).animate({ opacity: 0 }, 600, function() {
						$('.credits').stop().remove();
						clearInterval(creditRoll);

						// fade out overlay
						$('#magic-overlay').trigger('fadeout');
					});
				})
				.load('credits.html', function() {
					// once credits are loaded, start the show
					$('#magic-overlay').trigger('fadein');					
				});
		return false;
	});
	
	
	
	// mail
	// ------------------------------------------------------------
	$('.mustache-mail').submit(function(e) {
		e.preventDefault();
		if (validateForm()) {
			$('.error-message').stop().slideUp(300);
			$('.info-message').slideDown(300);

			$.ajax({
				data: { "email": $('#email').val() },
				dataType: 'json',
				error: function(request, status, error) {
					$('.info-message').stop().slideUp(300);
					$('.error-message').text(request.responseText).stop().slideDown(300);
				},
				success: function(data, status, request) {
					$('.newsletter-form').delay(1000).slideUp(500, function() {
						$('.success-message').html('<strong>Huzzah! You’re Almost There!</strong>Check your <em>' + data.email + '</em> email for an &ldquo;are you sure&rdquo; confirmation message. This message sometimes comes in as junk, so watch out.').stop().slideDown(300);
					});
				},
				type: "POST",
				url: "/ajax/mail-subscription.php"
			});
		} else {
			$('.error-message').stop().slideUp(200, function() {
				$(this).text('Are you sure that’s your email?').slideDown(300);
			});
		}
		return false;
	});
});

// on page load
$(window).load(function() {
	if (window.location.hash.match(/roll-credits/i)) {
		$('#credits').click();
	}	
});


function autoChooseSocialMediaIcon() {
	var button = iterator % $('.selector img').length;

	$('.selector img').animate({
		scale: 0.6
	}, 50);
	
	$($('.selector img').get(button)).click();
	
	iterator++;
	autoPlay = setTimeout(function() { autoChooseSocialMediaIcon(); }, 4000);
}


function selectSocialMediaIcon(element) {
	var icon = $(element);
	
	$('.selector img').each(function(i) {
		if ($($(this).get(0)).attr('alt').toLowerCase() != icon.attr('alt').toLowerCase()) {
			if ($(this).hasClass('on')) {
				$(this)
					.stop()
					.animate({
						opacity: [0.6, 'easeOutCubic'],
						scale: 0.6
					}, 1200, 'easeOutElastic')
					.removeClass('on');
			}
		} else {
			$(this)
				.stop()
				.animate({
					opacity: [1, 'easeOutCubic'],
					scale: 1
				}, 800, 'easeOutBounce')
				.addClass('on');
		}
	});
}


function playSong(song) {
	if (typeof song == 'undefined') {
		return;
	}
	
	/*
	if (song.GetPluginStatus() != "Complete" && song.GetPluginStatus() != "Playable") {
		setTimeout(function() { playSong(song); }, 100);
		return;
	}
	*/
	
	song.SetVolume(200);
	song.Play();
}


function fadeAndStopSong(song) {
	if (typeof song == 'undefined') {
		return;
	}

	if (song.GetVolume() == 0) {
		song.Stop();
		song.SetTime(0);
		$('#music-player').stop();
		return;
	}
	
	var newVolume = song.GetVolume() - 4;
	song.SetVolume(newVolume);
	
	setTimeout(function() { fadeAndStopSong(song); }, 30);
}


function validateForm() {
	var email = $('#email').val();
	
	if (!email || !email.match(/^[A-Z0-9._%\'-]+@[A-Z0-9._%-]+\.([A-Z]{2,6}){1,2}$/i)) {
		return false;
	}
	
	return true;
}
