window.addEvent('domready',function() {
																		
	registrationFormSent = false; 
	// global variable to track whether reg details have been sent (emails) 
	// a user can try payment again if necessary, skipping this stage
	
	var regForms = $$('form.regForm');
	
	if(regForms.length > 0) {
		regForms.each(function(el) {
			new FormValidator.Inline(el);
			
			if(!el.hasClass('noAjax')) {
				el.addEvent('submit', function(e) {
					e.stop();						   
				});
			}
		});
	}
	
	if($('billingPaymentType') && $('fee')) {
		// Logic to change how much the user pays (deposit or full amount)
		var billSelect = $('billingPaymentType');
		var billAmount = $('billingAmount');
		var deposit    = billAmount.value;
		var fee        = $('fee');
		
		billSelect.addEvent('change',function(e) {
			if(billSelect.value == "Deposit Only") {
				billAmount.value = deposit;
			}
			else {
				if(fee.value != '' && isNumber(fee.value)) {
				billAmount.value = fee.value;
				billAmount.highlight();
			}
			else {
				billSelect.getElement('option[value^=Deposit]').selected = true;
				alert('Please check the value you entered for \'Inclusive Fee\' - If the fee was 200 pounds, you would enter \'200.00\' in the box, without quotation marks.');	
				}
			}
		});
	}
	
	// Make the company name fieldset and label / input to inject if we need it
	var companyName = new Element('fieldset', {
		'class': 'clearfix spacer',
		'id': 'fldsCompany'
	});
	
	companyName.adopt(new Element('label', {
		'for': 'company',
		'html': 'Company Name: ',
		'class': 'required'
	}));
	
	companyName.adopt(new Element('input', {
		'name': 'company',
		'type': 'text',
		'id': 'company',
		'size': 30
	}));
	// end company name
		
	if($('submitForms')) {
		
		buildBillingSameEvents();
		
		if($('bookingType')) {
			$('bookingType').addEvent('change',function() {
				if($('bookingType').value !== 'Private Booking') {
					if($('formPayment')) {
						// store a copy of the payment form
						formPaymentObj = $('formPayment').clone(true,true).cloneEvents($('formPayment'));
						// change the step number of the t&c section
						$('numberTermsConditions').innerHTML = '4';		
						// remove the payment form
						$('formPayment').destroy();
					}
					if(!$('fldsCompany')) {
						// inject the companyName element
						companyName.inject('fldsUserLastName','after');
						// remove spacer from fldsUserLastName
						$('fldsUserLastName').removeClass('spacer');
					}
				}
				else {
					if(!$('formPayment')) {
						$('numberTermsConditions').innerHTML = '6';	
						formPaymentObj.inject($('bookingConfirmation'),'after');
						
						buildBillingSameEvents(); // Add checkbox events again
					}
					// if fldsCompany already exists, clone it and overwrite our default element
					if($('fldsCompany')) {
						companyName = $('fldsCompany').clone(true,true);
						$('fldsCompany').destroy();
						// add spacer class to fldsUserLastName
						$('fldsUserLastName').addClass('spacer');
					}
				}
			});
		}
		
		$('submitForms').addEvent('submit',function(el) {
													
			el.stop();
			
			var passedValidation = true;
			
			regForms.each(function(el) {
				if(!passedValidation) return;
				passedValidation = el.validate();
			});
			
			if(passedValidation) {
				
				// If T&C's checkbox exists, make sure it's true
				if($('termsConditionsCheck')) {
					if(!$('termsConditionsCheck').checked) {
						alert('You must accept our Terms & Conditions before continuing');
						return;
					}
				}
				
				////////////////////////
	
 				var formPayment = $('formPayment');
				
				if($('bookingConfirmation')) {
					
					var bookingConfirmation  = $('bookingConfirmation');
					var dataObject           = {};
					
					// Don't deliver the registration e-mails twice if the user needs to retry submitting their payment info
					if(registrationFormSent) {
						processPaymentForm();
						return;
					}
					
					regForms.each(function(regForm) {
											  
						dataObject[regForm.id] = {};
						
						var labels = regForm.getElements('label');
						
						labels.each(function(label,i) {
											 
							if(!label.hasClass('ignore')) {
							// ignore labels which have the class 'ignore'
							
								var fieldLabel   = '';
								var fieldValue   = '';
								var fieldHeading = '';
								
								fieldLabel = trim(label.innerHTML);
												 
								var forAttr = label.getProperty('for');
											
								if(forAttr) {
									// if the for attribute exists, this has a corresponding input, get the value				
									var input = regForm.getElement('[name^=' + forAttr + ']');
									
									if(input.getProperty('type') == 'checkbox') {
										// concatenate the checkbox values
										var checkboxes = regForm.getElements('[name^=' + forAttr + ']');
										var concatValues = new Array();
										checkboxes.each(function(checkbox) {
											if(checkbox.checked) {
												concatValues.push(checkbox.value);
											}
										});
										if(concatValues.length > 0) {
											fieldValue = concatValues.join(', ');
										}
									}
									else {
										fieldValue = input.value;
									}
								}
								else {
									forAttr      = 'heading' + i;
									fieldHeading = label.hasClass('title') ? 'title' : 'subtitle';
								}
								
								dataObject[regForm.id][forAttr] = {
									title: fieldLabel,
									value: fieldValue,
									heading: fieldHeading
								};
							}
						});
					});
					
					new Request.JSON({
						url: 'https://www.silkstreethotseven.co.uk/mailer/send-registration.php',
						data: dataObject,
						noCache: true,
						onRequest: function() {
							$('submitForms').addClass('loading');
							$('submitFormsButton').disabled = 1;
							$('status').innerHTML = 'Processing booking...';
						},
						onSuccess: function(jsonObj,responseText) {
							if(!jsonObj.errors) {
								$('submitForms').removeClass('loading');
								
								registrationFormSent = true;
								
								processPaymentForm();
							}
							else {
								$('status').innerHTML = 'Error: ';
								
								jsonObj['errors'].each(function(error) {
									$('status').appendText(error + ' ');
								});
								
								$('submitForms').removeClass('loading');
								$('submitFormsButton').disabled = 0;
							}
						}
					}).send();
					
				}
				else {
					
					processPaymentForm();
					
				}
					
				////////////////////////
				
			}
		});
	}
	
	function buildBillingSameEvents() {		
		$('registrationBillingSame').addEvent('click',function(e) {
															   																																
			if(!$('bookingConfirmation').validate()) {
								
				$('registrationBillingSame').checked = false;
				
				return false;
			}
						
			if($('registrationBillingSame').checked) {
				
				var labels = $('userContactDetails').getElements('label');
				
				labels.each(function(label) {
					var forAttr  = label.getProperty('for');
					
					if(forAttr) {
						if($('userContactDetails').getElement('input[name=' + forAttr + ']')) {
							var inputVal = $('userContactDetails').getElement('input[name=' + forAttr + ']').value;
							
							forAttr = forAttr.substr(4);
							
							$('billingDetails').getElement('input[name$=' + forAttr + ']').value = inputVal;
						}
					}
				});
			}
		});
	}
	
	// Process payment
	
	function processPaymentForm() {
		
		$('status').innerHTML = 'Processing payment...';
			
		if($('formPayment')) {
			new Request.JSON({
				url: 'https://www.silkstreethotseven.co.uk/wp-content/plugins/paypal-pro/paypal-pro.php',
				method: 'post',
				noCache: true,
				data: {
					'useSandbox'          : document.getElement('[name=useSandbox]') ? document.getElement('[name=useSandbox]').checked : '',
					'billingFirstName'    : document.getElement('[name=billingFirstName]').value,
					'billingLastName'     : document.getElement('[name=billingLastName]').value,
					'billingAddress1'     : document.getElement('[name=billingAddress1]').value,
					'billingAddress2'     : document.getElement('[name=billingAddress2]').value,
					'billingTownCity'     : document.getElement('[name=billingTownCity]').value,
					'billingCounty'       : document.getElement('[name=billingCounty]').value,
					'billingPostCode'     : document.getElement('[name=billingPostCode]').value,
					'billingCCType'       : document.getElement('[name=billingCCType]').value,
					'billingCCNum'        : document.getElement('[name=billingCCNum]').value,
					'billingCCIssue'      : document.getElement('[name=billingCCIssue]').value,
					'billingEmail'        : document.getElement('[name=billingEmail]').value,
					'billingCCStart_mm'   : document.getElement('[name=billingCCStart_mm]').value,
					'billingCCStart_yyyy' : document.getElement('[name=billingCCStart_yyyy]').value,
					'billingCCExp_mm'     : document.getElement('[name=billingCCExp_mm]').value,
					'billingCCExp_yyyy'   : document.getElement('[name=billingCCExp_yyyy]').value,
					'billingCCCvc'        : document.getElement('[name=billingCCCvc]').value,
					'billingAmount'       : document.getElement('[name=billingAmount]') ? document.getElement('[name=billingAmount]').value : '',
					'billingInvoice'      : document.getElement('[name=billingInvoice]') ? document.getElement('[name=billingInvoice]').value : '',
					
					'action'              : 'ppp_form',
					'submitpayment'       : 'true'
				},
				onRequest: function() {
					$('submitForms').addClass('loading');
				},
				onSuccess: function(jsonObj,responseText) {
					if(!jsonObj.errors) {
						$('status').innerHTML = 'Payment Complete!';
						$('submitForms').removeClass('loading');
						
						/* Redirect to thanks page */
						var backHome = function() { window.location = '/payment-complete' }	
						
						var countdown = 3;
						
						var currStatus = $('status').innerHTML;
						
						(function(){
							$('status').innerHTML = currStatus + ' (' + countdown + ')';
							countdown = countdown > 1 ? countdown - 1 : countdown;
						}).periodical(1000);
						
						backHome.delay(4000);
					}
					else {
						$('status').innerHTML = 'Error: ';
						
						jsonObj['errors'].each(function(error) {
							$('status').appendText(error + ' ');
						});
						
						$('submitForms').removeClass('loading');
						$('submitFormsButton').disabled = 0;
					}
				}
			}).send();
		}
		else {
			// No payment form was rendered - assume no payment is required and forward to payment complete page	
			
			$('status').innerHTML = 'Booking Complete!';
			$('submitForms').removeClass('loading');
			
			/* Redirect to thanks page */
			var backHome = function() { window.location = '/booking-complete' }	
			
			var countdown = 3;
			
			var currStatus = $('status').innerHTML;
			
			(function(){
				$('status').innerHTML = currStatus + ' (' + countdown + ')';
				countdown = countdown > 1 ? countdown - 1 : countdown;
			}).periodical(1000);
			
			backHome.delay(4000);
		}
	}
	
});

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function isNumber(str) {
	isPrice = /^\d+\.\d{2}$/;
	return isPrice.test(str);
} 
