/**
 * Process booking form
 *
 * @param string $prefix is fields have a prefix this should be it
 */
function processBookingFromForm(button, prefix)
{
	if((prefix === null) || (prefix === undefined)) {
		prefix = '';
	}

	// Hide any messages from previous submit, if any
	$('div.error').hide();
	$('input.error').removeClass('error');
	$('#eventstatus').hide();

	var fieldNames = ['firstName', 'lastName', 'email', 'emailConfirmation', 'phoneHome', 'phoneWork', 'mobile', 'state', 'privacyPolicyAcceptance'];
	var requiredFieldNames = ['firstName', 'lastName', 'email', 'emailConfirmation', 'state', 'privacyPolicyAcceptance'];

	var fieldErrors = {
		firstName:	'Please enter your first name',
		lastName:	'Please enter your last name',
		email:		'Please enter your email address',
		emailConfirmation: 'Please confirm your email address',
		state:	'Please enter you state',
		privacyPolicyAcceptance: 'Sorry, you must accept the privacy policy to continue'
	};

	var values = {};
	var valid = true;

	for (var key in fieldNames) {
		// Get around js flaw; http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
		if (fieldNames.hasOwnProperty(key)) {
			var fieldName = fieldNames[key];
			if (fieldName == 'state') {
				var field = $('#eventinterest select[name="'+prefix+fieldName+'"]');
			} else {
				var field = $('#eventinterest input[name="'+prefix+fieldName+'"]');
			}
			if (field.attr('type') == 'checkbox') {
				values[fieldName] = field.attr('checked') ? 1 : '';
			} else {
				if (field.val() == field.attr('title')) {
					values[fieldName] = '';
				} else {
					values[fieldName] = $.trim(field.val());
				}
			}
			if (values[fieldName] == '' && $.inArray(fieldName, requiredFieldNames) != -1) {
				if (fieldName == 'privacyPolicyAcceptance') {
					displayError(fieldName, fieldErrors[fieldName]);
				} else {
					//displayError(fieldName, fieldErrors[fieldName]);
					displayRequiredFieldsError(fieldName);
				}
				valid = false;
			} else {
				if (fieldName == 'emailConfirmation' && values['emailConfirmation'] != values['email']) {
					displayError('emailConfirmation', 'Sorry, email confirmation did not match. Please check your input and try again.');
					valid = false;
				}
			}
		}
	}

	if (!isEmpty(values['email'])) {
		var emailRegex = new RegExp(/^[^\][()<>@.,;\:"\0-\40\177]+(\.[^\][()<>@.,;\:"\0-\40\177]+)*@[^\][()<>@.,;\:"\0-\40\177]+(\.[^\][()<>@.,;\:"\0-\40\177]+)+$/);
		if (!emailRegex.test(values['email'])) {
			displayError('email', 'Please enter a valid email address');
			$('#eventinterest input[name="email"]').get()[0].focus();
			valid = false;
		}
	}

	if (isEmpty($('#'+prefix+'eventId').val())) {
		displayError('eventId', 'Please select the event you wish to attend');
		valid = false;
	}

	if (isEmpty(values['phoneHome']) && isEmpty(values['phoneWork']) && isEmpty(values['mobile'])) {
		//displayError('phoneHome', 'Please enter at least one contact number');
		displayRequiredFieldsError('phoneHome');
	}

	// Add any extra validation here. Set valid = false if not valid.
	//
	//
	// 


	if (valid) {
		$(button).attr('disabled', true);
		var postData = {
			eventId:		$('#'+prefix+'eventId').val(),
			tickets:		1
		}
		var q = $.parseQuery();	
		if (q.pId) {
			postData['promoterId'] = q.pId;
		}
		for (var key in fieldNames) {
			if (fieldNames.hasOwnProperty(key)) {
				var fieldName = fieldNames[key];
				postData['customer_'+fieldName] = values[fieldName]
			}
		}

		$.ajax({
				url: BOOKING_URL,
				data: postData, 
				success: function(data, textStatus) {
					$(button).removeAttr('disabled');
					if (!isValid(data)) {
						alert('Sorry, there was a problem processing your request. Please try again.');
						return false;
					}
					// Handle response
					switch (data.status) {
						case 'duplicate':
							$('#eventstatus').html('Sorry, you are already booked into this event').show();
							break;
						case 'full':
							$('#eventstatus').html('Sorry, this event has been booked out. There are no more tickets available.').show();
						case 'error':
							// Display errors from server side validation. Add any extra stuff you want here.
							for (var key in data.errors.customer) {
								$('#'+key+'_error').html(data.errors.customer[key]).show();
							}
							break;
						case 'failed':
							// Not necessary yet as you are not accepting paymetn
							break;
						case 'booked':
							// Success! Do something...
							// Booking id if you need it
							var bookingId = data.booking.bookingId;
							$('#eventinterest').html('<h1>Thank you!</h1><p>Thank you, your booking has been processed.');
							break;
					}

				},
				dataType: 'jsonp'
		});
	} else {
		if ($('input.error').length > 0) {
			$('input.error:first').get()[0].focus();
		} else if ($('select.error').length > 0) {
			$('select.error:first').get()[0].focus();
		}
	}

}

/**
 * Display an error for a field
 *
 * Shows a element with the id fieldName_error, eg.
 *
 * <div id="fieldName_error"></div>
 *
 * and sets it's html content to $message
 *
 * @param string $fieldName name of field
 * @param string $message message to display
 */
function displayError(fieldName, message)
{
	$('#'+fieldName+'_error').html(message).show();
	// Add other error related stuff here, eg adding error class to input 
	if (fieldName == 'state') {
		$('#eventinterest select[name="'+fieldName+'"]').addClass('error');
	} else {
		$('#eventinterest input[name="'+fieldName+'"]').addClass('error');
	}
}

function displayRequiredFieldsError(fieldName)
{
	$('#requiredFieldsError').show();

	if (fieldName == 'state') {
		$('#eventinterest select[name="'+fieldName+'"]').addClass('error');
	} else {
		$('#eventinterest input[name="'+fieldName+'"]').addClass('error');
	}
}

// Is variable empty?
function isEmpty(x)
{
	return (x === false) ||
			(x === undefined) ||
			(x === null) ||
			(x === '');
}

// Does variable have a valid value?
function isValid(x)
{
	return (x !== null) && (x !== undefined);
}



/**
 * A simple querystring parser.
 * Example usage: var q = $.parseQuery(); q.fooreturns  "bar" if query contains "?foo=bar"; multiple values are added to an array. 
 * Values are unescaped by default and plus signs replaced with spaces, or an alternate processing function can be passed in the params object .
 * http://actingthemaggot.com/jquery
 *
 * Copyright (c) 2008 Michael Manning (http://actingthemaggot.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 **/
jQuery.parseQuery = function(qs,options) {
	var q = (typeof qs === 'string'?qs:window.location.search), o = {'f':function(v){return unescape(v).replace(/\+/g,' ');}}, options = (typeof qs === 'object' && typeof options === 'undefined')?qs:options, o = jQuery.extend({}, o, options), params = {};
	jQuery.each(q.match(/^\??(.*)$/)[1].split('&'),function(i,p){
		p = p.split('=');
		p[1] = o.f(p[1]);
		params[p[0]] = params[p[0]]?((params[p[0]] instanceof Array)?(params[p[0]].push(p[1]),params[p[0]]):[params[p[0]],p[1]]):p[1];
	});
	return params;
}

