$(function() {

	// Bind return events to back buttons
	$('p.back a, a.back').bind('click', function(event) {
		window.history.back();
		event.preventDefault();
	});
	
	// Set up banner cycle 
	$('.banners .element').cycle({
		interval : 8000,
		keep : true,
		navigation : true,
		previous : false,
		next : false
	});
	
	// Set up tabs
	var tabs = $('#tabs');
	if(tabs.length) {
		
		function show(index) {
			
			$.each(liNodes, function(i) {
				if(index == i) {
					$(this).addClass('active');
				} else {
					$(this).removeClass('active');
				};
			});
			
			pages.hide();
			pages.eq(index).show();
			
		};
		
		// Custom addition -- remove pages that contain no elements with the class element
		tabs.find('.tab').each(function() {
			var page = $(this);
			if(!page.find('.element').length) {
				page.remove();
			};
		});
		
		var pages = tabs.find('.tab');
		if(pages.length) {
		
			var titles = tabs.find('h2'),
				liNodes = [];
		
			var ulNode = $('<ul class="navigation" />');
			ulNode.prependTo(tabs);
			
			titles.each(function(i) {
			
				var title = $(this);
				
				var liNode = $('<li />');
				liNode.appendTo(ulNode);
				liNodes.push(liNode);
				
				var aNode = $('<a />', {
					click : function(event) {
						show(i);
						event.preventDefault();
					},
					href : '#'
				});
				aNode.appendTo(liNode);
				
				$('<span>' + title.text() + '</span>').appendTo(aNode);
				
			});
			
			titles.remove();
			
			show(0);
			
		} else {
		
			tabs.remove();
		
		};
			
	};

});
