/** BDBE Website Javascript
 * by WebOutreach 2008 **/
 
/* Load-time stuff */
$(document).ready(function() {
	//Add the validation handler
	$('input.validate').bind("keypress",validateInput);

	//Add quantity updaters
	$('input',$('#basketTable')).bind("change",updateBasketQuantity);
	
	//Set up external link handler
	externalLinks();	
	
});

/**
 * Make all external links target correctly
 */
function externalLinks() {
	if (!document.getElementsByTagName) return;
 	var anchors = document.getElementsByTagName("a");
 	for (var i=0; i<anchors.length; i++) {
 		var anchor = anchors[i];
 		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank";
 	}
}

/** 
 * Perform a search
 *
 * @return bool False to stop the link from firing 
 */
function performSearch() {
	//Submit the form (but only if it's not blank)
	if ($('#searchWord').val() && $('#searchWord').val()!=defaultSearchText) {
		
		$('#searchForm').submit();
	}	
	//Stop the link from firing
	return false;	
	
}

/** 
 * Set the part of the site to search
 *
 */
function searchWhat(what) {
	//Which part of the site should we search?
	if ($(what).val()=='blog') {
		$('#searchForm').attr('action','/blog/');
	}
	else {
		$('#searchForm').attr('action','/search/');
	}	
	
}

/**
 * Search box has focussed or blurred - clear out or reset the default text
 *
 * @param object The calling object
 * @param bool The state: focus (true) or blur (false)
 */
function searchFocus(objInput,state) {
	objInput=$(objInput);
	if (state) {
		//It's a focus
		if (objInput.val()==defaultSearchText) {
			objInput.val("");
		}
		objInput.addClass("searchFocus");
	} else {
		//It's a blur
		if (!objInput.val() || objInput.val()==defaultSearchText) {
			objInput.removeClass("searchFocus");
			objInput.val(defaultSearchText);
		}		
	}
 
}

/**
 * New improved version of validateChar()
 * getting most of it's information from the DOM
 * Copyright (C) 2009 WebOutreach
 *
 * Just add the "validate" class to the relevant element, and one other class from the list:
 *     nowhitespace				(Anything apart from whitespace)
 *     integer                  (Only numbers)
 *     float                    (Numbers or fullstops)
 *     characters               (A-Z, a-z, 0-9, . and -)
 *     domainname               (as above)
 *     email                    (any char valid in email addresses)
 *     alphanumeric             (alpha numeric chars including spaces)
 *     alphanumericstrict       (alpha numeric chars excluding spaces)
 *     username                 (lower-case letters and numbers only)
 *     phone                    (numbers and spaces)
 *     date						(numbers or slashes)
 *
 * @param object The event
 * @param bool Return true/false dependent upon success
 */
