
var belaqua_review = {
	
	/**
	 * Returns the current reservations postage div.
	 */
	getPostage: function(currentBooking) {
		return $(currentBooking).parents('.reservation').find('.postage_opts_div');
	},
	
	/**
	 * Adds Address validation rules to the delivery address when 'Specify delivery address' is selected
	 */
	addDeliveryRules: function(target) {
		//Add required rules
		try
		{
			$(target).parent().find(".opt_required").each(function() {
				$(this).rules("add", {required:true});
			});
		}
		catch(e)
		{
			// doesn't work from the init function for some reason
		}
	},
	/**
	 * Removes validation rules from delivery address when 'Specify Delivery Address' is unselected
	 */
	removeDeliveryRules: function(target) {
		// Remove required rules
		$(target).parent().find(".opt_required").each(function() {
			$(this).rules("remove");
		});
	},
	/**
	 * Add email required rule
	 */
	addEmailRules: function(target) {
		try{
			$(target).parent().find(".email_field").rules("add", {required:true, email:true});
		}
		catch(e)
		{
			// doesn't work from the init function for some reason
		}
	},
	/**
	 * Remove email required rule
	 */
	removeEmailRules: function(target) {
		var obj = $(target).parent().find(".email_field");
		if (obj.rules()!=null) {
			obj.rules("remove");
		}
	},
	
	/**
	 * Recalculate the grand total in Order Summary box
	 */
	recalcTotal: function() {
		var total = 0;
		$('.subtotal-price').each(function() {
			var price = $(this).html();
			
			// Update the basket summary in the top right of the page.
			var wrapper = $(this).parents('.voucher');
			$('#step3-side .' + wrapper.attr('id') + ' .st_price').html(price);
			
			price = price.substring(1, price.length);
			total+=Number(price);
		});
		$('.voucher-price').each(function() {
			var price = $(this).html();
			price = price.substring(1, price.length);
			
			// Sometimes then the value of a voucher is displayed as a negative number.
			total-=Math.abs(Number(price));
		});
		$('.grand_total span').html("&pound;"+$.sprintf("%0.2f", total));
		var html = "Basket Total: &pound;"+$.sprintf("%0.2f", total);
		if(total == 0)
		{
			html = 'Basket';
		}
		$('.mybasket a').html(html);
	},
	
	/**
	 * Recalculate the subtotal in a Reservation box
	 */
	recalcSubtotal: function(target) {
		var calc_postage = !$(target).parents('.reservation-body').find('[value=evoucher]').is(':checked');
		if (target!=null) {
			var total = 0;
			$(target).find(".st_price").each(function() {
				if (($(this).hasClass('.postage_price') && calc_postage) || !$(this).hasClass('.postage_price')) {
					var price = $(this).html();
					price = price.substring(1, price.length);
					total+=Number(price);
				}
			});
			
			$(target).find(".subtotal-price").html("&pound;"+$.sprintf("%0.2f", total));
		}
		
		belaqua_review.recalcTotal();
	},
	/**
	 * Sets price of the postage
	 */
	setPostagePrice: function(target) {
		$('.postage_opts input').each(function() {
			if ($(this).is(":checked")) {
				//update price
				$(this).siblings('.st_price').html($(this).parent().find("label .amount").html());
			} else {
				$(this).siblings('.st_price').html('&pound;0.00');
			}
		});
		belaqua_review.recalcSubtotal(target);		
	},
	registerSuccess: function(data,status){
		$('#account-login').html(data);
	},
	loginSuccess: function(data,status){
		$('#account-login').html(data);
	},
	
	/**
	 * Copy the data over from one reservation to another
	 */
	copyReservationData: function(target, newTarget, id, newId, voucher)
	{
		//Copy text area over
		var textArea = target.find("textarea").val();
		
		//Copy common elements over
		newTarget.find("textarea").val(textArea);
		
		if (voucher)
		{
			//Replace all Voucher chars
			newTarget.addClass("voucher");
			newTarget.find('.datepicker-voucher').val(target.find('.datepicker-voucher').val());
			newTarget.find("#Contact"+newId+"FirstName").val(target.find("#Contact"+id+"FirstName").val());
			newTarget.find("#Contact"+newId+"LastName").val(target.find("#Contact"+id+"LastName").val());
			newTarget.find("#Address"+newId+"Line1").val(target.find("#Address"+id+"Line1").val());
			newTarget.find("#Address"+newId+"Line2").val(target.find("#Address"+id+"Line2").val());
			newTarget.find("#Address"+newId+"Line3").val(target.find("#Address"+id+"Line3").val());
			newTarget.find("#Address"+newId+"Town").val(target.find("#Address"+id+"Town").val());
			newTarget.find("#Address"+newId+"Locality").val(target.find("#Address"+id+"Locality").val());
			newTarget.find("#Address"+newId+"Postcode").val(target.find("#Address"+id+"Postcode").val());
			newTarget.find("#Contact"+newId + "Email").val(target.find("#Contact"+id + "Email").val());
			
			//Remove datepicker
			newTarget.find(".datepicker-voucher").removeClass("hasDatepicker");
			newTarget.find(".ui-datepicker-trigger").remove();
			
			//Copy over radio button values
			if(target.find('#Voucher' + id + 'DeliveryTypeMyAddr').attr('checked'))
			{
				newTarget.find('#Voucher' + newId + 'DeliveryTypeMyAddr').attr('checked', true);
			}
			if(target.find('#Voucher' + id + 'DeliveryTypeDelivery').attr('checked'))
			{
				newTarget.find('#Voucher' + newId + 'DeliveryTypeDelivery').attr('checked', true);
			}
			if(target.find('#Voucher' + id + 'DeliveryTypeEvoucher').attr('checked'))
			{
				newTarget.find('#Voucher' + newId + 'DeliveryTypeEvoucher').attr('checked', true);
			}
			
			if(target.find('#Voucher' + id + 'PostageStandard').attr('checked'))
			{
				newTarget.find('#Voucher' + newId + 'PostageStandard').attr('checked', true);
			}
			
			if(target.find('#Voucher' + id + 'PostageNextday').attr('checked'))
			{
				newTarget.find('#Voucher' + newId + 'PostageNextday').attr('checked', true);
			}
		}
		else 
		{
			//Hide date holder
			$("#spa-info .reservation:last .date-holder").hide();
			$("#spa-info .reservation:last .alt-date .end-date").before(new Option("Same as Reservation "+(newId), id));
			$("#spa-info .reservation:last .alt-date").val(id);
			$("#spa-info .reservation:last .alt-date").show();
			
			//Remove datepicker
			newTarget.find(".datepicker").removeClass("hasDatepicker");
			newTarget.find(".ui-datepicker-trigger").remove();
			
			// Copy the participant "type" radio fields.
			target.find('.participant input[type=radio]').each(function(i){
				if($(this).attr('checked'))
				{
					newTarget.find('.participant input[type=radio][value=' + $(this).val() + ']').attr('checked', true);
				}
			});
			
			// Copy the participant's details
			newTarget.find('.participant_title').val(target.find('.participant_title').val());
			newTarget.find('.participant_forename').val(target.find('.participant_forename').val());
			newTarget.find('.participant_surname').val(target.find('.participant_surname').val());
			
			// Copy the participant count
			newTarget.find('.participant_count input').val(target.find('.participant_count input').val());
		}
	},
	
	/**
	 * Updates a reservation id with new unique ids
	 *
	 */
	updateResId: function(newDiv, id, newId, voucher)
	{
		//replace
		newDiv = newDiv.replace("reservation_"+id, "reservation_"+newId);

		var regexp = new RegExp('/' + id, 'g');
		newDiv = newDiv.replace(regexp, "/"+newId);		
		newDiv = newDiv.replace("/edit_"+id, "/edit_"+newId);
		newDiv = newDiv.replace("copy_date_"+id, "copy_date_"+newId);
		newDiv = newDiv.replace("copy_date_"+id, "copy_date_"+newId);
		newDiv = newDiv.replace("date_preferred_"+id, "date_preferred_"+newId);
		newDiv = newDiv.replace("date_preferred_"+id, "date_preferred_"+newId);
		newDiv = newDiv.replace("date_alternative_"+id, "date_alternative_"+newId);
		newDiv = newDiv.replace("date_alternative_"+id, "date_alternative_"+newId);
		newDiv = newDiv.replace("requirement_"+id, "requirement_"+newId);

		var regexp = new RegExp('BookingDatePreferred' + id, 'g');
		newDiv = newDiv.replace(regexp, "BookingDatePreferred" + newId);
		
		regexp = new RegExp('BookingDateAlternative' + id, 'g');
		newDiv = newDiv.replace(regexp, "BookingDateAlternative" + newId);
		
		regexp = new RegExp('BookingRequirement' + id, 'g');
		newDiv = newDiv.replace(regexp, "BookingRequirement" + newId);
		
		regexp = new RegExp('Voucher' + id + 'Postage_', 'g');
		newDiv = newDiv.replace(regexp, "Voucher" + newId + 'Postage_');
		
		regexp = new RegExp('Voucher' + id + 'PostageStandard', 'g');
		newDiv = newDiv.replace(regexp, "Voucher" + newId + 'PostageStandard');
		
		regexp = new RegExp('Voucher' + id + 'PostageNextday', 'g');
		newDiv = newDiv.replace(regexp, "Voucher" + newId + 'PostageNextday');
		
		regexp = new RegExp('\\[' + id + '_postage\\]', 'g');
		newDiv = newDiv.replace(regexp, '[' + newId + '_postage]');
		
		regexp = new RegExp('Voucher' + id + 'DatePreferred', 'g');
		newDiv = newDiv.replace(regexp, 'Voucher' + newId + 'DatePreferred');
		
		regexp = new RegExp(id + '_date_preferred', 'g');
		newDiv = newDiv.replace(regexp, newId + '_date_preferred');
		
		regexp = new RegExp('Contact' + id + 'FirstName', 'g');
		newDiv = newDiv.replace(regexp, 'Contact' + newId + 'FirstName');
		
		regexp = new RegExp(id + '_first_name', 'g');
		newDiv = newDiv.replace(regexp, newId + '_first_name');
		
		regexp = new RegExp('Contact' + id + 'LastName', 'g');
		newDiv = newDiv.replace(regexp, 'Contact' + newId + 'LastName');
		
		regexp = new RegExp(id + '_last_name', 'g');
		newDiv = newDiv.replace(regexp, newId + '_last_name');
		
		regexp = new RegExp('Voucher' + id + 'GiftMessage', 'g');
		newDiv = newDiv.replace(regexp, 'Voucher' + newId + 'GiftMessage');
		
		regexp = new RegExp(id + '_gift_message', 'g');
		newDiv = newDiv.replace(regexp, newId + '_gift_message');
		
		regexp = new RegExp('Voucher' + id + 'DeliveryType_', 'g');
		newDiv = newDiv.replace(regexp, 'Voucher' + newId + 'DeliveryType_');
		
		regexp = new RegExp('Voucher' + id + 'DeliveryTypeMyAddr', 'g');
		newDiv = newDiv.replace(regexp, 'Voucher' + newId + 'DeliveryTypeMyAddr');
		
		regexp = new RegExp('Voucher' + id + 'DeliveryTypeDelivery', 'g');
		newDiv = newDiv.replace(regexp, 'Voucher' + newId + 'DeliveryTypeDelivery');
		
		regexp = new RegExp('Voucher' + id + 'DeliveryTypeEvoucher', 'g');
		newDiv = newDiv.replace(regexp, 'Voucher' + newId + 'DeliveryTypeEvoucher');
		
		regexp = new RegExp(id + '_delivery_type', 'g');
		newDiv = newDiv.replace(regexp, newId + '_delivery_type');
		
		regexp = new RegExp('Address' + id + 'Line1', 'g');
		newDiv = newDiv.replace(regexp, 'Address' + newId + 'Line1');
		
		regexp = new RegExp(id + '_line1', 'g');
		newDiv = newDiv.replace(regexp, newId + '_line1');
		
		regexp = new RegExp('Address' + id + 'Line2', 'g');
		newDiv = newDiv.replace(regexp, 'Address' + newId + 'Line2');
		
		regexp = new RegExp(id + '_line2', 'g');
		newDiv = newDiv.replace(regexp, newId + '_line2');
		
		regexp = new RegExp('Address' + id + 'Line3', 'g');
		newDiv = newDiv.replace(regexp, 'Address' + newId + 'Line3');
		
		regexp = new RegExp(id + '_line3', 'g');
		newDiv = newDiv.replace(regexp, newId + '_line3');
		
		regexp = new RegExp('Address' + id + 'Town', 'g');
		newDiv = newDiv.replace(regexp, 'Address' + newId + 'Town');
		
		regexp = new RegExp(id + '_town', 'g');
		newDiv = newDiv.replace(regexp, newId + '_town');
		
		regexp = new RegExp('Address' + id + 'Locality', 'g');
		newDiv = newDiv.replace(regexp, 'Address' + newId + 'Locality');
		
		regexp = new RegExp(id + '_locality', 'g');
		newDiv = newDiv.replace(regexp, newId + '_locality');
		
		regexp = new RegExp('Address' + id + 'Postcode', 'g');
		newDiv = newDiv.replace(regexp, 'Address' + newId + 'Postcode');
		
		regexp = new RegExp(id + '_postcode', 'g');
		newDiv = newDiv.replace(regexp, newId + '_postcode');
		
		regexp = new RegExp('Contact' + id + 'Email', 'g');
		newDiv = newDiv.replace(regexp, 'Contact' + newId + 'Email');
		
		regexp = new RegExp(id + '_email', 'g');
		newDiv = newDiv.replace(regexp, newId + '_email');
		
		regexp = new RegExp('Voucher' + id + 'Postage_', 'g');
		newDiv = newDiv.replace(regexp, 'Voucher' + newId + 'Postage_');
		
		regexp = new RegExp('Voucher' + id + 'PostageStandard', 'g');
		newDiv = newDiv.replace(regexp, 'Voucher' + newId + 'PostageStandard');
		
		regexp = new RegExp('Voucher' + id + 'PostageNextday', 'g');
		newDiv = newDiv.replace(regexp, 'Voucher' + newId + 'PostageNextday');
		
		regexp = new RegExp(id + '_postage', 'g');
		newDiv = newDiv.replace(regexp, newId + '_postage');
		
		regexp = new RegExp('participant_' + id, 'g');
		newDiv = newDiv.replace(regexp, 'participant_' + newId);
		
		regexp = new RegExp('participant_me_' + id, 'g');
		newDiv = newDiv.replace(regexp, 'participant_me_' + newId);
		
		regexp = new RegExp('participant_other_' + id, 'g');
		newDiv = newDiv.replace(regexp, 'participant_other_' + newId);
		
		regexp = new RegExp('ParticipantTitle' + id, 'g');
		newDiv = newDiv.replace(regexp, 'ParticipantTitle' + newId);
		
		regexp = new RegExp('title_' + id, 'g');
		newDiv = newDiv.replace(regexp, 'title_' + newId);
		
		regexp = new RegExp('ParticipantFirstName' + id, 'g');
		newDiv = newDiv.replace(regexp, 'ParticipantFirstName' + newId);
		
		regexp = new RegExp('first_name_' + id, 'g');
		newDiv = newDiv.replace(regexp, 'first_name_' + newId);
		
		regexp = new RegExp('ParticipantLastName' + id, 'g');
		newDiv = newDiv.replace(regexp, 'ParticipantLastName' + newId);
		
		regexp = new RegExp('last_name_' + id, 'g');
		newDiv = newDiv.replace(regexp, 'last_name_' + newId);
		
		regexp = new RegExp('participant_multiple_' + id, 'g');
		newDiv = newDiv.replace(regexp, 'participant_multiple_' + newId);
		
		regexp = new RegExp('BookingParticipantCount' + id, 'g');
		newDiv = newDiv.replace(regexp, 'BookingParticipantCount' + newId);
		
		regexp = new RegExp('participant_count_' + id, 'g');
		newDiv = newDiv.replace(regexp, 'participant_count_' + newId);
		
		if(voucher)
		{
			newDiv = newDiv.replace("<h3>YOUR GIFT VOUCHER "+(id+1)+".</h3>", "<h3>YOUR GIFT VOUCHER "+(newId+1)+".</h3>");
			for (i=0;i<5;i++)
			{
				newDiv = newDiv.replace("[Contact]["+id+"]", "[Contact]["+newId+"]");
			}
			for (i=0;i<5;i++)
			{
				newDiv = newDiv.replace("Contact_"+id+"_", "Contact_"+newId+"_");
			}
			for (i=0;i<12;i++)
			{
				newDiv = newDiv.replace("Address_"+id+"_", "Address_"+newId+"_");
			}
			for (i=0;i<2;i++)
			{
				newDiv = newDiv.replace("Email_"+id, "Email_"+newId);
			}
			for (i=1;i<=3;i++)
			{
				for (j=0;j<2;j++)
				{
					newDiv = newDiv.replace("delivery_type_"+i+"_"+id, "delivery_type_"+i+"_"+newId);
				}
			}
			for (i=0;i<8;i++)
			{
				newDiv = newDiv.replace("Vouchers_"+id+"_", "Vouchers_"+newId+"_");
				newDiv = newDiv.replace("data[Vouchers]["+id+"]", "data[Vouchers]["+newId+"]");
			}
		}
		else
		{
			newDiv = newDiv.replace("<h3>Reservation "+(id+1)+".</h3>", "<h3>Reservation "+(newId+1)+".</h3>");
		}
		
		return newDiv;
	},
	
	/**
	 * Returns the ID of the current reservation
	 */
	getReservationId: function(target)
	{
		var theId = target.attr("id");
		theId = theId.replace("reservation_", "");
		return theId;
	},
	
	/**
	 * Remove an item from the list
	 */
	removeItem: function(target)
	{
		//Disable all remove links
		$('.remove-but').each(function() {
			$(this).hide();
		});
		
		$('.change-but').hide();
		
		$(target).addClass("delete_target");
		var targetDiv = $(target).parents('.reservation');
		targetDiv.slideUp();
		//Call remove function
		jQuery.get($(target).attr('href'), null, belaqua_review.removeItemHtml);
	},
	
	/**
	 * Second part of remove function
	 */
	removeItemHtml: function()
	{
		var target = $(".delete_target");
		//Obtain div to remove
		var targetDiv = $(target).parents('.reservation');
		var targetId = belaqua_review.getReservationId(targetDiv);
		var fullId = $(target).attr("id");

		//Rename all higher reservation divs

		//remove booking
		$(".order-summary .reservation_"+targetId).remove();
		
		var count=0;
		$(".reservation").each(function() {
			var currentId = $(this).attr("id");
			currentId = currentId.replace("reservation_", "");
			currentId = Number(currentId);
			
			if (currentId!=targetId) {
				
				var newReservation = $(this).clone();
				var newHtml = newReservation.html();
				var voucher = $(this).hasClass("voucher");
				
				if (currentId!=count)
				{
					newHtml = belaqua_review.updateResId(newHtml, currentId, count, voucher);
					$(this).html(newHtml);
					newHtml = belaqua_review.copyReservationData(newReservation, $(this), currentId, count, voucher);
					$(this).attr('id', 'reservation_'+count);
					
					//renumber all other order summarys
					var ordSum = $(".order-summary li.reservation_"+currentId);
					var label = $(ordSum).find(".label").html();
					$(ordSum).removeClass("reservation_"+currentId);
					$(ordSum).addClass("reservation_"+count);
					if (label!=null)
					{
						label = label.replace(""+(currentId+1), count+1);
						$(ordSum).find(".label").html(label);
					}
				}
				count++;
			}
		})

		if(count == 0)
		{
			$('#submit_request_button').hide();
			$('#spa-info').append('<div class="reservation"><div class="reservation-header"><h3>You have no items selected</h3></div><div class="clear"></div></div>');
			
			// If we are on the reservations checkout page, and the customer now has no reservations but does
			// have vouchers, we should redirect to the voucher checkout page.
			if(window.location.pathname == '/customer_packages/review' && $('#step3-side .res_item').length > 0)
			{
				window.location = '/customer_packages/voucher';
			}
		}
		//Remove the div
		targetDiv.remove();
		//enable remove links
		$('.remove-but').each(function() {
			$(this).show();
		});
		
		$('.change-but').show();
		
		belaqua_review.init();
	},
	
	/**
	 * Duplicate an order
	 */
	duplicateItem:  function(obj)
	{
		//disable duplicate button
		$(".button.duplicate-but").hide();
		
		//Find last res
		var target = $("#spa-info .reservation:last");
		
		//Send call to server to duplicate
		jQuery.post($(obj).attr('href'), null, belaqua_review.duplicateItemHtml);
	},
	
	/** 
	 * Second part of duplication after call to server is complete
	 */
	duplicateItemHtml: function(obj, objtwo)
	{
		var dup_id = jQuery.trim(obj);
		//Find last res
		var target = $("#reservation_"+dup_id);
		
		var id = belaqua_review.getReservationId(target);
		var newId = $('.order-summary li').size()-1;
		//Build new div
		var newDiv = '<div class="reservation" style="display:none" id="reservation_'+newId+'">'+target.clone().html()+"</div>";
		
		//Test for voucher
		var voucher = target.hasClass("voucher");
		
		//Disable all date pickers
		$('.datepicker').datepicker('destroy'); 
		$('.datepicker-voucher').datepicker('destroy'); 
		
		newDiv = belaqua_review.updateResId(newDiv, Number(id), Number(newId), voucher);
		
		//Create copy.
		$("#spa-info .reservation:last").after(newDiv);
		var newTarget = $("#spa-info .reservation:last");

		belaqua_review.copyReservationData(target, newTarget, Number(id), Number(newId), voucher);
		
		belaqua_review.init();
		
		//Update order summary
		var ordSum = $(".order-summary li.reservation_"+dup_id);
		var line = ordSum.find(".label").html();
		line = line.replace(/([0-9])*/g, "");
		$(".order-summary li.res_item:last").after("<li class='reservation_"+newId+" res_item' ><span class='label'>"+line+" "+(newId+1)+"</span><span class='st_price'>"+ordSum.find("span.st_price").html()+"</span><div class=\"clear\"/</li>");

		//show
		newTarget.slideDown();
		
		//enable duplicate button
		$(".button.duplicate-but").show();
		
		$('.giftmessage').each(function(i){
			$(this).rules('add', {maxlength: 200});
			$(this).valid();
		});
		
		return false;
	},
	
	/**
	 * Setup all the defaults
	 */
    init: function() {
		if ($('#voucher_form').length>0) {
			//Validation
			$('#voucher_form').validate({
				debug: false,
				errorPlacement: function(error, element) {
					element.addClass("error");
				},
				submitHandler: function(form){
					$(form).find('input[type=submit]').attr('disabled', true);
					form.submit();
				},
				errorContainer: '.error_headline'
			});
			
			$('#voucher_form input[type=submit]').click(function(){
				$('#voucher-form-action').attr('name', $(this).attr('name'));
			});
			
			$('#voucher_form').submit(validateDeliveryType);
			$('#voucher_form').submit(validatePostage);
		}
		if ($('#reservation_form').length>0) {
			$('#reservation_form').validate({
				debug: false,
				errorPlacement: function(error, element) {
					element.addClass("error");
				},
				errorContainer: '.error_headline',
				submitHandler: function(form){
					$(form).find('input[type=submit]').attr('disabled', true);
					form.submit();
				}
			});
			
			// Because the form submission is ultimately done through JavaScript, then some browsers will not
			// include the button that was clicked on in the POST data.
			// This means we need to add a hidden field containing this.
			$('#reservation_form input[type=submit]').click(function(){
				$('#review-form-action').attr('name', $(this).attr('name'));
			});
		}

		//Init date picker
		$('.datepicker').datepicker({
			closeText: 'X',
			minDate: '+1d',
			maxDate: '+1y',
			showButtonPanel: false,
			dateFormat: 'dd/mm/yy',
			onClose: function(dateText, inst)
			{
				$(this.form).valid();
			}
		});
		
		$('.datepicker-voucher').datepicker({
			closeText: 'X',
			minDate: '+0d',
			maxDate: '+6m',
			showButtonPanel: false,
			dateFormat: 'dd/mm/yy'
		});
		
		var first=true;
		//Hide all but first date boxes.
		$('.date-holder').each(function() {
			if (!first) {
				$(this).hide();
			}
			first = false;
		});
		
		//Add click event handler to date dropdown
		$('.alt-date').change(function(e) {
			if ($(this).val()==-1) {
				//Show date fields
				$(this).next().show();
			} else {
				//hide
				$(this).next().hide();
			}

		});
		
		//Send to my Address
		var dom_myAddress = $('.delivery-type-fields input[value=my_addr]').unbind().click(function() {
			$(this.parentNode.parentNode).siblings('.delivery_address').slideUp(250);
			$(this.parentNode.parentNode).siblings('.email_address').slideUp(250);
			belaqua_review.getPostage($(this)).slideDown(250);
			$(this.parentNode.parentNode).siblings('.delivery_name').slideDown(250);
			
			belaqua_review.removeEmailRules(this.parentNode.parentNode);
			belaqua_review.removeDeliveryRules(this.parentNode.parentNode);
			addDeliveryNameRules($(this.parentNode.parentNode.parentNode));
			
			belaqua_review.recalcSubtotal($(this).parents(".reservation-body").find(".spa-info"));
			$('#voucher_form').validate();
		});

		//Specify a Delivery Address
		var dom_specifyAddress = $('.delivery-type-fields input[value=delivery]').click(function() {
			$(this.parentNode.parentNode).siblings('.delivery_address').slideDown(500);
			$(this.parentNode.parentNode).siblings('.delivery_name').slideDown(250);
			$(this.parentNode.parentNode).siblings('.email_address').slideUp(250);
			belaqua_review.getPostage($(this)).slideDown(250);
				
			belaqua_review.addDeliveryRules(this.parentNode.parentNode);
			belaqua_review.removeEmailRules(this.parentNode.parentNode);
			addDeliveryNameRules($(this.parentNode.parentNode.parentNode));
			
			belaqua_review.recalcSubtotal($(this).parents(".reservation-body").find(".spa-info"));
			$('#voucher_form').validate();
		});
		
		//Send E-Voucher
		var dom_evoucher = $('.delivery-type-fields input[value=evoucher]').click(function() {
			$(this.parentNode.parentNode).siblings('.delivery_address').slideUp(250);
			$(this.parentNode.parentNode).siblings('.delivery_name').slideUp(250);
			$(this.parentNode.parentNode).siblings('.email_address').slideDown(250);
			
			belaqua_review.getPostage($(this)).slideUp(250);
			
			belaqua_review.addEmailRules(this.parentNode.parentNode);
			belaqua_review.removeDeliveryRules(this.parentNode.parentNode);
			removeDeliveryNameRules($(this.parentNode.parentNode.parentNode));
			belaqua_review.recalcSubtotal($(this).parents(".reservation-body").find(".spa-info"));
			
			$('#voucher_form').validate();
		});
		
		//Check for selected email
		$('[value=evoucher]').each(function() {
			if ($(this).is(':checked')) {
				$(this.parentNode.parentNode).siblings('.email_address').slideDown(250);
				belaqua_review.getPostage($(this)).slideUp(250);
				$(this.parentNode.parentNode).siblings('.delivery_name').slideUp(250);
				belaqua_review.addEmailRules(this);
				removeDeliveryNameRules($(this.parentNode.parentNode.parentNode));
			}
		});
		
		$('[value=delivery]').each(function() {
			if ($(this).is(':checked')) {
				$(this.parentNode.parentNode).siblings('.delivery_address').slideDown(250);
				$(this.parentNode.parentNode).siblings('.delivery_name').slideDown(250);
				belaqua_review.addDeliveryRules(this);
				addDeliveryNameRules($(this.parentNode.parentNode.parentNode));
			}
		});
		
		$('[value=my_addr]').each(function() {
			if ($(this).is(':checked')) {
				$(this.parentNode.parentNode).siblings('.delivery_address').slideUp(250);
				$(this.parentNode.parentNode).siblings('.delivery_name').slideDown(250);
				addDeliveryNameRules($(this.parentNode.parentNode.parentNode));
			}
		});
		
		$(".datepicker-voucher").each(function() {
			$(this).rules("add", {required:true, date:true});
		});
		
		$(".datepicker-voucher").change(function() {
			$('#voucher_form').validate().element($(this));
		});
		
		$(".date_preferred:visible").each(function() {
			$(this).rules("add", {required:true, date:true});
		});
		
		
		//Postage options
		$('.postage_opts input').change(function() {
			belaqua_review.setPostagePrice($(this).parents(".spa-info"));
		});
		//Update subtotals
		$(".spa-info").each(function() {
			belaqua_review.setPostagePrice($(this));
		});
		
		belaqua_review.recalcTotal();
		
		//login button
		$('#submit-button').unbind().click(function() {
			
			$('#reservation_form').submit();
			$('#voucher_form').submit();
			return false;
		});

		$("#pay_button").unbind().click(function() {
			$('#voucher_form').submit();
			$('#reservation_form').submit();
		});
		$("#submit_request_button").unbind().live('click', function() {
			$('#reservation_form').validate();
			$('#voucher_form').validate();
			$('#reservation_form').submit();
		});

		$(".duplicate-but").unbind().click(function() {
			belaqua_review.duplicateItem(this);
			return false;
		});
		
		$(".remove-but").unbind();
		$(".remove-but").unbind().click(function() {
			belaqua_review.removeItem(this);
			return false;
		});
		
		$('.giftmessage').each(function(i){
			$(this).rules('add', {maxlength: 200});
			$(this).valid();
		});
		
		$('#reservation_form').submit(validateParticipantOptions);
		
		$('.participant_me').click(function(){
			$(this).parents('fieldset').find('.participant_name,.participant_count').slideUp('slow');
			removeParticipantRules($(this).parents('fieldset').find('.participant_name'));
			removeParticipantCountRules($(this).parents('fieldset').find('.participant_count'));
		});
		
		$('.participant_other').click(function(){
			$(this).parents('fieldset').find('.participant_name').slideDown('slow');
			$(this).parents('fieldset').find('.participant_count').slideUp('slow');
			addParticipantRules($(this).parents('fieldset').find('.participant_name'));
			removeParticipantCountRules($(this).parents('fieldset').find('.participant_count'));
		});
		
		$('.participant_multiple').click(function(){
			$(this).parents('fieldset').find('.participant_count').slideDown('slow');
			$(this).parents('fieldset').find('.participant_name').slideUp('slow');
			removeParticipantRules($(this).parents('fieldset').find('.participant_name'));
			addParticipantCountRules($(this).parents('fieldset').find('.participant_count'));
		});
		
		// For accessibility, then the participant name fields are always shown on page load, and are hidden with
		// JavaScript as appropriate.
		$('.participant_name,.participant_count').hide();
		
		$('.participant_other:checked').each(function(){
			$(this).parents('fieldset').find('.participant_name').show();
			addParticipantRules($(this).parents('fieldset').find('.participant_name'));
		});
		
		$('.participant_multiple:checked').each(function(){
			$(this).parents('fieldset').find('.participant_count').show();
			addParticipantCountRules($(this).parents('fieldset').find('.participant_count'));
		});
    }
};
$(document).ready(belaqua_review.init);
// IE fix for radio buttons
$(function () {
    if ($.browser.msie) {
        $('input:radio').click(function () {
            this.blur();
            this.focus();
        });
    }
});

