/**
 *
 * Contains JS specific to events on PWN forms.
 *
 * Reusable functions such as those to show error messags and validating fields
 * are contained in form-functions.js
 *
 * To set up a new form to be handled by ajax, create the following 3 functions,
 * see formGeneratePin_*() for an examples.
 *
 *  1. formFORMNAME_Init();
 *         Use this to set up the form, call .ajaxForm() and set up default text
 *         in fields, see
 *  2. formFORMNAME_Validate();
 *          Performs form validation and calls showInputErrorsBoxes() to show the
 *          error messages. Returns the value of showInputErrorsBoxes
 *  3. formFORMNAME_Response();
 *          Handles the ajax response by showing or hiding any relevant divs
 *
 */


/**
 * AJAX response may inclue JavaScript code for tracking purposes. This loads and executes it.
 */

function processAjaxJavascript(js) {
	for (var i in js) {
		switch (js[i]['type']) {
			// It's an explicit code snippet, so eval() it - in the global scope!
			case 'code':
//				alert("about to execute: \n"+js[i]['value']);
				$.globalEval(js[i]['value']);
//				alert("executed");
				break;
			
			// It's a reference to a file include, so fetch the file and execute it with jQuery
			case 'file':
//				alert("about to load: \n"+js[i]['value']);
				$.getScript(js[i]['value']);
//				alert('loaded');
				break;
		}
	}	
}
 
/**
 * Pin Generation Form (Such as that on the homepage)
 */
function formGeneratePin_Init() {
	defaultTextField($('form#form-generate-pin input[name$="email"]'), DEFAULT_TEXT_EMAIL_ADDRESS_HOME_PAGE_REGISTER);

	$('#form-generate-pin').ajaxForm({
		beforeSubmit: formGeneratePin_Validate,
		success:	  formGeneratePin_Response,
		error:		  formCommunicationError
	});
	
	// If a user has already registered we want to show the pin, so the pin gets stored in a cookie,
	// and gets shown on this page using php.
	// 
	// IE cache behaviour reloads the page when you press the back button, but not if you navigate
	// to the page, so here we add the pin to the box if it is in the cookie
	if ($.cookie('registered_pin') != undefined && $(".pin-container").html() == '******') {
		$('.pin-container').addClass('pin-container-response');
		$('.pin-container').html($.cookie('registered_pin'));
	}
	
}

function formGeneratePin_Validate(formData) {

    var errors = new Array();

	if (!isValidEmail($('form#form-generate-pin input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'form-generate-pin');
	}

	if (!$('form#form-generate-pin input[name$="agree_tick"]').is(':checked')) {
		errors.push({'message': FORM_VALIDATION_T_AND_C,
		             'field_name'  : 'agree_tick'});
		return showInputErrorsBoxes(errors, 'form-generate-pin');
	}

	formShowAjaxLoader('/img/ajax-loader-h.gif', $('.pin-container'),null,35,5);
	return true;
}

/**
 *  Generate Pin Default
 */

function formGeneratePin_Response(responseText) {


	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
			// Remove the ajax loader image
			formRemoveAjaxLoader();
			
			// prepopulate email if it is not empty
			if ($('#register_email').val() != '') {
				$('#pin_reminder_email_address').val($('#register_email').val());
			}
			
			return showInputErrorsBoxes(responseArr['error_messages'], 'form-generate-pin', true);
	}


	processAjaxJavascript(responseArr['javascript']);

	var $newElements = $(responseArr['html']);
	var videosHtml   = $newElements.find('#lower-content-container').html();
	var pinHtml      = $newElements.find('#tab-pwn-pin-registered').html();

	$('#right-content-container').html(videosHtml);
	// This turns the right content into a container the full width of the page
	$('#right-content-container').attr('id', 'lower-content-container');
	$('#lower-content-container').attr('class', 'grid_24 omega');

	
	// Remove the ajax loader image
	formRemoveAjaxLoader();
	
	$('#left-content-container').remove();

	$('#tab-pwn-pin-registered').html(pinHtml);

    	if(typeof applyCufon == 'function') {
		applyCufon();
	}
	$('#tab-pwn').hide();
	$('#tab-pwn-pin-registered').show();

        /* Set a cookie value with current email addres => this cookie will expire in next 15 minutes, (used for create login form) */
        var date = new Date();
        date.setTime(date.getTime() + (15 * 60 * 1000));
        $.cookie("prepopulatedemail", $('form#form-generate-pin input[name$="email"]').val(), { expires: date });

	// Set a cookie to remember the pin until the browser gets closed
	$.cookie("registered_pin", responseArr['pin']);
	
	// Setup jcarousel & lightbox for videos
	videos_Init();

}


/**
 * Pin Generation Form (Such as that on the homepage)
 */
function formGeneratePinLandingPage_Init() {
	defaultTextField($('form#form-generate-pin input[name$="email"]'), DEFAULT_TEXT_EMAIL_ADDRESS);

	$('#form-generate-pin').ajaxForm({
		beforeSubmit: formGeneratePinLandingPage_Validate,
		success:	  formGeneratePinLandingPage_Response,
		error:		  formCommunicationError
	});
}

function formGeneratePinLandingPage_Validate(formData) {
    var errors = new Array();
	if (!isValidEmail($('form#form-generate-pin input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'form-generate-pin');
	}

	if (!$('form#form-generate-pin input[name$="agree_tick"]').is(':checked')) {
		errors.push({'message': FORM_VALIDATION_T_AND_C,
		             'field_name'  : 'agree_tick'});
		return showInputErrorsBoxes(errors, 'form-generate-pin');
	}
	formShowAjaxLoader('/img/ajax-loader-h.gif', $('.pin-container'),null,35,5);
	return showInputErrorsBoxes(errors, 'form-generate-pin');
}

/**
 *  Generate Pin from Landing Page
 */
function formGeneratePinLandingPage_Response(responseText) {
	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-generate-pin', true);
	}
	

	processAjaxJavascript(responseArr['javascript']);


	var $newElements = $(responseArr['html']);
	var videosHtml   = $newElements.find('#lower-content-container').html();
	var pinHtml      = $newElements.find('#tab-pwn-pin-registered').html();

	$('#right-content-container').html(videosHtml);
	// This turns the right content into a container the full width of the page
	$('#right-content-container').attr('id', 'lower-content-container');
	$('#lower-content-container').attr('class', 'grid_24 omega');

	$('#left-content-container').remove();
	
	// resizing the main box to fit the content
	$('#right-menu-container').css('margin-bottom','80px');
	$('#landingpage-tabs-container').animate({height: '370px'}, 1500 );
	//information-links dummy
	
	$('#tab-pwn-pin-registered').html(pinHtml);

        	if(typeof applyCufon == 'function') {
		applyCufon();
	}
	$('#tab-pwn').hide();
	$('#tab-pwn-pin-registered').show();

	// Set a cookie to remember the pin until the browser gets closed
	$.cookie("registered_pin", responseArr['pin']);
		
	// Setup jcarousel & lightbox for videos
	videos_Init();

}


/**
 * Forgot Password Form
 */
function formForgotPassword_Init() {
	$('#form-forgot-password').ajaxForm({
		beforeSubmit: formForgotPassword_Validate,
		success:	  formForgotPassword_Response,
		error:		  formCommunicationError
	});
}

function formForgotPassword_Validate(formData) {
    var errors = new Array();

	if (!isValidEmail($('form#form-forgot-password input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'form-forgot-password');
	}

	return showInputErrorsBoxes(errors, 'form-forgot-password');
}

function formForgotPassword_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-forgot-password', true);
	}

	$('#form-forgot-password-container').html(responseArr['html']);
		if(typeof applyCufon == 'function') {
		applyCufon();
	}

}

/**
 * Password Reset From
 */
function formPasswordReset_Init() {
	$('#form-password-reset').ajaxForm({
		beforeSubmit: formPasswordReset_Validate,
		success:	  formPasswordReset_Response,
		error:        formCommunicationError
	});
}
function formPasswordReset_Validate(formData) {
    var errors = new Array();

	if ($('form#form-password-reset input[name$="password"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_PASSWORD,
		             'field_name'  : 'password'});
		return showInputErrorsBoxes(errors, 'form-password-reset');
	}

	if ($('form#form-password-reset input[name$="password"]').val().length < 6) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_LESS_THAN_SIX_CHARS,
					 'field_name'  : 'password'});
		return showInputErrorsBoxes(errors, 'form-password-reset');
	}

	if ($('form#form-password-reset input[name$="password"]').val() != $('form#form-password-reset input[name$="confirm_password"]').val()) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_MISMATCH,
					 'field_name'  : 'confirm_password'});
		return showInputErrorsBoxes(errors, 'form-password-reset');
	}

	return showInputErrorsBoxes(errors, 'form-password-reset');
}
function formPasswordReset_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-forgot-password', true);
	}
	$('#form-reset-password-container').html(responseArr['html']);
		if(typeof applyCufon == 'function') {
		applyCufon();
	}
	
}

