available = new Array();

var form_submitted = false;

function validatePaymentForm() {
	var errors = "";
	var err_head = 'The following errors exist on this form:\n';
	var emailRx = /^.+\@.+\..+$/;

	if (!$F('name')) {
		errors += ' - please enter the name of the card holder\n';
	}

	if (!$F('card_number') || !mod10Check($F('card_number'))) {
		errors += ' - please enter a valid credit card number\n';
	}

	if (!$F('expiry_month') || !$F('expiry_year')) {
		errors += ' - please enter an expiry month and year\n';
	}

	if ($F('card_type') == 'Solo' && !$F('issue_number')) {
		errors += ' - please enter the issue number\n';
	}

	if (!$F('cv2')) {
		errors += ' - please enter the security number\n';
	}

	if (!$F('amount')) {
		errors += ' - please enter an amount\n';
	}

	if (!$F('bill_addr_1')) {
		errors += ' - please enter the first line of the billing address\n';
	}

	if (!$F('bill_city')) {
		errors += ' - please enter the billing address city\n';
	}

	if (!$F('bill_state')) {
		errors += ' - please enter the billing address county/state\n';
	}

	if (!$F('bill_post_code')) {
		errors += ' - please enter the billing address postcode/zip\n';
	}
	
	if (!$F('bill_tel')) {
		errors += ' - please enter a contact telephone number\n';
	}
	
	if (!$F('bill_email').match(emailRx)) {
		errors += ' - please enter a valid email address\n';
	}

	if ($F('bill_email') != $F('bill_confirm_email')) {
		errors += ' - please check and confirm your email address\n';
	}

	$$('input[name^="child_age"]').pluck('value').each(function(age) {
		if ( !age.match(/^\d+$/) ) {
			errors += ' - please enter a valid age for all children\n';
			throw $break;
		}
	});

	// has form been submitted already...
	if (errors == "" && form_submitted) {
		errors = " - form already submitted, please wait\n";
	}
	
	// return if we have any errors after displaying them
	if (errors != "") {
		alert(err_head + errors);
	} else {
		form_submitted = true;
	}

	return (errors == "");
}

function showHideIssueNo(card_type) {

	if (card_type == 'Switch' || card_type == 'Solo') {
		$('issue_number_row').show();
	} else {
		document.form.issue_number.value = '';
		$('issue_number_row').hide();
	}

}

function format_iso_date(date) {
	if (!date.match(/^\d{4}-\d{2}-\d{2}$/))
		return;

	var dsplit = date.split("-");
	var d = "";
	date = new Date(dsplit[0], dsplit[1] - 1, dsplit[2], 0, 0, 0, 0);
	switch (date.getDay()) {
		case 0: d = "Sun"; break;
		case 1: d = "Mon"; break;
		case 2: d = "Tue"; break;
		case 3: d = "Wed"; break;
		case 4: d = "Thu"; break;
		case 5: d = "Fri"; break;
		case 6: d = "Sat"; break;
	}
	
	d += " " + dsplit[2];
	
	switch (date.getMonth()) {
		case 0: d += " Jan"; break;
		case 1: d += " Feb"; break;
		case 2: d += " Mar"; break;
		case 3: d += " Apr"; break;
		case 4: d += " May"; break;
		case 5: d += " Jun"; break;
		case 6: d += " Jul"; break;
		case 7: d += " Aug"; break;
		case 8: d += " Sep"; break;
		case 9: d += " Oct"; break;
		case 10: d += " Nov"; break;
		case 11: d += " Dec"; break;
	}
	
	return d;
}
function format_time(time) {
	if (!time.match(/^\d{2}:\d{2}:\d{2}$/))
		return;

	var ampm = "";
	var tp = time.split(":");
	if (tp[0] > 12) {
		tp[0] = tp[0] - 12;
		ampm = "pm";
	} else {
		ampm = "am";
	}

	return tp[0] + ":" + tp[1] + " " + ampm;

}

var booking_template = new Template('<div id="booking_#{slot_id}"><div class="bookingleft"><span class="bold">#{slot_type}</span> on <span class="bold">#{slot_date}</span> @ <span class="bold">#{slot_time}</span></div><div class="bookingright"><a href="#" onclick="delBooking(#{slot_id}); return false;"><img src="images/buttons/santa/remove.gif" alt="remove" width="60" height="18" border="0" /></a></div> <div class="divclear">&nbsp;</div></div>');

var alt_time_template = new Template('<li><a href="#" onclick="reserveNewTime(\'#{time}\'); return false;">#{time}</a></li>');


