/*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:.

  JavaScript for Bad Religion: Main File

.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*/


/**
 * Browser-specific nudges and what-not.
 */
function cssFixes() {
	if($.browser.mozilla) {
		$('#header form input.text').css({
			paddingTop: '1px'
		});
	}
}


/**
 * Nullify links that resolve to only '#'. It's annoying seeing that thing
 * in the addressbar during development!
 */
function nullifyEmptyLinks() {
	$('a').each(function() {
		if($(this).attr('href') == '#') {
			$(this).click(function() {
				return false;
			});
		}
	});
}


/**
 * Modal Overlay Mini-Plugin for search results.
 * Quick and dirty. Err, I mean clean. Squeaky clean.
 */
(function($) {
	$.fn.extend({

		modalOverlay: function() {

			function loadFlickr(obj, flickrUrl) {
				var img = new Image;
				img.onload = function() {
					$('#modalOverlay').animate({
						width: this.width,
						height: this.height
					}, {
						duration: 250,
						step: centerOverlayInIE,
						complete: function() {
							$('#modalOverlay').append(img);
							$(img).hide().fadeIn(250);
						}
					});
				}
				img.src = $(obj).data('src');
			}

			function loadVimeo(obj, videoId) {

				var $div = $('<div>');

				$div.flash({
					src: 'http://vimeo.com/moogaloop.swf',
					width: 640,
					height: 405,
					allowscriptaccess: 'always',
					bgcolor: '#000000',
					allowfullscreen: true,
					flashvars: {
						clip_id: videoId,
						width: 604,
						height: 405,
						color: 'db2334',
						show_portrait: 0,
						show_byline: 0,
						show_title: 0,
						fullscreen: 1,
						js_api: 0
					}
				});

				$div.click(function(e) {
					e.stopPropagation();
					return false;
				})

				$('#modalOverlay').animate({
					width: 640,
					height: 405
				}, {
					duration: 250,
					step: centerOverlayInIE,
					complete: function() {
						$('#modalOverlay').append($div);
						$($div).hide().fadeIn(250);
					}
				});
			}

			function insertOverlay(obj) {
				$('body').append('<div id="modalOverlayBackground">').append('<div id="modalOverlay">');
				$('#modalOverlayBackground').css('opacity', '0.8');

				$(window).resize(centerOverlayInIE);
				centerOverlayInIE();

				var init = false;

				$('#modalOverlay, #modalOverlayBackground')
					.hide()
					.click(closeOverlay)
					.fadeIn(250, function() {

						if(init) return false;

						init = true;

						if($(obj).data('video')) {
							loadVimeo(obj, $(obj).data('src'));
						} else {
							loadFlickr(obj, $(obj).data('src'));
						}

						return false;
					});
			}

			function closeOverlay() {
				$('#modalOverlay, #modalOverlayBackground').fadeOut(250, function() {
					$(this).remove();
				});
			}

			function centerOverlayInIE() {
				if(!$.browser.msie) return;
				$('#modalOverlay').css({
					left: $(window).width()/2 - $('#modalOverlay').width()/2,
					top: $(window).height()/2 - $('#modalOverlay').height()/2
				});
			}

			return $(this).each(function() {

				var vimeo = this.href.match(/https?:\/\/(?:www.)?vimeo\.com\/(\d+)/);

				if(vimeo && vimeo[1]) {
					$(this).data({video: true, src: vimeo[1]});
				} else {
					$(this).data({video: false, src: this.href});
				}

				$(this).click(function(e) {
					insertOverlay(this);
					return false;
				});

			});
		}
	});
})(jQuery);


/**
 * Flash replacement of sorts.
 *
 * Dependencies:
 * jQuery 1.4.1
 * jquery.flash.js 1.0
 */