/**
 * Pin Reminder Form
 */
function formPinReminder_Init() {

	defaultTextField($('form#form-pin-reminder input[name$="email"]'), DEFAULT_TEXT_EMAIL_ADDRESS);
	defaultTextField($('form#form-pin-reminder input[name$="mobile_number"]'), DEFAULT_TEXT_MOBILE);

	$('#form-pin-reminder').ajaxForm({
		beforeSubmit: formPinReminder_Validate,
		success:	  formPinReminder_Response,
		error:		  formCommunicationError
	});
}
function formPinReminder_Validate(formData) {

    var errors = new Array();
	
	// Sadly and inexplicably, formData, rather than being an object with the field names as properties, is an array that looks like this:
	// [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
	
	// In our case:
	// formData[0] is email
	// formData[1] is mobile_number
	
	if (!isValidEmail(formData[0].value)) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'form-pin-reminder');
	}

	// The mobile_number field as default text, if validation has passed then remove this text
	// before submitting to the server
	if (errors.length == 0) {
		if (formData[1].value == DEFAULT_TEXT_MOBILE) {
			formData.splice(1);
		}
	}
	
	return showInputErrorsBoxes(errors, 'form-pin-reminder');
}
function formPinReminder_Response(responseText) {

	// @warning: This tooltip gets reset by rightMenuToolTips_ResetContent();
	// when it gets re-shown

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-pin-reminder', true);
	}

	$('#pin-reminder-response-placeholder').html(responseArr['html']);
    	if(typeof applyCufon == 'function') {
		applyCufon();
	}
	$('#pin-reminder-form-placeholder').fadeOut('slow', function() {
		$('#pin-reminder-response-placeholder').fadeIn('slow');
	});

    return true;
}

/**
 * Mypowwownow Login Small (On the top right of most pages)
 */
function formLogInSmall_Init() {

	// Add default text
	defaultTextField($('form#log-in-small input[name$="loginEmail"]'));
	defaultTextField($('form#log-in-small input[name$="loginPassword"]'));

	// Hide password under asterix
	$('#labelPassword').focus(function(){
		$('#labelPassword').blur();
		$('#labelPassword').hide();
		$('#loginPassword').show();
		$('#loginPassword').focus();
		$('#loginPassword').parent('span').removeClass('mypwn-input-container').addClass('mypwn-input-container-focused');
	});
	$('#loginPassword').focusout(function(){
		if ($('#loginPassword').val() == '') {
			$('#loginPassword').hide();
			$('#labelPassword').show();
			$('#labelPassword').parent('span').removeClass('mypwn-input-container-focused').addClass('mypwn-input-container');
		}
	});
	$('#loginPassword').focusout(function(){
		$('#loginPassword').parent('span').removeClass('mypwn-input-container-focused').addClass('mypwn-input-container');
	});
	$('#loginPassword').focus(function(){
		$('#loginPassword').parent('span').removeClass('mypwn-input-container').addClass('mypwn-input-container-focused');
	});

	// Attach validation and post submit functions to form
	$('#log-in-small').ajaxForm({
        url:          URL_MYPWN_LOGIN,
		beforeSubmit: formLogInSmall_Validate,
		success:	  formLogInSmall_Response,
		error:		  formCommunicationError
	});
}
function formLogInSmall_Validate(formData) {

    var errors = new Array();

	if (!isValidEmail($('form#log-in-small input[name$="loginEmail"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'loginEmail'});
		return showInputErrorsBoxes(errors, 'log-in-small');
	}

	if (($('form#log-in-small input[name$="loginPassword"]').val() == '')) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_EMPTY, 'field_name'  : 'loginPassword_Text'});
		return showInputErrorsBoxes(errors, 'log-in-small');
        }

	return showInputErrorsBoxes(errors, 'log-in-small');
}
/**
 * Switches to the logged in content and creates cookies
 */
function formLogInSmall_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if (responseArr['status'] == 'success') {
		// Set up cookies
		logUserIn(responseArr['first_name']);

		// Redirect to mypowwownow
		window.location = URL_MYPWN_START_PAGE;
	} else {
		// Remove cookies
		logUserOut();

		var errors = new Array();
		errors.push({'message': FORM_VALIDATION_INVALID_PASSWORD, 'field_name'  : 'loginEmail'});

		showInputErrorsBoxes(errors, 'log-in-small');
	}
}

/**
 * Logs the user out, hides the logged in text and shows the log inbox
 * @todo: The if statement is for testing the new mypwn only on stage,
 * when we go live we need remove the if and else part
 */