function findBookings() {
	if (!$F('babies').match(/^\d+$/) || !$F('children').match(/^\d+$/) || !$F('adults').match(/^\d+$/)) {
		hidePopup();
		$('inline_alt_popup').show();
		$('inline_visitor_error').show();
		return;
	}

	if ( Number($F('babies')) + Number($F('children')) + Number($F('adults')) <= 0 ) {
		hidePopup();
		$('inline_alt_popup').show();
		$('inline_visitor_error').show();
		return;
	}

	if ( Number($F('babies')) + Number($F('children')) > 50 ) {
		hidePopup();
		$('inline_alt_popup').show();
		$('inline_max_error').show();
		return;
	}
	
	if (!$F('date').match(/^\d{1,2}\/\d{1,2}\/\d{4}$/)) {
		hidePopup();
		$('inline_alt_popup').show();
		$('inline_date_error').show();
		return;
	}

	new Ajax.Request('santa/', {
		method: 'post',
 		parameters: {
			fa: 'ajax_f_s',
			date: $F('date'),
			time_hour: $F('time_hour'),
			time_minute: $F('time_minute'),
			babies: $F('babies'),
			children: $F('children'),
			adults: $F('adults')
		},
		onLoading: function() {	$('spinner').show(); },
		onSuccess: function(transport) {
			var response_lines = transport.responseText.split("\n");
			if (response_lines[0] == 'RESERVED') {
				for ( var i = 1; i < response_lines.length; i++ ) {
					var args = response_lines[i].split(",");
					addBooking(args[0], args[1], args[2], args[3]);
				}
				$('bookings_wrapper').style.display = 'inline';
			} else if (response_lines[0] == 'ALTERNATIVES') {
				if ( response_lines.length == 1 ) {
					hidePopup();
					$('inline_no_alternatives').show();
					$('inline_alt_popup').show();
				} else {
					$('inline_alt_ul').innerHTML = "";
					for ( var i = 1; i < response_lines.length; i++ ) {
						var dp = response_lines[i].split(" ");
						var tp = dp[1].split(":");
						var new_time = tp[0] + ":" + tp[1];

						new_time_li = alt_time_template.evaluate({time: new_time});
						$('inline_alt_ul').update($('inline_alt_ul').innerHTML + new_time_li);
					}
					hidePopup();
					$('inline_alt_list').show();
					$('inline_alt_popup').show();
				}
			} else if (response_lines[0] == 'TOOLATE') {
			    hidePopup();
				$('inline_too_late').show();
				$('inline_alt_popup').show();
			} else {
				// No nothing. Bad response from server.
			}

		},
		onComplete: function() { $('spinner').hide(); }
	});
}

function addBooking(slot_id, date, time, type) {
	if ( slot_id == "" ) { return; }

	date = format_iso_date(date);
	time = format_time(time);
	
	new_booking = booking_template.evaluate({slot_id: slot_id, slot_date: date, slot_time: time, slot_type: type});
	$('bookings').update($('bookings').innerHTML + new_booking);

	if ($$('div[id^="booking_"]').length > 0) {
		$('bookings_wrapper').style.display = 'inline';
	} else {
		$('bookings_wrapper').style.display = 'none';
	}
}

function delBooking (slot_id) {
	new Ajax.Request('santa/', {
		method: 'post',
 		parameters: { fa: 'ajax_d_s', id: slot_id },
		onLoading: function() {	$('spinner').show(); },
		onSuccess: function() { $('booking_' + slot_id).remove(); },
		onComplete: function() {
			$('spinner').hide();
			if ($$('div[id^="booking_"]').length > 0) {
				$('bookings_wrapper').style.display = 'inline';
			} else {
				$('bookings_wrapper').style.display = 'none';
			}
		}
	});
}

function hidePopup () {
	$$('div[id^="inline_"]').invoke('hide');
}

function reserveNewTime(new_time) {
	hidePopup();

	var tp = new_time.split(":");
	$('time_hour').value = tp[0];
	$('time_minute').value = tp[1];

	findBookings();
}



function checkout (url) {
	if ( $$('div[id^="booking_"]').length > 0 ) {

		// Check at least one adult is in the booking
		var adults = false;
		$$('div[id^="booking_"]').pluck('innerHTML').each(function(x) {
			if (x.match(/adult/))
				 adults = adults || true;
			else
				adults = adults || false;
		});

		if (!adults) {
			alert("Please add at least one adult to the booking.");
			return false;
		} else {
			window.location.href=url;
		}
	}
}

function removeAllBookings () {
	$('removeAllForm').submit();
}

function loadAvailableDays () {
	new Ajax.Request('santa/', {
		method: 'post',
 		parameters: { fa: 'ajax_a_d' },
		onSuccess: function(transport) {
			var lines = transport.responseText.split("\n");
			for ( var i = 0; i < lines.length; i++ ) {
				available.push(lines[i]);
			}
		}
	});
}

function bookingFormSetup () {
	new Draggable($('inline_alt_popup'));
	$('date').value='';

	if ($$('div[id^="booking_"]').length > 0) {
		$('bookings_wrapper').style.display = 'inline';
	}

	Event.observe($('date'), 'click', function () {
		new Ajax.Request('santa/', {
			method: 'post',
	 		parameters: { fa: 'ajax_a_d' },
			asynchronous: false,
			onSuccess: function(transport) {
				var lines = transport.responseText.split("\n");
				available = new Array();
				for ( var i = 0; i < lines.length; i++ ) {
					var dp = lines[i].split("-");
					available.push(new Date(dp[0], dp[1]-1, dp[2]));
				}
			}
		});

		var cal = new CalendarDateSelect('date', {
			show_now: null,
			buttons: null,
			show_nav: null,
			minute_interval: 20,
			loadData: function () {
				$data = $H({
					start_date: new Date(Date.UTC(2009, 11, 5)),
					end_date: new Date(Date.UTC(2009, 11, 22)),
					available: available
				});
				return $data;
			}
		});
		
		cal.navMonth(11);
		cal.navYear(2009)
	});
}
