$(document).ready(function(){
	$('p#enterDeliveryAddress input').change(function() {
		var f = $('fieldset#deliveryAddress');
		this.checked ? f.slideDown() : f.slideUp();
		$('p#enterDeliveryAddress').toggleClass('expanded', this.checked);
		return false;
	});

	$('.newAddressBlock').not('checked').one('click', function() {
		$(this).addClass('expanded');
		$(this).children('input').click();
		return false;
	});

	$('div.component').each(function() {
		var container = $(this);
		var extras = $(this).find('.extra');
		var radio = $(this).find('input:radio');

		if (!radio.attr('checked')) {
			extras.hide();
		}
		else {
			container.addClass('selected');
		}

		radio.click(function() {
			$('div.component.' + this.name + ' .extra').slideUp(); // hide all other extras *of this type*
			$('div.component.' + this.name).removeClass('selected');
			extras.slideDown();
			container.addClass('selected');
			return true;
		});
	});

	if ($('#priceGrid').size()) {
		$('#priceGrid tbody td').click(function () {
			$('#priceGrid td.selected').removeClass('selected');
			$(this).addClass('selected');
			$(this).find('input').attr('checked', true);
		});

		// Number the tbodies.
		$('#priceGrid tbody').each(function (i) {
			$(this).attr('num', i);
		});

		var getActiveTbody = function () {
			return $('#priceGrid tbody:visible').attr('num');
		};

		var checkLinks = function () {
			var num = getActiveTbody();
			$('a#prevWeek').toggle(num > 0);
			$('a#nextWeek').toggle(num < $('#priceGrid tbody').size() - 1);
		};

		$('a#prevWeek, a#nextWeek').click(function () {
			var num = getActiveTbody();
			(this.id == 'prevWeek') ? num-- : num++;
			$('#priceGrid tbody').hide();
			$('#priceGrid tbody[num=' + num + ']').show();
			checkLinks();
			return false;
		});

		$('#priceGrid tbody').hide();
		var selected = $('#priceGrid td.selected');
		if (selected.size()) {
			selected.parents('tbody').show();
		}
		else {
			$('#priceGrid tbody:first').show();
		}
		checkLinks();
	}
});