function flashReplacement() {

	/**
	 * Convert arguments into key-value pairs suitable for arguments to be
	 * applied to a SWF. Multiple arguments accepted.
	 */
	function makeParams() {
		var string = '?';

		for(var i = 0; i < arguments.length; i = i + 2) {
			if(i > 0) string += '&';
			string += encodeURIComponent(arguments[i]) + '=' + encodeURIComponent(arguments[i + 1]);
		}

		return string;
	}

	/**
	 * Do the actual Flash-replacing
	 */
	function flashReplacement(expression, swf, width, height, uppercase, center, html) {
		var id = 0;

		$(expression).each(function() {

			var text;

			if(html) {
				text = $(this).html();
			} else {
				text = $(this).text();
			}

			var flashvars = {};

			if(uppercase) text = text.toUpperCase();

			if(center) {
				flashvars.center = true;
			}

			$(this).flash({
				src: swf + makeParams('txt', text, 'id', (id++)),
				width: width,
				height: height,
				wmode: 'transparent',
				flashvars: flashvars
			}, {
				version: 9,
				update: false
			});

			if($(this).hasClass('flash-replaced')) {
				$('.flash-replaced .alt').css('display', 'none');
			}

		});
	}

	flashReplacement('#header h1', '/_swf/titling.swf', 900, 40);
	flashReplacement('#header h2', '/_swf/subtitling.swf', 900, 22);
	flashReplacement('#news .blog h2', '/_swf/newsheader.swf', 500, 28, false, false, true);
	flashReplacement('#contact dt, #links h2', '/_swf/miniheader.swf', 300, 18, true);
	flashReplacement('body.home h1', '/_swf/newsheader.swf', 604, 28, false, true, true);
}


/**
 * Resize a news item header to the actual height of the news header SWF
 * content. Invoked when a news header SWF's content wraps beyond the first
 * line via an ExternalInterface call in 'newsheader.swf'.
 */
function resizeNewsHeader(size, id) {
	$('#news .blog h2 embed').eq(id).height(size);
}


/**
 * CONTROLLER: NEWS
 */
function NewsController() {

	//var googleMapsApiKey = 'ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSsTL4WIgxhMZ0ZK_kHjwHeQuOD4xQJpBVbSrqNn69S6DOTv203MQ5ufA'; // Google's API Key
	var googleMapsApiKey = 'ABQIAAAA7SAckO3mSLJSTOrhr6HQARSpofxwKohdTBO5R2q4M5H6Q8iMMRR_7Niadxo2r-Ucjt6WAZKyL5jEqA'; // BR's API Key

	var $allItems = $('#news .events .items>li');

	// Truncate long URLs in updates column
	$('#news .updates dt a').each(function() {
		var s = $(this).text();
		s = s.replace(/^https?:\/\/(www.)?/, '');
		if(s.length > 12) s = s.substr(0, 11) + '…';
		$(this).text(s);
	});

	// Setup click handling for tour date items
	$('#news .events .items>li h3>a').click(function() {

		$item = $(this).parent().parent();
		$contents = $item.find('div');

		// If this item is open, close it and abort the rest of the
		// opening operation here.
		if($contents.css('display') != 'none') {
			$item.removeClass('open');
			$contents.slideUp();
			return false;
		}

		// Close open elements
		$('#news .events .items>li').removeClass('open');
		$('#news .events .items>li div').slideUp();

		// If we haven't generated a Google Map for this item, do it now
		if($contents.find('img').size() <= 0) {
			var address = $contents.find('span').text();
			$contents.find('span').remove();
			$contents.append(generateGoogleMap(address));
		}

		// Show the contents
		$item.addClass('open');
		$contents.slideDown();

		return false;
	});

	function generateGoogleMap(address) {
		address = address || '1304 Maltman Ave Los Angeles, CA';
		address = address.replace(/\s/g, '+');

		url = 'http://maps.google.com/maps/api/staticmap?';

		params = {
			center: address,
			zoom: 13,
			size: '180x220',
			sensor: 'false',
			markers: 'color:red|label:|' + address,
			key: NewsController.googleMapsApiKey
		}

		for(var key in params) {
			url += key + '=' + params[key] + '&';
		}

		url = url.substring(0, url.length - 1); // JavaScript chop, baby. Here's looking at you, Perl.

		return $('<a href="http://maps.google.com/maps?q=' + address + '"><img src="' + url + '" width="180" height="220" alt=""></a>');
	}
}


/**
 * CONTROLLER: ALBUMS
 */