function formLogInSmall_LogOut() {

//    if (window.location.href.indexOf('staging.powwownow') != -1) {
        $.ajax({
            url: '/ajax/mypwn/logout', 
            method: 'get',
            error: function(XMLHttpRequest, textStatus, errorThrown){
                alert(FORM_RESPONSE_LOGOUT_UNSUCCESSFUL);
            },
            success: function(data){
                if (data == 1) {
                    $('.logged').addClass('hidden');
                    $('.notLogged').removeClass('hidden');
                    window.location = '/';
                    return true;
                } else {
                    alert(FORM_RESPONSE_LOGOUT_UNSUCCESSFUL);
                    return false;
                }
            }
        });

/*    } else {
        window.location = '/mypwn/logout/';
        $('.logged').addClass('hidden');
        $('.notLogged').removeClass('hidden');
    }
*/
}



/**
 * Changes content of the myPowwownow log in box in the top right-hand
 * side of most pages
 * 
 * If loggedIn is true, will show the 'Your are logged in' message,
 * if false will show log in box.
 * Optionally supply the name to be shown
 */
function changeLoggedInBoxState(loggedIn, loggedFirstName) {
	if (loggedIn) {
		if ($.trim(loggedFirstName) != '') {
			$('span.loggedInFirstname').text(" " + loggedFirstName);
		}
		$('div.logged').removeClass('hidden');
		$('div.notLogged').addClass('hidden');
	} else {
		$('div.notLogged').removeClass('hidden');
		$('div.logged').addClass('hidden');
	}
}

/**
 * Web Conference Get Started Form
 */