function validateInput(e) {
	//Get settings from the DOM
	var maxLength=$(e.target).attr('maxlength'); //In jquery, this will always be positive if set, some browsers return negative to mean unset
	var characterCode=e.charCode || e.keyCode || 0;

	//Choose the character set and check if we need to do an ajax request
	var characters="";

	//First check the whitespace class
	if ($(e.target).hasClass("nowhitespace")) {
		//Return a value based on whether this was in the list, or we have exceeded the length
		if (String.fromCharCode(characterCode)==" " || (e.target.length>=maxLength && maxLength>0)) {
			//Whitespace - don't allow
			return false;
		} else {
			//No whitespace
			return true;
		}
	}

	//Check each class of item	
	if ($(e.target).hasClass("characters") || $(e.target).hasClass("domain")) {
		//Host Name
		characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-";
	} else if ($(e.target).hasClass("email")) {
		//Email Address
		characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-/=?^_`{|}~.@";
	} else if ($(e.target).hasClass("alphanumeric")) {
		//Alpha numeric
		characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ";
	} else if ($(e.target).hasClass("cardname")) {
		//Card Name
		characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.- ";
	} else if ($(e.target).hasClass("postcode")) {
		//Alpha numeric
		characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
	} else if ($(e.target).hasClass("alphanumericstrict")) {
		//Alpha numeric
		characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	} else if ($(e.target).hasClass("username")) {
		//Alpha numeric
		characters="abcdefghijklmnopqrstuvwxyz0123456789";
	} else if ($(e.target).hasClass("phone")) {
		//A mobile number
		characters="0123456789+-.,#* ";
	} else if ($(e.target).hasClass("integer") || $(e.target).hasClass("cardnumber") || $(e.target).hasClass("shortnumber")) {
		//A card number or CVV2 code - no spaces, or number of days
		characters="0123456789";
	} else if ($(e.target).hasClass("float")) {
		//A discount % - could be a float
		characters="0123456789.";
	} else if ($(e.target).hasClass("date")) {
		//A date
		characters="0123456789/";
	} else {
		//General - just use this for length tests
		characters="";	
	}

	//Return a value based on whether this was in the list, or we have exceeded the length
	//ALWAYS allow Del and Backspace
	if (((characters.indexOf(String.fromCharCode(characterCode))<0 && characters!="") || (e.target.length>=maxLength && maxLength>0)) && characterCode!=8 && characterCode!=9 && characterCode!=46 && characterCode!=37 && characterCode!=39) {
		//Not found
		return false;
	} else {
		//Found
		return true;
	}	
}

/**
 * Remove something from the basket
 *
 * @param int The basket ID
 * @return bool False to stop the link firing
 */
function basketRemove(basketId) {
	//Get the product name
	var productName=$('#basket'+basketId+' td.item a').html();
	var basketType=$('#basket'+basketId+' td.type').html().toLowerCase();
	
	if (confirm("Are you sure you want to remove the "+basketType+" item \""+productName+"\" from your basket?")) {
		//Remove the item via proper ajax

		$.get("/ajax/basket/remove/"+basketId+"/",null,function() {
			//Remove that row from the DOM
			$('#basket'+basketId).remove();
				
			//Redirect to the basket page?
			if ($('#basketTable tbody tr').size()>1) {
				//No - it's fine
			
				//Recalculate the basket
				recalculateBasket();
			} else {
				//Now empty!
				window.location.href=httpUrl+"basket/";	
			}
		});		
	} else {
		//Reset the basket quantity
		$('#quantity'+basketId).val(oldBasketQuantities[basketId]);
	}
	
	return false;
}

/**
 * Recalculate the basket
 */
function recalculateBasket() {
	//Get each row in the table body
	var rows=$('#basketTable tbody tr');
	
	//Iterate through the rows
	var subTotal=0;
	var itemCount=0;
	var downloadCount=0;
	for (i=0;i<rows.length;i++) {
		var row=$(rows[i]);
		
		//Get the real id
		var basketId=row.attr("id").substr(6);
		
		//Get the quantity
		var quantity=parseInt($('#quantity'+basketId).val())+0;
		itemCount+=quantity;
		
		//Get the unit price
		var unitPrice=$('#basket'+basketId+' td.price').html().replace(/[^\d\.]/,"")+0;
		
		//Is this a download?
		if ($('#basket'+basketId+' td.type').html().toLowerCase()=='download') downloadCount+=quantity;
		
		//Calculate the total
		var lineTotal=unitPrice*quantity;
		subTotal+=lineTotal;
		
		//Update the line total
		$('#basket'+basketId+' td.lineTotal').html(lineTotal ? numberFormat(lineTotal,2) : '');
	}
	
	//Update the subtotal
	$('#basketTable tr.subtotal td.price').html(numberFormat(subTotal,2));

	//Update the carriage
	var carriage=calculateCarriage(itemCount-downloadCount);
	$('#basketTable tr.carriage td.price').html(numberFormat(carriage,2));
	
	//Update the total
	var total=subTotal+carriage;
	$('.total .price').html(numberFormat(total,2));
	
	//And the basket summary item count
	if (itemCount==1) {
		$('#summaryItemCount').html("1 item");
	} else {
		$('#summaryItemCount').html(itemCount+" items");
	}
}

/**
 * A basket quantity has updated
 *
 * @param Event The jquery event
 */
function updateBasketQuantity(e) {
	//Work out what triggered this
	var basketId=$(e.currentTarget).attr("id").substr(8);

	//Is it a remove?
	if ($(e.currentTarget).val()<1) {
		//It's a removal
		basketRemove(basketId);
	} else {
		//Just an update - via ajax
		$.get("/ajax/basket/update/"+basketId+"/quantity/"+parseInt($(e.currentTarget).val())+"/");
		
		//Log the new basket quantity for next time
		oldBasketQuantities[basketId]=$(e.currentTarget).val();

		//Recalculate the basket
		recalculateBasket();
		
	}

}

/**
 * Empty the basket
 *
 * @return false to stop the link firing
 */
function emptyBasket() {
	//ask for confirmation
	if (confirm("Are you sure you want to remove all items from your basket?")) {
		//Yes - empty it
		$.get("/ajax/basket/empty/1/",null,function() {
			//Redirect to the homepage
			document.location.href=httpUrl;
		});	
		
	}
	
	return false;
}

/**
 * Calculate the carriage on a given quantity
 *
 * @param int The number of items
 * @return float The carriage
 */
function calculateCarriage(items) {
	//Go through all the items
	var carriage=0;
	
	//Go through all the items
	for (var quantity=1;quantity<=items;quantity++) {
		//And loop through the rates to test
		for	(var rate in carriageRates) {
			if (quantity>=carriageRates[rate].minQuantity) {
				break;
			}
			
		}

		//Add the appropriate carriage on
		carriage+=parseFloat(carriageRates[rate].amount);
	}
	
	return carriage;
}

/**
 * Equivalent of PHP's number_format
 *
 * @param float The number
 * @param int The number of decimal places
 * @param string The decimal point character (optional)
 * @param string The thousand's separator (optional)
 * @return string The formatted number
 */
function numberFormat( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

/**
 * SHow the password reminder form
 *
 * @return Bool false to stop the link firing
 */
function showPasswordReminderForm() {
	$('#forgottenPassword').slideDown("fast");	
	
	return false;
	
}

/**
 * Send a password reminder
 *
 * @param string The email address
 * @return bool False to stop the link firing
 */
function sendPasswordReminder(email) {
	if (!email) email=$('#emailReminder').val();
	if (isValidEmail(email)) {
		//Send the reminder via ajax
		$.get("/ajax/reset/email/"+encodeURIComponent(email)+"/");
		alert("You will shortly receive your new password via e-mail.");
	} else {
		//Invalid e-mail address
		alert("You must enter a valid e-mail address!");
		
	}
	return false;	
}


/**
 * Return true if the given email address is valid
 *
 * @param string The e-mail address
 */
function isValidEmail(x) {
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(x)) {
    	return true;
    } else {
    	return false;
    }
}

/**
 * Log in
 *
 * @return bool False to stop the link firing
 */
function performLogin() {
	if (isValidEmail($('#loginEmail').val()) && $('#loginPassword').val()!="") {
		//Log in via ajax
		$.ajax({
			cache: false,
			type: "GET",
			url: "/ajax/login/email/"+encodeURIComponent($('#loginEmail').val())+"/password/"+encodeURIComponent($('#loginPassword').val())+"/",
			success: function(result) {
				if (result) {
					//Great - we're logged in.
					if (referer) {
						//Go somewhere specific
						window.location.href=referer;
					} else {
						//Go to the homepage
						window.location.href=httpUrl;
					}
				} else {
					//Oops - some random error
					alert("The e-mail address or password you supplied were incorrect. Please try again.");	
					
				}
			
			}
		});
	} else {
		//Invalid e-mail address
		alert("You must enter a valid e-mail address and password!");
		
	}	
	
	return false;
}

/**
 * Login Redirector
 */
function loginRedirect() {
	if (referer) {
		//Go somewhere specific
		window.location.href=referer;
	} else {
		//Go to the homepage
		window.location.href=httpUrl;
	}
}

/**
 * Login redirector for the checkout
 */
function checkoutLoginRedirect() {
	window.location.href=httpsUrl+"checkout/";	
	
}

/**
 * Log out
 *
 * @return bool False to stop the link firing
 */
function logOut() {
	$.get("/ajax/logout/",null,function() {
		window.location.reload();
	});
	
	return false;	
}

/**
 * Show or hide the delivery info
 *
 * @param string The enclosing ID
 */
function displayDeliveryInfo() {
	if ($('#useDelivery').attr("checked")) {
		//Show
		$('#customerForm tr.delivery').show();	
	} else {
		//Hide
		$('#customerForm tr.delivery').hide();	
		
	}	
	
}

/**
 * Check a form is correctly filled in, if so submit it - for the account form really
 *
 * @return false To stop the link from firing
 */
function checkForm() {
	theForm=$("#customerForm");
	
	//Clear the errors
	clearErrors(theForm.attr("id"));
		
	//iterate through them
	var errors=new Array();
	var errorIds=new Object();

	//Do we have an existing password?
	var passwordError=false;
	
	if ($('#existingPassword').val()) {
		//Check it syncronously
		
		//Failsafe!
		passwordError=true;
		
		$.ajax({
			async: false,
			cache: false,
			url: "/ajax/checkPassword/password/"+encodeURIComponent($('#existingPassword').val())+"/",
			type: "GET",
			success: function(retVal) {
				correctPassword=parseInt(retVal);
				
				if (correctPassword) passwordError=false;
			}
		});
		
		//If we have a pwe, report it
		if (passwordError) {
			errors.push($('#existingPasswordLabel').html()+" is incorrect");
			errorIds['existingPassword']=1;
		}
		
		//Make the other password fields required
		$('#password').parent().parent().addClass("required");
		$('#confirmPassword').parent().parent().addClass("required");

	} else if ($('#existingPassword:visible')) {
		//No existing password. Don't require them if we are already logged in
		$('#password').parent().parent().removeClass("required");
		$('#confirmPassword').parent().parent().removeClass("required");
	}
	
	//Find items
	var items=$('tr.required td input:visible, tr.required td select:visible',theForm);
	if (items.length<1) items=$('input.required:visible, select.required:visible');

	for (i=0;i<items.length;i++) {
		var item=$(items[i]);
		
		//Only do this for required items!
		var error="";
		if (!item.val() || (item.attr("type")=="checkbox" && !item.attr("checked"))) {
			error=$('#'+item.attr("id")+'Label').html()+" is blank";
			errorIds[item.attr("id")]=1;
		} else {
			//Not blank...
			if (item.hasClass("email")) {
				//Check for valid e-mail address too
				if (isValidEmail(item.val())) {
					//Valid address, but check it matches confirm
					if (item.attr("id")=="confirmemail") {
						if (item.val()!=$('#email').val()) {
							//It doesn't!
							errors.push($('#emailLabel').html()+" and "+$('#'+item.attr("id")+'Label').html()+" must match");
							errorIds[item.attr("id")]=1;
							errorIds['email']=1;
						}
					} else if (item.attr("id")=="email") {
						//Do the ajax check for the e-mail address duplicate							
						var ajaxUrl="/ajax/account/checkEmail/"+encodeURIComponent(item.val())+"/";
						var duplicateUser=1;

						$.ajax({
							async: false,
							cache: false,
							url: ajaxUrl,
							type: "GET",
							success: function(retVal) {
								duplicateUser=parseInt(retVal);
							}
						});
						
						if (duplicateUser>0) {
							//We can't use this user
							errors.push("The "+$('#emailLabel').html()+" is already in use - please try a different address, or <a href=\"./\" onclick=\"return sendPasswordReminder('"+item.val()+"');\">click here</a> to reset your password.");
							errorIds[item.attr("id")]=1;	
						}
						
					}
				} else {
					//Invalid address
					if (error) {
						error+=" and the e-mail address is invalid";
					} else {
						error+=$('#'+item.attr("id")+'Label').html()+" has an invalid e-mail address";	
					}
					errorIds[item.attr("id")]=1;
				}
				
			} else if (item.attr("id")=="confirmPassword") {
				//It's the password - so check them	
				if (item.val()!=$('#password').val()) {
					errors.push($('#passwordLabel').html()+" and "+$('#'+item.attr("id")+'Label').html()+" must match");
					errorIds[item.attr("id")]=1;
					errorIds['password']=1;
				}				
			}
			
		}
		
		//Add any error
		if (error) errors.push(error);
	}

	//Now show the errors if any
	if (errors.length>0) {
		var plural=false;
		if (errors.length>1) plural=true;

		showErrors("errors"+ucFirst(theForm.attr("id")),"<ul>\n\t<li>"+errors.join("</li>\n\t<li>")+"</li>\n</ul>\n",plural);

		//And add the error class to each row
		var firstId="";
		for (var id in errorIds) {
			if (firstId=="") firstId=id;

			//Give it's parent tr the class "error"
			$('#'+id).parent().parent().addClass("error");
			$('#'+id).addClass("error");
			$('#'+id+"Label").addClass("error");
		}
		
		//Focus the first item
		if (firstId) $('#'+firstId).focus();
		
		//Return false to show it failed
// 		return false;
	} else {
		//Submit the form
		//Hide any outstanding errors
		hideErrors("errors"+ucFirst(theForm.attr("id")));
		
		//Compose array of data
		var postData=new Object();
		
		//Make the button greyed out
		var oldButtonHtml=$('#'+theForm.attr("id")+"Button").html();
		$('#'+theForm.attr("id")+"Button").addClass("disabledButton").html("Please Wait...");
	
		//This bit of code simulates a normal browser based form post, and as such uses "name" attributes and not "id" in the output post
		var fields=theForm.find("input,select,textarea");
		for (i=0;i<fields.length;i++) {
			var field=$(fields[i]);
			
			//Get the field value;
			var fVal;
			if (field.attr("type")=="checkbox") {
				if (field.attr("checked")) {
					fVal=1;
				} else {
					fVal=0;
				}
			} else if (field.attr("type")=="radio") {
				if (field.attr("checked")) {
					fVal=field.val();	
				}
			} else {
				fVal=field.val();
			}
			
			//Add to the order
			if (field.attr("name")) postData[field.attr("name")]=fVal;
		}
		//Add the unique ID
		if (uniqueId) postData['uniqueId']=uniqueId;
		
		//Now post that
		$.post(theForm.attr("action"),postData,function(results) {
			//Parse the results
			if (results['errors'].length>0) {

				//An error(s) occurred! Display accordingly
				var plural=false;
				if (results['errors'].length>1) plural=true;
				showErrors("errorsCustomerForm","<ul>\n\t<li>"+results['errors'].join("</li>\n\t<li>")+"</li>\n</ul>\n",plural);
				//And add the error class to each row
				if (results['errorFieldCount']>0) {
					var firstId="";

					for (var id in results['errorFields']) {
						if (firstId=="") firstId=results['errorFields'][id];
						//Give it's parent tr the class "error"
						$('#'+results['errorFields'][id]).parent().parent().addClass("error");
						$('#'+id).addClass("error");
						$('#'+id+"Label").addClass("error");
					}
					
				}
					
				//Focus the first error item
				if (firstId) $('#'+firstId).focus();
									
			} else {
				//Success with whatever we were doing
				
				//Any account control?
				if (results['accountControlHtml']) $('#accountControl').html(results['accountControlHtml']);
				
				//Notity the user
				if (results['noticeHtml']) showNotice("errorsCustomerForm",results['noticeHtml']);
				
				//Change the button text
				if (results['buttonText']) {
					$('.buttonText').html(results['buttonText']);
					oldButtonHtml=results['buttonText'];
				}
				
				//Change the main heading text?
				if (results['mainHeadingText']) $('.mainHeading').html(results['mainHeadingText']);
				
				//Blank any passwords
				$('#existingPassword').val("");
				$('#password').val("");
				$('#confirmPassword').val("");
				
				//Run anything?
				if (results['call']) eval(results['call']+"(results)");
				
				//Redirect?
				if (results['redirect']) window.location.href=results['redirect'];
			}

			$('#'+theForm.attr("id")+"Button").removeClass("disabledButton").html(oldButtonHtml);
			
						
		},"json");		
	}
	
	return false;
}

/**
 * Show the existing password box etc.
 */
function showExistingPassword() {
	$('#password').parent().parent().removeClass("required");
	$('#confirmPassword').parent().parent().removeClass("required");
	$('#existingPassword').parent().parent().show();
}

/**
 * Hide currently visible errors
 *
 * @param string The div ID to hide
 */
function hideErrors(divId) {
	$('#'+divId).hide();
	if (divId) $("tr.error",$('#'+divId.substr(6).toLowerCase())).removeClass("error");
}


function ucFirst (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: ucfirst('kevin van zonneveld');
    // *     returns 1: 'Kevin van zonneveld'
 
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}


/**
 * Show an error
 *
 * @param string The enclosing ID
 * @param string The error text
 * @param bool Whether it's plural (default false)
 */
function showErrors(divId,errorText,plural) {
	//Hide any existing error first
	$('#'+divId).hide().removeClass("notice");
	$("tr.error",$('#'+divId.substr(6).toLowerCase())).removeClass("error");
	
	//Set the details
	$('#'+divId+' div.errorText').html(errorText);
	if (plural) {
		$('#'+divId+' h3 span').show();
	} else {
		$('#'+divId+' h3 span').hide();
	}
	
	//Show the div
	$('#'+divId).slideDown();
	
}

/**
 * Show a notice
 *
 * @param string The enclosing ID
 * @param string The notice text
 */
function showNotice(divId,noticeText) {
	//Hide any existing notice or error
	$('#'+divId).hide();
	$("tr.error",$('#'+divId.substr(6).toLowerCase())).removeClass("error");
	
	//add the notice class
	$('#'+divId).addClass("notice");
	
	//Set the text
	$('#'+divId+' div.errorText').html(noticeText);

	//Show the div
	$('#'+divId).slideDown();
	
}

/**
 * Clear errors from a section
 *
 * @param string The section
 */
function clearErrors(section) {
	//Remove the error class from everything here first
	$('#'+section+' .validate').parent().parent().removeClass("error");
	$("tr.error",$('#'+section)).removeClass("error");

}

/**
 * Hide an error
 *
 * @param object The object firing
 * @return bool False to stop the link from firing
 */
function closeErrors(objFire) {
	$(objFire).parent().parent().slideUp();
	
	return false;
}

/**
 * Checkout - show forgotten password options
 *
 * @return Bool false to stop the link from firing
 */
function showForgottenPassword() {
	//Copy any e-mail address found
	$('#emailReminder').val($('#loginEmail').val());

	$('#existing').hide();
	$('#forgottenPassword').show();	
	
	return false;
}

/**
 * Hide the forgotten password section
 *
 * @return boolean false To stop the link from firing
 */
function hideForgottenPassword() {
	$('#forgottenPassword').hide();
	$('#existing').show();	
	return false;
}

/**
 * Reset the checkout password
 *
 * @return Bool false to stop the link firing
 */
function resetCheckoutPassword() {
	var email=$('#emailReminder').val();
	if (isValidEmail(email)) {
		//Send the reminder via ajax
		$.get("/ajax/reset/email/"+encodeURIComponent(email)+"/");
		alert("You will shortly receive your new password via e-mail.");
		
		hideForgottenPassword();
	} else {
		//Invalid e-mail address
		alert("You must enter a valid e-mail address!");
		
	}
		
	return false;
}

/**
 * Show the security info bits
 *
 * @return bool false to stop the link firing
 */
function showSecurityInfo() {
	$('p.securityInfo').slideDown("fast");
	return false;
}

/**
 * Hide the security info bits
 *
 * @return bool false to stop the link firing
 */
function hideSecurityInfo() {
	$('p.securityInfo').hide();
	return false;
}

//Flag to remember if the card name has changed from itself or not. If so, we don't change it again.
var cardNameIsDefault=true;

/**
 * Bind card name change events
 */
function bindCardChangeEvents() {
	$('#firstName').bind("change",cardNameChange);
	$('#surname').bind("change",cardNameChange);
	$('#cardName').bind("change",cardNameChange);
}

//This is set until a card name change has occurred
var cardNameIsDefault=true;

/**
 * The card name has changed probably
 */
function cardNameChange() {
	if ($(this).attr("id")) {
		//We have a valid id
			
		if (cardNameIsDefault) {
			//Yes - we can change it
			if ($(this).attr("id")=="cardName") {
				//The card name has been changed, so disable further changes
				cardNameIsDefault=false;
			} else {
				//One of the proper fields has changed, so recalculate the card name
				var cardName=$('#firstName').val();
				if (cardName) cardName+=" ";
				cardName+=$('#surname').val();
				cardName=cardName.toUpperCase();
				$('#cardName').val(cardName);
			}
			
		}	
	}
}

/**
 * Show the 3d authentication form
 *
 * @param object The results
 */
function show3dForm(results) {
	//So we should have results['3dSecure'] populated with some stuff now - stuff them into the 3dform, then submit it
	$('#3dPaReq').val(results['3dSecure']['PaReq']);
	$('#3dTermUrl').val(results['3dSecure']['TermURL']);
	$('#3dMD').val(results['3dSecure']['MD']);
	$('#3dForm').attr("action",results['3dSecure']['ACSURL']).submit();
	
	//Hide the top stuff
	$('.hideWhen3d',$('#containerContent')).hide();
	$('.showWhen3d',$('#containerContent')).show();
	
}