function validateParticipantOptions()
{
	var res = true;
	$('.participant').each(function(i){
		if($(this).find(':checked').length == 0)
		{
			res = false;
			$(this).addClass('error');
		}
		else
		{
			$(this).removeClass('error');
		}
	});
	
	return res;
}

function validateDeliveryType()
{
	var res = true;
	$('.delivery-type-fields fieldset').each(function(i){
		if($(this).find(':checked').length == 0)
		{
			res = false;
			$(this).addClass('error');
		}
		else
		{
			$(this).removeClass('error')
		}
	});
	return res;
}

function validatePostage()
{
	var res = true;
	$('.delivery-type-fields fieldset').each(function(i){
		var postageOptions = $(this).parents().find('.postage_opts');
		if($(this).find(':checked').length > 0 && $(this).find(':checked').val() != 'evoucher' && $(this).find(':checked').val() != '')
		{
			if(postageOptions.find(':checked').length == 0)
			{
				postageOptions.addClass('error');
				res = false;
			}
			else
			{
				postageOptions.removeClass('error');
			}
		}
		else
		{
			postageOptions.removeClass('error');
		}
	});
	return res;
}

function addParticipantRules(fields)
{
	fields.find('input,select').each(function(i){
		$(this).rules('add', {required: true});
	});
}

function removeParticipantRules(fields)
{
	fields.find('input,select').each(function(i){
		$(this).rules('remove');
	});
}

function addParticipantCountRules(fields)
{
	fields.find('input').each(function(i){
		$(this).rules
		(
			'add',
			{
				required: true,
				digits: true,
				min: 1
			}
		);
	});
}

function removeParticipantCountRules(fields)
{
	fields.find('input,select').each(function(i){
		$(this).rules('remove');
	});
}

function addDeliveryNameRules(fields)
{
	fields.find('.delivery_name input').each(function(i){
		$(this).rules('add', {required: true});
	});
}

function removeDeliveryNameRules(fields)
{
	fields.find('.delivery_name input').each(function(i){
		$(this).rules('remove');
	});
}