function formWebConferenceGetStarted_Init() {

	$('#web-conferencing-get-started-form').ajaxForm({
		beforeSubmit: formWebConferenceGetStarted_Validate,
		success:	  formWebConferenceGetStarted_Response,
		error:		  formCommunicationError
	});
}
function formWebConferenceGetStarted_Validate(formData) {

	var errors = new Array();

	if ($('form#web-conferencing-get-started-form input[name$="first_name"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_FIRST_NAME,
					 'field_name'  : 'first_name'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if ($('form#web-conferencing-get-started-form input[name$="surname"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_SURNAME,
					 'field_name'  : 'surname'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if ($('form#web-conferencing-get-started-form input[name$="company"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_COMPANY_NAME,
					 'field_name'  : 'company'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if ($('form#web-conferencing-get-started-form input[name$="phone"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_INVALID_PHONE_NUMBER,
					 'field_name'  : 'phone'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if ($('form#web-conferencing-get-started-form input[name$="phone"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_INVALID_PHONE_NUMBER,
					 'field_name'  : 'phone'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if (!isValidEmail($('form#web-conferencing-get-started-form input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if ($('form#web-conferencing-get-started-form input[name$="email"]').val() != $('form#web-conferencing-get-started-form input[name$="confirm_email"]').val()) {
		errors.push({'message': FORM_VALIDATION_EMAIL_MISMATCH,
					 'field_name'  : 'confirm_email'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if ($('form#web-conferencing-get-started-form input[name$="password"]').val().length < 6) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_LESS_THAN_SIX_CHARS,
					 'field_name'  : 'password'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if ($('form#web-conferencing-get-started-form input[name$="password"]').val() != $('form#web-conferencing-get-started-form input[name$="confirm_password"]').val()) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_MISMATCH,
					 'field_name'  : 'confirm_password'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if ($('form#web-conferencing-get-started-form select[name$="how_heard"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_HOW_HEARD_OF_PWN_NOT_SELECTED,
					 'field_name'  : 'how_heard'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	if (!$('form#web-conferencing-get-started-form input[name$="agree"]').is(':checked')) {
		errors.push({'message': FORM_VALIDATION_T_AND_C,
					 'field_name'  : 'agree'});
		return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
	}

	return showInputErrorsBoxes(errors, 'web-conferencing-get-started-form');
}
function formWebConferenceGetStarted_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'web-conferencing-get-started-form', true);
	}
	
	processAjaxJavascript(responseArr['javascript']);

	// If no error, an account was created successfully, so log the user in via ajax call to old
	// mypwn
	$.get(URL_MYPWN_LOGIN, {loginEmail: $('form#web-conferencing-get-started-form input[name$="email"]').val(),
												loginPassword: $('form#web-conferencing-get-started-form input[name$="password"]').val()},
		function(loginResponseText){

			logInResponseArr = eval('(' + loginResponseText + ')');

			if (logInResponseArr['status'] == 'success') {
				// Set up cookies
				logUserIn($('form#web-conferencing-get-started-form input[name$="first_name"]').val());
				// Change log in box at top right to logged in
				changeLoggedInBoxState(true, $('form#web-conferencing-get-started-form input[name$="first_name"]').val());
			} else {
				// Login failed - remove cookies and show error message
				logUserOut();
				alert(FORM_RESPONSE_LOG_IN_UNABLE);
			}

			// Extract the upper content (main text) and videos from the html in the response
			var $newElements    = $(responseArr['html']);
			var videosHtml      = $newElements.find('#lower-content-container').html();
			var mainContentHtml = $newElements.find('#upper-content-container').html();

			// Show the main (upper) content
			$('#tab-web-conferencing-get-started-form-response-placeholder').html(mainContentHtml);
			$('#tab-web-conferencing-get-started-initial-content').hide();	
			$('#tab-web-conferencing-get-started-form-response-placeholder').show();
			
			// Add the videos
			$('#right-content-container').html(videosHtml);
			// This turns the right content into a container the full width of the page
			$('#right-content-container').attr('id', 'lower-content-container');
			$('#lower-content-container').attr('class', 'grid_24 omega');
			
			$('#left-content-container').remove();

			// Setup jcarousel & lightbox for videos
			videos_Init();

				if(typeof applyCufon == 'function') {
		applyCufon();
	}			
	});

    return true;
}




/**
 * Plus Registration on Plus Tab  on Home Page
 */
function formPlusRegistration_Init() {

	$('#plus-registration-form').ajaxForm({
		beforeSubmit: formPlusRegistration_Validate,
		success:	  formPlusRegistration_Response,
		error:		  formCommunicationError
	});
}

function formPlusRegistration_Validate(formData) {

	var errors = new Array();

	if ($('form#plus-registration-form input[name$="first_name"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_FIRST_NAME,
					 'field_name'  : 'first_name'});
		return showInputErrorsBoxes(errors, 'plus-registration-form');
	}

	if ($('form#plus-registration-form input[name$="surname"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_SURNAME,
					 'field_name'  : 'surname'});
		return showInputErrorsBoxes(errors, 'plus-registration-form');
	}

	if ($('form#plus-registration-form input[name$="organisation"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_COMPANY_NAME,
					 'field_name'  : 'organisation'});
		return showInputErrorsBoxes(errors, 'plus-registration-form');
	}


	if ($('form#plus-registration-form input[name$="phone"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_INVALID_PHONE_NUMBER,
					 'field_name'  : 'phone'});
		return showInputErrorsBoxes(errors, 'plus-registration-form');
	}

	if (!isValidEmail($('form#plus-registration-form input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'plus-registration-form');
	}

	if ($('form#plus-registration-form input[name$="email"]').val() != $('form#plus-registration-form input[name$="confirm_email"]').val()) {
		errors.push({'message': FORM_VALIDATION_EMAIL_MISMATCH,
					 'field_name'  : 'confirm_email'});
		return showInputErrorsBoxes(errors, 'plus-registration-form');
	}

	if ($('form#plus-registration-form input[name$="password"]').val().length < 6) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_LESS_THAN_SIX_CHARS,
					 'field_name'  : 'password'});
		return showInputErrorsBoxes(errors, 'plus-registration-form');
	}

	if ($('form#plus-registration-form input[name$="password"]').val() != $('form#plus-registration-form input[name$="confirm_password"]').val()) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_MISMATCH,
					 'field_name'  : 'confirm_password'});
		return showInputErrorsBoxes(errors, 'plus-registration-form');
	}

    if (errors.length == 0) {
        $('#form-plus-btn').parent().after().append('<img src="/img/ajax-loader-white.gif" alt="" id="ajaxloader" />');
        $('#form-plus-btn').attr('disabled', 'true');
    }

	return showInputErrorsBoxes(errors, 'plus-registration-form');
}

function formPlusRegistration_Response(responseText) {

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        
        $('#ajaxloader').remove();
        $('#form-plus-btn').removeAttr('disabled');
        
		return showInputErrorsBoxes(responseArr['error_messages'], 'plus-registration-form', true);
	}

	$.get(URL_MYPWN_LOGIN, {loginEmail: $('form#plus-registration-form input[name$="email"]').val(),
                                        loginPassword: $('form#plus-registration-form input[name$="password"]').val()},
        function(loginResponseText){
            logInResponseArr = eval('(' + loginResponseText + ')');

            if (logInResponseArr['status'] == 'success') {
                // Set up cookies
                logUserIn(logInResponseArr['first_name']);

                window.setTimeout(function (){
                    window.location = URL_MYPWN_PLUS_CONFIRMATION_PAGE;
                }, 1000);

            } else {
                // Login failed - remove cookies and show error message
                logUserOut();
                alert(FORM_RESPONSE_LOG_IN_UNABLE);
            }
    });
}


/**
 * Download Showtime Form
 */
function formDownloadShowtime_Init() {
	$('#web-conferencing-download-showtime-form').ajaxForm({
		beforeSubmit: formDownloadShowtime_Validate,
		success:	  formDownloadShowtime_Response,
		error:		  formCommunicationError
	});
}
function formDownloadShowtime_Validate(formData) {
    var errors = new Array();

	if (!isValidEmail($('form#web-conferencing-download-showtime-form input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'web-conferencing-download-showtime-form');
	}

	if ($('form#web-conferencing-download-showtime-form input[name$="password"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_PASSWORD,
		             'field_name'  : 'password'});
		return showInputErrorsBoxes(errors, 'web-conferencing-download-showtime-form');
	}

	return showInputErrorsBoxes(errors, 'web-conferencing-download-showtime-form');
}
function formDownloadShowtime_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-contact-us', true);
	}

	$('#web-conferencing-download-showtime-form-response-placeholder').html(responseArr['html']);
    	if(typeof applyCufon == 'function') {
		applyCufon();
	}
	$('#web-conferencing-download-showtime-form-initial-content').hide();
	$('#web-conferencing-download-showtime-form-response-placeholder').show();

    return true;
}

/**
 * Log in form on the log in page
 */
function formLogInOnLoginPage_Init() {
	$('#form-log-in').ajaxForm({
        url:          URL_MYPWN_LOGIN,
		beforeSubmit: formLogInOnLogInPage_Validate,
		success:	  formLogInOnLogInPage_Response,
		error:		  formCommunicationError
	});
}
function formLogInOnLogInPage_Validate(formData) {
    var errors = new Array();

	if (!isValidEmail($('form#form-log-in input[name$="loginEmail"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'loginEmail'});
		return showInputErrorsBoxes(errors, 'form-log-in');
	}

	if ($('form#form-log-in input[name$="loginPassword"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_PASSWORD,
		             'field_name'  : 'loginPassword'});
		return showInputErrorsBoxes(errors, 'form-log-in');
	}

	return showInputErrorsBoxes(errors, 'form-log-in');
}


function formLogInOnLogInPage_Response(responseText) {

	responseArr = eval('(' + responseText + ')');

	if (responseArr['status'] == 'success') {
		// Set up cookies
		logUserIn(responseArr['first_name']);

		// Redirect to mypowwownow, if hidden form field d (destination) is set,
		// then that is the array key value to MYPWN_LOGIN_REDIRECTS, so redirect
		// there
		if ($('form#form-log-in input[name$="d"]').val() !== undefined &&
			MYPWN_LOGIN_REDIRECTS[$('form#form-log-in input[name$="d"]').val()] !== undefined) {
			window.location = MYPWN_LOGIN_REDIRECTS[$('form#form-log-in input[name$="d"]').val()];
		} else {
			window.location = URL_MYPWN_START_PAGE;
		}

	} else {
		// Remove cookies
		logUserOut();
                var errors = new Array();
                errors.push({'message': FORM_VALIDATION_INVALID_PASSWORD,
		             'field_name'  : 'loginEmail'});
		return showInputErrorsBoxes(errors, 'form-log-in');
	}
}

/**
 * Create a log in form on the log in page
 */
function formCreateLoginOnLoginPage_Init() {
	$('#form-create-log-in').ajaxForm({
		beforeSubmit: formCreateLoginOnLoginPage_Validate,
		success:	  formCreateLoginOnLoginPage_Response,
		error:        formCommunicationError
	});
}
function formCreateLoginOnLoginPage_Validate(formData) {
    var errors = new Array();

	if ($('form#form-create-log-in input[name$="first_name"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_FIRST_NAME,
		             'field_name'  : 'first_name'});
		return showInputErrorsBoxes(errors, 'form-create-log-in');
	}

	if ($('form#form-create-log-in input[name$="last_name"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_SURNAME,
		             'field_name'  : 'last_name'});
		return showInputErrorsBoxes(errors, 'form-create-log-in');
	}

	if (!isValidEmail($('form#form-create-log-in input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'form-create-log-in');
	}

	if ($('form#form-create-log-in input[name$="password"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_PASSWORD,
		             'field_name'  : 'password'});
		return showInputErrorsBoxes(errors, 'form-create-log-in');
	}

	if ($('form#form-create-log-in input[name$="password"]').val().length < 6) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_LESS_THAN_SIX_CHARS,
					 'field_name'  : 'password'});
		return showInputErrorsBoxes(errors, 'form-create-log-in');
	}


	if ($('form#form-create-log-in input[name$="password"]').val() != $('form#form-create-log-in input[name$="confirm_password"]').val()) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_MISMATCH,
					 'field_name'  : 'confirm_password'});
		return showInputErrorsBoxes(errors, 'form-create-log-in');
	}


	return showInputErrorsBoxes(errors, 'form-create-log-in');
}