function AlbumController() {

	var $lyrics;
	var $trackDetails;

	setupMetaColumn();

	$('.tracks li>a').each(function() {
		$(this).click(function() {
			loadTrackData($(this).attr('href'));
			return false;
		})
	});

	function setupMetaColumn() {
		$lyrics = $('#album .meta div');
		$trackDetails = $('#album .meta dl');

		$trackDetails.css('opacity', 0);
		$('#album .meta .chooser a').click(showTrackDetails);
	}

	function showTrackDetails() {
		$lyrics.css('z-index', 9).animate({opacity: 0}, {duration: 250});
		$trackDetails.css('z-index', 10).animate({opacity: 1}, {duration: 250});
		changeLinks();

		return false;
	}

	function showLyrics() {
		$lyrics.css('z-index', 10).animate({opacity: 1}, {duration: 250});
		$trackDetails.css('z-index', 9).animate({opacity: 0}, {duration: 250});
		changeLinks();

		return false;
	}

	function changeLinks() {
		$link = $('#album .meta .chooser a');
		$span = $('#album .meta .chooser span');

		$link.replaceWith('<span>' + $link.text() + '</span>');
		$span.replaceWith('<a href="#">' + $span.text() + '</a>');

		$link = $('#album .meta .chooser a');

		if($link.text().toLowerCase() == 'track details') {
			$link.click(showTrackDetails);
		} else {
			$link.click(showLyrics);
		}
	}

	function loadTrackData(url) {
		$.get(url, null, insertTrackData, 'html');
	}

	function insertTrackData(html) {
		$('#album .meta').hide().empty().append(html);
		setupMetaColumn();
		$('#album .meta').fadeIn(250);
	}

	// Footer Fix
	if($('#album').size() > 0) {
		$('#footerHack').addClass('albums');
	}

	// Truncate log track titles
	$('#album .tracks a[href*="songmeta"]').each(function() {
		var s = $(this).text();
		if(s.length > 40) s = s.substr(0, 40) + '…';
		$(this).text(s);
	});
}


/**
 * ALBUM SCROLLBAR
 */
$(function() {
	// Add some extra spans which become gradient overlays on the album thumbnails
	$('#albums>.thumbs a').prepend('<span>');
	$('#albums>.thumbs span').mouseover(function(e) {
		e.stopPropagation();
		$(this).animate({opacity: 0}, {queue: false, duration: 150});
	});
	$('#albums>.thumbs span').mouseout(function(e) {
		e.stopPropagation();
		$(this).animate({opacity: 1}, {queue: false, duration: 150});
	});
	new AlbumScroller();
});


/**
 * CONTROLLER: SEARCH
 */
function SearchController() {

	var transitionDuration = 250;

	$('#searchResults .seeAll a').click(function(e) {

		var text = $(this).text();
		var $more = $(this).parent().parent().find('.more');

		$('#searchResults .more').slideUp(transitionDuration);
		$('#searchResults .seeAll a').each(function() {
			$(this).text( $(this).text().replace(/show\sfewer/i, 'see all') );
		});

		if(text.match(/see\sall/i) != null) {
			$(this).text( text.replace(/see\sall/i, 'show fewer') );
			$more.slideDown(transitionDuration);
		} else {
			$(this).text( text.replace(/show\sfewer/i, 'see all') );
			$more.slideUp(transitionDuration);
		}

		return false;
	});

	// Make all video items equal height so they float correctly
	equalizeHeights('#searchResults .videos .items div')

	// Make all lyrical items equal height so they float correctly
	equalizeHeights('#searchResults .lyrics .items div');

	// Make event items equal height so they float correctly
	equalizeHeights('#searchResults .events .event');

	// Equalize elements' heights to the size of the largest in the bunch
	function equalizeHeights(jQueryExpression) {

		var height = 0;

		$(jQueryExpression).each(function() {
			height = ($(this).height() > height) ? $(this).height() : height;
		});

		$(jQueryExpression).height(height);
	}

	// Init modal overlay
	$('#searchResults .photos .items a, #searchResults .videos .items a').each(function() {
		if(!$(this).parent().hasClass('seeAll')) {
			$(this).modalOverlay();
		}
	});
}

