$(function() {
	$("section.gallery-bg").each(function() {
		var self = this;
		var items = $.makeArray($("article.image-gallery", this));
		var current = null;
		var T;
		
		if ($(this).attr('data-container')) {
			$(this).bind('update-title', function(_event) {
				var id = $(self).attr('data-container');
				
				$("#" + id).empty()
					.attr("class", "gallery-bg-title")

				if (!$(current).triggerHandler('gallery-set-markup', {
					prevClass: 'back',
					nextClass: 'next',
					openClass: 'open',
					container: $('#' + id)
				})) {
					$("#" + id).html("<a class='back' href='#' onclick='return false;'>&lt;</a> <a class='next' href='#' onclick='return false;'>&gt;</a> <span class='title'></span> <a href='#' class='open'>Learn more</a>");
					if (!$(current).triggerHandler('gallery-set-title', { container: $('#' + id + ' .title') }))
						$("#" + id + " .title").text($(current).attr('data-title'));
				}
				
				$("#" + id + " .open").click(function() {
					var g = $(current).attr('data-record-id');
					var f = window['gallery_' + g];
					f(0);
					return false;
				});

				if (items.length == 1) {
					$("#" + id + " .back, #" + id + " .next").remove();
				} else {
					var C = arguments.callee;
					$("#" + id + " .next").click(function() {
						clearTimeout(T);
						C();
					});
					$("#" + id + " .back").click(function() {
						clearTimeout(T);
						var P = items.pop();
						items.unshift(P);
						P = items.pop();
						items.unshift(P);
						C();
					});				
				}
			});
		}
		
		var animationIsPaused = false;
		$('body').bind('pause', function() { animationIsPaused = true; }).bind('play', function() { animationIsPaused = false; });
		
		(function() {
			if (!animationIsPaused) {
				if (!$(items[0]).is('[data-image-loaded=true]')) {
					var img = new Image();
					var fn = arguments.callee;
					var item = items[0];
					img.onload = function() {
						item.setAttribute('data-image-loaded', 'true');
						item.style.backgroundImage = 'url(' + item.getAttribute('data-image-url') + ')';
						fn();
					}
					img.src = item.getAttribute('data-image-url');
					return;
				}
				var next = items.shift();
				if (!current) {
					$(next).addClass('current');
				} else {
					$(current).addClass("animating").animateClass("current", "", { complete: function() { $(this).removeClass("animating"); } });
					$(next).animateClass("", "current");
				}
				items.push(next);
				current = next;
			
				$(self).triggerHandler('update-title');
			}
			if (items.length > 1)
				T = setTimeout(arguments.callee, 5000);
		})();
	});
});

		