function formCreateLoginOnLoginPage_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	// If the ajax call returned an error then show it
	responseArr = eval('(' + responseText + ')');
	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-create-log-in', true);
	}
	
	processAjaxJavascript(responseArr['javascript']);

	// If no error, an account was created successfully, so log the user in via ajax call to old
	// mypwn
	$.get(URL_MYPWN_LOGIN, {loginEmail: $('form#form-create-log-in input[name$="email"]').val(),
                                        loginPassword: $('form#form-create-log-in input[name$="password"]').val()},
		function(loginResponseText){
			logInResponseArr = eval('(' + loginResponseText + ')');

			if (logInResponseArr['status'] == 'success') {
				// Set up cookies
				logUserIn(logInResponseArr['first_name']);

				// Redirect user to the specified page based on the destination (called 'd') hidden form input
				// after a time delay. Use URL_MYPWN_START_PAGE as the default page if one was not set or invalid
				window.setTimeout(function (){
						if ($('form#form-create-log-in input[name$="d"]').val() !== undefined &&
							MYPWN_LOGIN_REDIRECTS[$('form#form-create-log-in input[name$="d"]').val()] !== undefined) {
							redirectUrl = MYPWN_LOGIN_REDIRECTS[$('form#form-create-log-in input[name$="d"]').val()];
						} else {
							redirectUrl = URL_MYPWN_START_PAGE;
						}
						// Perform redirect
						window.location = redirectUrl;

					}, 3000);

			} else {
				// Login failed - remove cookies and show error message
				logUserOut();
				alert(FORM_RESPONSE_LOG_IN_UNABLE);
			}

			$('#mypwn-create-login-form-placeholder').hide();
			$('#mypwn-create-login-response-placeholder').html(responseArr['html']);
			
				if(typeof applyCufon == 'function') {
		applyCufon();
	}
			
	});

}

/**
 * Contact us form on contact us page
 */
function formContactUs_Init() {
	$('#form-contact-us').ajaxForm({
		beforeSubmit: formContactUs_Validate,
		success:	  formContactUs_Response,
		error:        formCommunicationError
	});
}
function formContactUs_Validate(formData) {

    var errors = new Array();

	if ($('form#form-contact-us input[name$="first_name"]').val() == '') {
		errors.push({'message'    : FORM_VALIDATION_NO_FIRST_NAME,
		             'field_name' : 'first_name'});
		return showInputErrorsBoxes(errors, 'form-contact-us');
	}

	if ($('form#form-contact-us input[name$="last_name"]').val() == '') {
		errors.push({'message'    : FORM_VALIDATION_NO_SURNAME,
		             'field_name' : 'last_name'});
		return showInputErrorsBoxes(errors, 'form-contact-us');
	}

	if ($('form#form-contact-us input[name$="company"]').val() == '') {
		errors.push({'message'    : FORM_VALIDATION_NO_COMPANY_NAME,
		             'field_name' : 'company'});
		return showInputErrorsBoxes(errors, 'form-contact-us');
	}

	if ($('form#form-contact-us input[name$="phone_number"]').val() == '') {
		errors.push({'message'    : FORM_VALIDATION_INVALID_PHONE_NUMBER,
		             'field_name' : 'phone_number'});
		return showInputErrorsBoxes(errors, 'form-contact-us');
	}

	if (!isValidEmail($('form#form-contact-us input[name$="email"]').val())) {
		errors.push({'message'    : FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name' : 'email'});
		return showInputErrorsBoxes(errors, 'form-contact-us');
	}

	if (!isValidEmail($('form#form-contact-us input[name$="confirm_email"]').val())) {
		errors.push({'message'    : FORM_VALIDATION_EMAIL_MISMATCH,
		             'field_name' : 'confirm_email'});
		return showInputErrorsBoxes(errors, 'form-contact-us');
	}

	if ($('form#form-contact-us input[name$="email"]').val() != $('form#form-contact-us input[name$="confirm_email"]').val()) {
		errors.push({'message'    : FORM_VALIDATION_EMAIL_MISMATCH,
		             'field_name' : 'confirm_email'});
		return showInputErrorsBoxes(errors, 'form-contact-us');
	}

	if ($('form#form-contact-us textarea[name$="comments"]').val() == '') {
		errors.push({'message'    : FORM_VALIDATION_NO_COMMENTS,
		             'field_name' : 'comments'});
		return showInputErrorsBoxes(errors, 'form-contact-us');
	}

	return showInputErrorsBoxes(errors, 'form-contact-us');
}
function formContactUs_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-contact-us', true);
	}

	$('.contact-us-container').html(responseArr['html']);
	$('#contact-form-disclaimer').hide();
	$('#contact-form-required-fields').hide();
		if(typeof applyCufon == 'function') {
		applyCufon();
	}

    return true;
}

/**
 * Unsubscribe form on unsubscribe page
 */
function formUnsubscribe_Init() {
	$('#form-unsubscribe').ajaxForm({
		beforeSubmit: formUnsubscribe_Validate,
		success:	  formUnsubscribe_Response,
		error:        formCommunicationError
	});
}
function formUnsubscribe_Validate(formData) {

    var errors = new Array();

	if (!isValidEmail($('form#form-unsubscribe input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name': 'email'});
		return showInputErrorsBoxes(errors, 'form-unsubscribe');
	}

	return showInputErrorsBoxes(errors, 'form-unsubscribe');
}
function formUnsubscribe_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');
	
	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-unsubscribe', true);
	}

	$('.unsubscribe-container').html(responseArr['html']);
		if(typeof applyCufon == 'function') {
		applyCufon();
	}
}

/**
 * Delete pin form on unsubscribe page
 */
function formDeletePin_Init() {
	$('#form-delete-pin').ajaxForm({
		beforeSubmit: formDeletePin_Validate,
		success:	  formDeletePin_Response,
		error:        formCommunicationError
	});
}
function formDeletePin_Validate(formData) {
    var errors = new Array();

	if (!isValidEmail($('form#form-delete-pin input[name$="email"]').val())) {
		errors.push({'message'    : FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name' : 'email'});
		return showInputErrorsBoxes(errors, 'form-delete-pin');
	}

	if ($('form#form-delete-pin input[name$="pin"]').val().length != 6) {
		errors.push({'message': FORM_VALIDATION_INVALID_SIX_DIGIT_PIN,
		             'field_name': 'pin'});
		return showInputErrorsBoxes(errors, 'form-delete-pin');
	}

	return showInputErrorsBoxes(errors, 'form-delete-pin');
}
function formDeletePin_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-delete-pin', true);
	}
	
	$('.delete-pin-container').html(responseArr['html']);
		if(typeof applyCufon == 'function') {
		applyCufon();
	}
}