/**
 * CONTROLLER: HOME
 */
function HomeController() {

	// If this is not the homepage, abort
	if(!$('#home').size()) return false;

	var videoId = 'vimeo';

	// If this is the video or photo page, make a minor adjustment for CSS's sake
	if($('#home>div.promo').size() > 0) {
		$('#home').parent().parent().addClass('promo');
	}

	// Center the photo container
	if($('#home>div.promo').size() > 0) {

		var $root = $('#home>div.promo>div>div');
		var containerHeight;

		if(!$.browser.msie) {
			containerHeight = 80;
			containerHeight += $('#home>div.promo h1').height();
			containerHeight += $('#home>div.promo>div>div').height();
		} else {
			containerHeight = $('#home>div.promo>div>div').height();
			containerHeight += $('#home>div.promo>div>a').height() + 2;
			if($('#home>div.promo h1').size() > 0) containerHeight += $('#home>div.promo h1').height() + 10;
			if($('#home>div.promo p').size() == 0) containerHeight += 19;
		}

		$('#home>div.promo>div').css({
			height: containerHeight
		});

		// IE = poop
		if($.browser.msie) {
			$('body').css('overflow-x', 'hidden');
			$('.promo>div>div>div>p:last-child').remove();
			centerPromoForIE();
		}
	}

	if($.browser.msie) $(window).resize(centerPromoForIE);

	function centerPromoForIE() {
		if(!$.browser.msie) return;
		var $o = $('#home>div.promo>div');
		$o.css({
			left: $(window).width()/2 - $o.width()/2,
			top: $(window).height()/2 - $o.height()/2
		});
	}

	// Insert Vimeo Video
	if($('#home>div.video').size() > 0) {

		var clipId = null;

		$('#home .video a').each(function() {
			if(this.href.indexOf('vimeo') != -1) clipId = this.href.match(/\d+$/)[0];
		});

		// No Vimeo URL found. Odd. The URL was probably inputted
		// incorrectly then. If that's the case let's just abort.
		if(!clipId) return false;

		$('#home .video img').unwrap().css('cursor', 'pointer');

		var $div = $('<div>');

		// Embed Flash
		$div.flash({
			src: 'http://vimeo.com/moogaloop.swf',
			width: 604,
			height: 320,
			allowscriptaccess: 'always',
			bgcolor: '#000000',
			allowfullscreen: true,
			flashvars: {
				clip_id: clipId,
				width: 604,
				height: 400,
				color: 'db2334',
				show_portrait: 0,
				show_byline: 0,
				show_title: 0,
				fullscreen: 1,
				js_api: ($.browser.msie) ? 0 : 1,
				js_onLoad: 'HomeController.initVideo',
				js_swf_id: videoId
			}
		});

		$div.find('embed').attr('id', videoId);

		var offset = $('#home .video img').offset();

		if($.browser.msie || navigator.userAgent.toLowerCase().indexOf('windows') != -1) {
			// Windows sux
			$('#home .video img').click(function() {
				$('#home .video img').after($div);
				try {
					document.getElementById('vimeo').api_play();
				} catch(e) {
					//alert(e);
				}
			});
		} else {
			$('#home .video img').after($div);
		}
	}

}

HomeController.initVideo = function() {

	$('#home .video img').fadeIn(250, function() {

		var $img = $(this);

		$img.click(function() {
			$img.animate({
				opacity: 0
			}, {
				duration: 250,
				complete: function() {
					$img.css('z-index', 0);
				}
			});

			document.getElementById('vimeo').api_play();
		})
	});

}


/**
 * GENERAL
 */
$(function() {

	// Search Box
	$('#header input.text').focus(function() {
		if($(this).attr('value').toLowerCase() == 'search') {
			$(this).attr('value', '');
		}
	}).blur(function() {
		if($(this).attr('value') == '') {
			$(this).attr('value', 'Search');
		}
	});

});


/**
 * Execute routines as soon as the DOM is ready.
 */
$(cssFixes);
$(flashReplacement);
//$(nullifyEmptyLinks);
$(HomeController);
$(NewsController);
$(AlbumController);
$(MiniPlayerController);
$(SearchController);