/**
 * Tell a friend form
 */
function formTellAFriend_Init() {
	$('#form-tell-a-friend').ajaxForm({
		beforeSubmit: formTellAFriend_Validate,
		success:	  formTellAFriend_Response,
		error:        formCommunicationError
	});
}
function formTellAFriend_Validate(formData) {

    var errors = new Array();

	if ($('form#form-tell-a-friend input[name$="your_name"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_NAME,
		             'field_name'  : 'your_name'});
		return showInputErrorsBoxes(errors, 'form-tell-a-friend');
	}

	if (!isValidEmail($('form#form-tell-a-friend input[name$="your_email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'your_email'});
		return showInputErrorsBoxes(errors, 'form-tell-a-friend');
	}

	if ($('form#form-tell-a-friend input[name$="friends_name"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_FRIENDS_NAME,
		             'field_name'  : 'friends_name'});
		return showInputErrorsBoxes(errors, 'form-tell-a-friend');
	}

	if (!isValidEmail($('form#form-tell-a-friend input[name$="friends_email"]').val())) {
		errors.push({'message': FORM_VALIDATION_NO_FRIENDS_EMAIL,
		             'field_name'  : 'friends_email'});
		return showInputErrorsBoxes(errors, 'form-tell-a-friend');
	}

	return showInputErrorsBoxes(errors, 'form-tell-a-friend');
}
function formTellAFriend_Response(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-tell-a-friend', true);
	}

	// A friend was succesfully told, append form repsone to the top of the form
	$('.tell-a-friend-output-container').html(responseArr['html']);
	// Remove friends name and email
    $('form#form-tell-a-friend input[name$="friends_name"]').val('');
    $('form#form-tell-a-friend input[name$="friends_email"]').val('');
	
		if(typeof applyCufon == 'function') {
		applyCufon();
	}
}


/**
 * 
 *  B testing part
 *  amended response functions below
 *
 */





/**
 * Pin Generation Form (Such as that on the homepage) for B testing of the index page
 */
function formGeneratePin_Init_B() {
	defaultTextField($('form#form-generate-pin input[name$="email"]'), DEFAULT_TEXT_EMAIL_ADDRESS_HOME_PAGE_REGISTER);

	$('#form-generate-pin').ajaxForm({
		beforeSubmit: formGeneratePin_Validate,
		success:	  formGeneratePin_Response_B,
		error:		  formCommunicationError
	});
	
	// If a user has already registered we want to show the pin, so the pin gets stored in a cookie,
	// and gets shown on this page using php.
	// 
	// IE cache behaviour reloads the page when you press the back button, but not if you navigate
	// to the page, so here we add the pin to the box if it is in the cookie
	if ($.cookie('registered_pin') != undefined && $(".pin-container").html() == '******') {
		$('.pin-container').addClass('pin-container-response');
		$('.pin-container').html($.cookie('registered_pin'));
	}
	
}



/**
 *  Generate Pin for B testing of the index page
 */ 

function formGeneratePin_Response_B(responseText) {


	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
			// Remove the ajax loader image
			formRemoveAjaxLoader();
			return showInputErrorsBoxes(responseArr['error_messages'], 'form-generate-pin', true);
	}


	processAjaxJavascript(responseArr['javascript']);

	var $newElements = $(responseArr['html']);
	var videosHtml   = $newElements.find('#lower-content-container').html();
	var pinHtml      = $newElements.find('#tab-pwn-pin-registered').html();

	$('#right-content-container').html(videosHtml);
	// This turns the right content into a container the full width of the page
	$('#right-content-container').attr('id', 'lower-content-container');
	$('#lower-content-container').attr('class', 'grid_24 omega');

	
	// Remove the ajax loader image
	formRemoveAjaxLoader();
	
	$('#left-content-container').remove();

	$('#tab-pwn-pin-registered').html(pinHtml);

    	if(typeof applyCufon == 'function') {
		applyCufon();
	}
	$('#tab-pwn').hide();
	$('#tab-pwn-pin-registered').show();
	$('#tabs-container').height(630);
	$('.pwn-registration-option').show();
	reg_email = $('#register_email').val();
	$('#create_login_email').val(reg_email);

        /* Set a cookie value with current email addres => this cookie will expire in next 15 minutes, (used for create login form) */
        var date = new Date();
        date.setTime(date.getTime() + (15 * 60 * 1000));
        $.cookie("prepopulatedemail", $('form#form-generate-pin input[name$="email"]').val(), { expires: date });

	// Set a cookie to remember the pin until the browser gets closed
	$.cookie("registered_pin", responseArr['pin']);
	
	// Setup jcarousel & lightbox for videos
	videos_Init();

}





function formCreateLoginOnLoginPage_Init_B() {
	$('#form-create-log-in').ajaxForm({
		beforeSubmit: formCreateLoginOnLoginPage_Validate,
		success:	  formCreateLoginOnLoginPage_Response_B,
		error:        formCommunicationError
	});
}

function formCreateLoginOnLoginPage_Response_B(responseText) {

	// Remove the ajax loader image
	formRemoveAjaxLoader();

	// If the ajax call returned an error then show it
	responseArr = eval('(' + responseText + ')');
	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'form-create-log-in', true);
	}
	
	processAjaxJavascript(responseArr['javascript']);

	// If no error, an account was created successfully, so log the user in via ajax call to old
	// mypwn
	$.get(URL_MYPWN_LOGIN, {loginEmail: $('form#form-create-log-in input[name$="email"]').val(),
										loginPassword: $('form#form-create-log-in input[name$="password"]').val()},
		function(loginResponseText){
			logInResponseArr = eval('(' + loginResponseText + ')');

			if (logInResponseArr['status'] == 'success') { 
				// Set up cookies
				logUserIn(logInResponseArr['first_name']);
				
				    $('.logged').removeClass('hidden');
					$('.notLogged').addClass('hidden');
						if(typeof applyCufon == 'function') {
		applyCufon();
	}
					$('.pwn-registration-option').hide();
					$('#tabs-container').height(750);
					$('.pwn-walletcard-option').show();


			} else {
				// Login failed - remove cookies and show error message
				logUserOut();
				alert(FORM_RESPONSE_LOG_IN_UNABLE);
			}
		});			
			
}



function formRequestWalletCard_Init() {
	$('#mypins-walletcard-form').ajaxForm({
		beforeSubmit: formRequestWalletCard_Validate,
		success:	  formRequestWalletCard_Response,
		error:        formCommunicationError
	});
}


function isValidPostcode(toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkpmnrstuvwxy]";                         // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  
  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  
  // Overseas Territories
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);  
  
  // Anguilla
  pcexp.push (/^(ai-2640)$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and inserting a space 
      // between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // If it is the Anguilla overseas territory postcode, we need to treat it specially
      if (toCheck.toUpperCase() == 'AI-2640') {postCode = 'AI-2640'};
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid postcode
  if (valid) {return postCode;} else return false;
}



function formRequestWalletCard_Validate(formData) {
    var errors = new Array();

	if ($('form#mypins-walletcard-form input[name$="building"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_ADDRESS,
		             'field_name'  : 'building'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}

	if ($('form#mypins-walletcard-form input[name$="town"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_TOWN,
		             'field_name'  : 'town'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}

	if (!isValidPostcode($('form#mypins-walletcard-form input[name$="postal_code"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_POSTCODE,
		             'field_name'  : 'postal_code'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}


	return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
}

function formRequestWalletCard_Response(responseText) {

	// If the ajax call returned an error then show it
	responseArr = eval('(' + responseText + ')');
	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'mypins-walletcard-form', true);
	}
	
	processAjaxJavascript(responseArr['javascript']);
	
	$('.pwn-walletcard-option').html(responseArr['html']);  
	$('#tabs-container').height(400);
	
	var timeout;
	timeout = setTimeout('wcr_timeout_trigger()', 5000);




	// show nice headings in rockwell
		if(typeof applyCufon == 'function') {
		applyCufon();
	}
}

function wcr_timeout_trigger() {
    $('.wcr-success').hide();
	$('.what-to-do-now').show();
		if(typeof applyCufon == 'function') {
		applyCufon();
	}
}

function wcr_timeout_clear() {
    clearTimeout(timeout);
}


/* A/B testing -- Version C of the home page */


function formGeneratePin_C_Init() {
	defaultTextField($('form#form-generate-pin input[name$="email"]'), DEFAULT_TEXT_EMAIL_ADDRESS_HOME_PAGE_REGISTER);

	$('#form-generate-pin').ajaxForm({
		beforeSubmit: formGeneratePin_C_Validate,
		success:	  formGeneratePin_C_Response,
		error:		  formCommunicationError
	});
	
	// If a user has already registered we want to show the pin, so the pin gets stored in a cookie,
	// and gets shown on this page using php.
	// 
	// IE cache behaviour reloads the page when you press the back button, but not if you navigate
	// to the page, so here we add the pin to the box if it is in the cookie
	
}

function formGeneratePin_C_Validate(formData) {

    var errors = new Array();

	if (!isValidEmail($('form#form-generate-pin input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'form-generate-pin');
	}

	//formShowAjaxLoader('/img/ajax-loader-h.gif', $('.pin-container'),null,35,5);
	return true;
}

/**
 *  Generate Pin Default
 */

function formGeneratePin_C_Response(responseText) {


	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
			// Remove the ajax loader image
			//formRemoveAjaxLoader();
			
			// prepopulate email if it is not empty
			if ($('#register_email').val() != '') {
				$('#pin_reminder_email_address').val($('#register_email').val());
			}
			
			return showInputErrorsBoxes(responseArr['error_messages'], 'form-generate-pin', true);
	}


	processAjaxJavascript(responseArr['javascript']);

	var $newElements = $(responseArr['html']);
	var videosHtml   = $newElements.find('#lower-content-container').html();
	var pinHtml      = $newElements.find('#tab-pwn-pin-registered').html();

	$('#right-content-container').html(videosHtml);
	// This turns the right content into a container the full width of the page
	$('#right-content-container').attr('id', 'lower-content-container');
	$('#lower-content-container').attr('class', 'grid_24 omega');

	
	// Remove the ajax loader image
	formRemoveAjaxLoader();
	
	$('#left-content-container').remove();

	$('#tab-pwn-pin-registered').html(pinHtml);
	$('#header-hint-premium').remove();
    
		if(typeof applyCufon == 'function') {
		applyCufon();
	}
	$('#pwn-before-registration').hide();
	$('#tab-pwn-pin-registered').show();

        /* Set a cookie value with current email addres => this cookie will expire in next 15 minutes, (used for create login form) */
        var date = new Date();
        date.setTime(date.getTime() + (15 * 60 * 1000));
        $.cookie("prepopulatedemail", $('form#form-generate-pin input[name$="email"]').val(), { expires: date });

	// Set a cookie to remember the pin until the browser gets closed
	$.cookie("registered_pin", responseArr['pin']);
	
	// Setup jcarousel & lightbox for videos
	videos_Init();

}



/* A/B testing -- Version D of the home page */


function formGeneratePin_D_Init() {
	defaultTextField($('form#form-generate-pin input[name$="email"]'), DEFAULT_TEXT_EMAIL_ADDRESS_HOME_PAGE_REGISTER);

	$('#form-generate-pin').ajaxForm({
		beforeSubmit: formGeneratePin_D_Validate,
		success:	  formGeneratePin_D_Response,
		error:		  formCommunicationError
	});
	
	// If a user has already registered we want to show the pin, so the pin gets stored in a cookie,
	// and gets shown on this page using php.
	// 
	// IE cache behaviour reloads the page when you press the back button, but not if you navigate
	// to the page, so here we add the pin to the box if it is in the cookie
	
}

function formGeneratePin_D_Validate(formData) {

    var errors = new Array();

	if (!isValidEmail($('form#form-generate-pin input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'form-generate-pin');
	}

	//formShowAjaxLoader('/img/ajax-loader-h.gif', $('.pin-container'),null,35,5);
	return true;
}

/**
 *  Generate Pin Default
 */

function formGeneratePin_D_Response(responseText) {


	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
			// Remove the ajax loader image
			//formRemoveAjaxLoader();
			
			// prepopulate email if it is not empty
			if ($('#register_email').val() != '') {
				$('#pin_reminder_email_address').val($('#register_email').val());
			}
			
			return showInputErrorsBoxes(responseArr['error_messages'], 'form-generate-pin', true);
	}


	processAjaxJavascript(responseArr['javascript']);

	var $newElements = $(responseArr['html']);
	var videosHtml   = $newElements.find('#lower-content-container').html();
	var pinHtml      = $newElements.find('#tab-pwn-pin-registered').html();

	$('#right-content-container').html(videosHtml);
	// This turns the right content into a container the full width of the page
	$('#right-content-container').attr('id', 'lower-content-container');
	$('#lower-content-container').attr('class', 'grid_24 omega');

	
	// Remove the ajax loader image
	formRemoveAjaxLoader();
	
	$('#left-content-container').remove();

	$('#tab-pwn-pin-registered').html(pinHtml);
	$('#header-hint-premium').remove();
    
	$('#pwn-before-registration').hide();
	$('#tab-pwn-pin-registered').show();
	$('#tabs-container').height(1190);
	$('.pwn-november-option').show();
	
	// assign email to a hidden field for the next step
	reg_email = $('#register_email').val();
	$('#create_login_email').val(reg_email);

        /* Set a cookie value with current email addres => this cookie will expire in next 15 minutes, (used for create login form) */
        var date = new Date();
        date.setTime(date.getTime() + (15 * 60 * 1000));
        $.cookie("prepopulatedemail", $('form#form-generate-pin input[name$="email"]').val(), { expires: date });

	// Set a cookie to remember the pin until the browser gets closed
	$.cookie("registered_pin", responseArr['pin']);
	
	// Setup jcarousel & lightbox for videos
	videos_Init();

}





function formGeneratePin_Nov_Init() {
	defaultTextField($('form#form-generate-pin input[name$="email"]'), DEFAULT_TEXT_EMAIL_ADDRESS_HOME_PAGE_REGISTER);

	$('#form-generate-pin').ajaxForm({
		beforeSubmit: formGeneratePin_Nov_Validate,
		success:	  formGeneratePin_Nov_Response,
		error:		  formCommunicationError
	});
	
	// If a user has already registered we want to show the pin, so the pin gets stored in a cookie,
	// and gets shown on this page using php.
	// 
	// IE cache behaviour reloads the page when you press the back button, but not if you navigate
	// to the page, so here we add the pin to the box if it is in the cookie
	if ($.cookie('registered_pin') != undefined && $(".pin-container").html() == '******') {
		$('.pin-container').addClass('pin-container-response');
		$('.pin-container').html($.cookie('registered_pin'));
	}
	
}

function formGeneratePin_Nov_Validate(formData) {

    var errors = new Array();

	if (!isValidEmail($('form#form-generate-pin input[name$="email"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_EMAIL_ADDRESS,
		             'field_name'  : 'email'});
		return showInputErrorsBoxes(errors, 'form-generate-pin');
	}

	if (!$('form#form-generate-pin input[name$="agree_tick"]').is(':checked')) {
		errors.push({'message': FORM_VALIDATION_T_AND_C,
		             'field_name'  : 'agree_tick'});
		return showInputErrorsBoxes(errors, 'form-generate-pin');
	}

	formShowAjaxLoader('/img/ajax-loader-h.gif', $('.pin-container'),null,35,5);
	return true;
}

/**
 *  Generate Pin Default
 */

function formGeneratePin_Nov_Response(responseText) {


	responseArr = eval('(' + responseText + ')');

	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
			// Remove the ajax loader image
			formRemoveAjaxLoader();
			
			// prepopulate email if it is not empty
			if ($('#register_email').val() != '') {
				$('#pin_reminder_email_address').val($('#register_email').val());
			}
			
			return showInputErrorsBoxes(responseArr['error_messages'], 'form-generate-pin', true);
	}


	processAjaxJavascript(responseArr['javascript']);

	var $newElements = $(responseArr['html']);
	var videosHtml   = $newElements.find('#lower-content-container').html();
	var pinHtml      = $newElements.find('#tab-pwn-pin-registered').html();

	$('#right-content-container').html(videosHtml);
	// This turns the right content into a container the full width of the page
	$('#right-content-container').attr('id', 'lower-content-container');
	$('#lower-content-container').attr('class', 'grid_24 omega');

	
	// Remove the ajax loader image
	formRemoveAjaxLoader();
	
	$('#left-content-container').remove();

	$('#tab-pwn-pin-registered').html(pinHtml);

	$('#tab-pwn').hide();
	$('#tab-pwn-pin-registered').show();
	$('#tabs-container').height(1190);
	$('.pwn-november-option').show();
	
	// assign email to a hidden field for the next step
	reg_email = $('#register_email').val();
	$('#create_login_email').val(reg_email);

        /* Set a cookie value with current email addres => this cookie will expire in next 15 minutes, (used for create login form) */
        var date = new Date();
        date.setTime(date.getTime() + (15 * 60 * 1000));
        $.cookie("prepopulatedemail", $('form#form-generate-pin input[name$="email"]').val(), { expires: date });


	// Set a cookie to remember the pin until the browser gets closed
	$.cookie("registered_pin", responseArr['pin']);
	
	// Setup jcarousel & lightbox for videos
	videos_Init();

}




function formAdvancedRegistration_Init() {
	$('#mypins-walletcard-form').ajaxForm({
		beforeSubmit: formAdvancedRegistration_Validate,
		success:	  formAdvancedRegistration_Response,
		error:        formCommunicationError
	});
}

function formAdvancedRegistration_Validate(formData) {
    var errors = new Array();
    
	if ($('form#mypins-walletcard-form input[name$="first_name"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_FIRST_NAME,
		             'field_name'  : 'first_name'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}

	if ($('form#mypins-walletcard-form input[name$="last_name"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_SURNAME,
		             'field_name'  : 'last_name'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}
    
	if ($('form#mypins-walletcard-form input[name$="company"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_COMPANY_NAME,
		             'field_name'  : 'company'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}

	if ($('form#mypins-walletcard-form input[name$="building"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_ADDRESS,
		             'field_name'  : 'building'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}

	if ($('form#mypins-walletcard-form input[name$="town"]').val() == '') {
		errors.push({'message': FORM_VALIDATION_NO_TOWN,
		             'field_name'  : 'town'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}

	if (!isValidPostcode($('form#mypins-walletcard-form input[name$="postal_code"]').val())) {
		errors.push({'message': FORM_VALIDATION_INVALID_POSTCODE,
		             'field_name'  : 'postal_code'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}
	
    if ($('form#mypins-walletcard-form input[name$="password"]').val().length > 0)
	if ($('form#mypins-walletcard-form input[name$="password"]').val().length < 6) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_LESS_THAN_SIX_CHARS,
					 'field_name'  : 'password'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}

    if ($('form#mypins-walletcard-form input[name$="password"]').val().length > 0)
	if ($('form#mypins-walletcard-form input[name$="password"]').val() != $('form#mypins-walletcard-form input[name$="confirm_password"]').val()) {
		errors.push({'message': FORM_VALIDATION_PASSWORD_MISMATCH,
					 'field_name'  : 'confirm_password'});
		return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
	}


	return showInputErrorsBoxes(errors, 'mypins-walletcard-form');
}

function formAdvancedRegistration_Response(responseText) {

        //prepopulate name and surname in Create-A-Login page

        //$.cookie("prepopulatedName", $('#create_login_first_name').val(), { expires: date });
        //$.cookie("prepopulatedSurname", $('#create_login_last_name').val(), { expires: date });

	// If the ajax call returned an error then show it
	responseArr = eval('(' + responseText + ')');
	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'mypins-walletcard-form', true);
	}
	
	processAjaxJavascript(responseArr['javascript']);
	
	$('.pwn-november-option').html(responseArr['html']);  
	$('.green-rounded-box').height(680);
	$("html, body").animate({ scrollTop: 250 }, "slow");

/* check */

}





