function showCommentStars(numStars) {
	if (numStars >= 5) {
		$('#rating_1_star, #rating_2_star, #rating_3_star, #rating_4_star, #rating_5_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/star.png');
	} else if (numStars == 4) {
		$('#rating_1_star, #rating_2_star, #rating_3_star, #rating_4_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/star.png');
		$('#rating_5_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/grey_star.png');
	} else if (numStars == 3) {
		$('#rating_1_star, #rating_2_star, #rating_3_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/star.png');
		$('#rating_4_star, #rating_5_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/grey_star.png');
	} else if (numStars == 2) {
		$('#rating_1_star, #rating_2_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/star.png');
		$('#rating_3_star, #rating_4_star, #rating_5_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/grey_star.png');
	} else if (numStars == 1) {
		$('#rating_1_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/star.png');
		$('#rating_2_star, #rating_3_star, #rating_4_star, #rating_5_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/grey_star.png');
	} else {
		$('#rating_1_star, #rating_2_star, #rating_3_star, #rating_4_star, #rating_5_star').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/grey_star.png');
	}
}

function clearCommentStars() {
	showCommentStars($('#rating').val());
}

function setCommentStars(numStars) {
	$('#rating').val(numStars);
	$('#post_comment').attr('disabled', false);
	$('#post_comment').focus();
}

function showLogInForm() {
	$('#log_in_form_surround, #log_in_form_background').fadeIn(500);
}

function showForgottenPasswordForm() {
	$('#log_in_form_surround').fadeOut(500, function() {
		$('#forgotten_password_form_surround').fadeIn(500);
	});
}

function hideForgottenPasswordForm() {
	if ($('#log_in_error_box').css('display') != 'none') {
		$('#log_in_error_box').fadeOut(100);
	}

	$('#forgotten_password_form_surround, #log_in_form_background').fadeOut(500, function() {
		document.getElementByIf('forgotten_password_form').reset();
	});
}

function hideLogInForm() {
	if ($('#log_in_error_box').css('display') != 'none') {
		$('#log_in_error_box').fadeOut(100);
	}

	$('#log_in_form_surround, #log_in_form_background').fadeOut(500, function() {
		document.getElementById('log_in_form').reset();
	});
}

function postComment() {
	if ($('#rating').val() == 0) {
		alert('You need to a rating star before you can post your rating.');
		return false;
	}
	$('#post_comment').html('<img class="button-loading-icon" src="' + siteUri + 'themes/bwbroadcast/images/button-loading.gif" alt="Loading&#x2026; Please wait." title="Loading&#x2026; Please wait" /> Posting comment&#x2026;');
	$('#post_comment').attr('disabled', true);
	$('#post_comment').addClass('submit-form-button-disabled');
	$('#post_comment').removeClass('submit-form-button');

	var requestUri = siteUri + 'ajax/comment/post';
	$.getJSON(requestUri, {
			rating: $('#rating').val(),
			preset_id: $('#preset_id').val(),
			comment: $('#comment').val()
		}, function(response, statusMsg) {
		if (response.success) {
			$('#preset_rating').attr('src', siteUri + 'themes/bwbroadcast/images/ratings/' + response.roundedRating + '-stars.png');
			$('#preset_rating').attr('alt', response.rating + ' star(s)');
			$('#preset_rating').attr('title', response.rating + ' star(s)');

			var html = '<div id="newly_posted_comment_surround" style="display: none; background: #ffc;" class="comment-surround"><h4>' + response.username;
				if ($('#rating').val() > 0) {
					html += ' <img src="' + siteUri + 'themes/bwbroadcast/images/ratings/' + $('#rating').val() + '-stars.png" style="display: inline-block;" />';
				}
			html += '</h4><h5>' + dateFormat(new Date(), 'h:MM "on" dddd, dS mmmm, yyyy') + '</h5>' + formatText($('#comment').val()) + '</div>';
			$('div.comments-surround h3:first-child').after(html);
			$('#no_comments, #comment_form_surround').slideUp(500, function() {
				window.location.hash = 'comments';
				$('#newly_posted_comment_surround').slideDown(500, function() {
					$('#newly_posted_comment_surround').animate({
						backgroundColor: '#fff'
					}, 2000);
				});
			});
		} else {
			alert('Sorry, but we couldn\'t post your comment.  Please try again later.');
			$('#comment_form_surround').slideUp(500);
		}
	});
	return false;
}

function ratePassword(password, feedbackBox) {
	var hasLower = password.match(/[a-z]/);
	var hasCaps = password.match(/[A-Z]/);
	var hasDigits = password.match(/[0-9]/);
	var hasOther = password.match(/[^a-zA-Z0-9]/);

	if (password.length < 8) {
		$('#' + feedbackBox).html('<span>Your password is too short!</span><br />Passwords need to be at least eight characters long.');
		$('#' + feedbackBox).attr('class', 'weak-password');
	} else if (hasCaps && hasLower && hasDigits && hasOther) {
		$('#' + feedbackBox).html('<span>This is a really good password</span>');
		$('#' + feedbackBox).attr('class', 'strong-password');
	} else if ((hasCaps && hasLower && hasDigits && !hasOther) ||
			(hasCaps && hasLower && !hasDigits && hasOther) ||
			(hasCaps && !hasLower && hasDigits && hasOther) ||
			(!hasCaps && hasLower && hasDigits && hasOther)) {
		$('#' + feedbackBox).html('<span>This is a good password</span>');
		$('#' + feedbackBox).attr('class', 'strong-password');
	} else if ((hasCaps && hasLower && !hasDigits && !hasOther) ||
			(hasCaps && !hasLower && hasDigits && !hasOther) ||
			(!hasCaps && hasLower && hasDigits && !hasOther) ||
			(hasCaps && !hasLower && !hasDigits && hasOther) ||
			(!hasCaps && hasLower && !hasDigits && hasOther) ||
			(!hasCaps && !hasLower && hasDigits && hasOther)) {
		$('#' + feedbackBox).html('<span>This password is O.K.</span><br />You can make this a better password by having capital letters, lower-case letters and numbers in it.');
		$('#' + feedbackBox).attr('class', 'average-password');
	} else {
		$('#' + feedbackBox).html('<span>This password is too easy to guess.</span><br />Weak passwords are easy for people and computers to guess.  You need to have both letters and numbers in your password.');
		$('#' + feedbackBox).attr('class', 'weak-password');
	}
}

function comparePasswords(passwordA, passwordB, passwordErrorBox) {
	if (passwordA != passwordB) {
		$('#' + passwordErrorBox).html('<span>The passwords you\'ve provided don\'t match.</span><br />Please re-type them to make sure that you haven\'t made a mistake whilst typing your password.');
	} else {
		$('#' + passwordErrorBox).html('&#xa0;');
	}
}

function clearPasswordRating(feedbackBox) {
	$('#' + feedbackBox).html('&#xa0;');
	$('#' + feedbackBox).removeClass('weak-password');
	$('#' + feedbackBox).removeClass('average-password');
	$('#' + feedbackBox).removeClass('strong-password');
}

function clearPasswordError(passwordErrorBox) {
	$('#' + passwordErrorBox).html('&#xa0;');
}

function checkEmailIsValid(email, emailErrorBox) {
	if (!email.match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$/)) {
		$('#' + emailErrorBox).html('<span>This is not a valid email address.</span><br />Please check that you\'ve typed it correctly, as we need this to verify your account.');
	} else {
		$('#' + emailErrorBox).html('&#xa0;');
	}
}

function isValidEmail(email) {
	return email.match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$/);
}

function compareEmails(emailA, emailB, emailErrorBox) {
	if (emailA != emailB) {
		$('#' + emailErrorBox).html('<span>The email addresses are different.</span><br />Please check you\'ve typed your email address correctly in both boxes, as we need this to verify your account.');
	} else {
		$('#' + emailErrorBox).html('&#xa0;');
	}
}

function formatText(text) {
	var formattedText = '';
	var lines = text.split(/[\r\n]+/);

	for (var i = 0; i < lines.length; i++) {
		formattedText += '<p>' + lines[i].replace(/^\s+/, '').replace(/\s+$/, '') + '</p>';
	}

	return formattedText;
}

function showUploadPresetForm() {
	$('#upload_preset_form_background, #upload_preset_form_box').fadeIn(500);
}

function closeUploadPresetForm() {
	$('#upload_preset_form_background, #upload_preset_form_box').fadeOut(500, function() {
		$('#upload_preset_form').reset();
	});
}

function displayProcessorThumbnail() {
	if ($('#processor').attr('selectedIndex') == 0) {
		$('#processor_thumbnail').attr('src', siteUri + 'themes/bwbroadcast/images/clear.gif');
	} else {
		var i;
		var found = false;
		for (i = 0; i < processors.length; i++) {
			if (processors[i] == $('#processor').val()) {
				found = true;
				break;
			}
		}
		if (found) {
			$('#processor_thumbnail').attr('src', siteUri + 'themes/bwbroadcast/images/' + processorThumbnails[i]);
		}
	}
}

function uploadPreset() {
	var errors = [];
	var focusField = false;

	if (!$('#firmware_version').val().replace('/(^\s+|\s+$)/', '').match(/^[1-9][0-9]*(\.[0-9]+)?$/)) {
		errors.push('You need to give the firmware version (eg: 1.04, 2.2, 3, etc.)');
		focusField = 'firmware_version';
	}

	if ($('#processor').val().replace('/(^\s+|\s+$)/', '') == '') {
		errors.push('You need to pick the processor for this preset from the list.');
		if (!focusField) {
			focusField = 'processor';
		}
	}

	if ($('#preset_file').val().replace('/(^\s+|\s+$)/', '') == '') {
		errors.push('You need to browse for and choose your preset file.');
		if (!focusField) {
			focusField = 'preset_file';
		}
	}

	if ($('#description').val().replace('/(^\s+|\s+$)/', '') == '') {
		errors.push('You need to give your preset a description.');
		if (!focusField) {
			focusField = 'description';
		}
	}

	if (errors.length > 0) {
		var message = 'Please correct the following errors before uploading your preset:\n';
		for (var i = 0; i < errors.length; i++) {
			message += '\n\t-- ' + errors[i];
		}
		$('#' + focusField).focus();
		alert(message);
	} else {
		$('#upload_preset_form_controls').fadeOut(500, function() {
			$('#title_text').html($('#preset_file').val());
			$('#firmware_version_text').html($('#firmware_version').val());
			$('#description_text').html($('#description').val().substr(0, 64) + '&#x2026;');
			$('.upload-preset-form-body div.field-surround').slideUp(150);
			$('#upload_preset_form_title').html('Uploading preset&#x2026;');
			$('#upload_preset_form_box').animate({
				height: '150px',
				marginTop: '-75px'
			}, 500);
			$('#preset_details_text').slideDown(500, function() {
				$('#loading_bar_surround').fadeIn(500, function() {
					$('#info_text').html('Uploading ' + $('#preset_file').val() + '&#x2026;');
					$('#upload_preset_form').ajaxSubmit({
						success: function(response, statusMsg) {
							response = $.evalJSON(response);
							if (response.success) {
								$('#title_text').html(response.presetName);
								$('#info_text').html('Preset \'' + response.presetName + '\' uploaded successfully.  Reloading&#x2026;');
							} else {
								$('#info_text').html('Preset upload failed! :(');
								alert('Sorry, but an error occurred whilst uploading your file.  The error was:\n\n\t-- ' + response.errorMessage);
							}
							window.location.href = siteUri + $('#processor').val() + '/presets';
						},
						error: function() {
							alert('Sorry, but an error occurred whilst uploading your file.  Please try again later, or contact us if this error has appeared before.');
							window.location.href = siteUri + $('#processor').val() + '/presets';
						}
					});
				});
			});
		});
	}
	return false;
}

function processLogIn() {
	var errors = [];
	var emailError = false;
	var passwordError = false;

	if ($('#email').val().length <= 0) {
		emailError = true;
	}
	
	if ($('#drowssap').val().length <= 0) {
		passwordError = true;
	}

	if (emailError && passwordError) {
		errors.push('You need to type your email and password.');
	} else if (emailError) {
		errors.push('You need to type your email address.');
	} else if (passwordError) {
		errors.push('You need to type your password.');
	}
	
	if(errors.length <= 0) {
		if ($('#log_in_error_box').css('display') != 'none') {
			$('#log_in_error_box').fadeOut(100);
		}

		$('#log_in_form').ajaxSubmit({
			success: function(response, statusMsg) {
				response = $.evalJSON(response);
				if (response.success) {
					window.location.href = response.redirect;
				} else {
					$('#log_in_error_title').html(response.errorTitle);
					$('#log_in_error_text').html(response.errorMessage);
					$('#log_in_error_box').fadeIn(500);
				}
			},
			error: function() {
				alert('Sorry, but we are currently unable to process log-ins.  Please try again later.');
				$('#log_in_form_surround, #log_in_form_background, #log_in_error_box').fadeOut(500);
			}
		});
	} else {
		$('#log_in_error_title').html('Missing details');
		var message = 'Please correct the following errors before clicking "Log in&#x2026;" again:<div style="font-size: 2px;">&#xa0;</div>';
		for (var i = 0; i < errors.length; i++) {
			if (i > 0) {
				message += '<br />';
			}
			message += '&#x2013;' + errors[i];
		}
		$('#log_in_error_text').html(message);
		$('#log_in_error_box').fadeIn(500);
	}
	return false;
}

function processForgottenPassword() {
	var errors = [];
	var emailMissing = false;
	var emailInvalid = false;

	if ($('#forgotten_email').val().length <= 0) {
		emailMissing = true;
	} else if (!isValidEmail($('#forgotten_email').val())) {
		emailInvalid = true;
	}
	
	if(!emailMissing && !emailInvalid) {
		if ($('#log_in_error_box').css('display') != 'none') {
			$('#log_in_error_box').fadeOut(100);
		}

		$('#forgotten_password_form').ajaxSubmit({
			success: function(response, statusMsg) {
				response = $.evalJSON(response);
				if (response.success) {
					alert('Your password has been reset, and an email containing your new password has been sent to the address you provided.  Please check your inbox and log in with the new password.');
					$('#log_in_form_background, #log_in_error_box, #forgotten_password_form_surround').fadeOut(500);
				} else {
					$('#log_in_error_title').html(response.errorTitle);
					$('#log_in_error_text').html(response.errorMessage);
					$('#log_in_error_box').fadeIn(500);
				}
			},
			error: function() {
				alert('Sorry, but we are currently unable to process password retrievals.  Please try again later.');
				$('#log_in_form_background, #log_in_error_box, #forgotten_password_form_surround').fadeOut(500);
			}
		});
	} else {
		if (emailMissing) {
			$('#log_in_error_title').html('Missing details');
			$('#log_in_error_text').html('You need to type your email address to reset your password.');
		} else if (emailInvalid) {
			$('#log_in_error_title').html('Invalid email');
			$('#log_in_error_text').html('The email address you\'ve typed is not valid.<br /><br />Please make sure that you\'ve typed it correctly.');
		}
		$('#log_in_error_box').fadeIn(500);
	}
	return false;
}

function format_telno(num, convert_mode, include_zero_in_intl_uk) {
	var output = '';
	// Strip anything that's not 0123456789+#X
	num = num.replace(/[^0-9\+#X]/g, '');

	// Convert ^([^0\+]) to +\1
	num = num.replace(/^([^0\+])/g, '+$1');

	// Convert 00# to +#
	num = num.replace(/^00/g, '+');

	// Strip the (0) from +44(0)## numbers
	num = num.replace(/^\+440/, '+44');

	if (num.match(/^0/)) {
		if (convert_mode == 'uk_to_intl') {
			if (include_zero_in_intl_uk) {
				output = '+44(0)';
			} else {
				output = '+44';
			}

			if (num.match(/^02/)) {
				output += '2' + num.substr(2, 1) + ' ' + num.substr(3, 4) + '-' + num.substr(7, 4);
			} else if (num.match(/^011[3-8]/)) {
				output += '11' + num.substr(3, 1) + ' ' + num.substr(4, 3) + '-' + num.substr(7, 4);
			} else if (num.match(/^01[2-9]1/)) {
				output += '1' + num.substr(2, 1) + '1 ' + num.substr(4, 3) + '-' + num.substr(7, 4);
			} else if (num.match(/^01[2-9]/)) {
				output += '1' + num.substr(2, 3) + ' ' + num.substr(5, 3) + '-' + num.substr(8, 3);
			} else if (num.match(/^07/)) {
				output += '7' + num.substr(2, 3) + ' ' + num.substr(5, 3) + '-' + num.substr(8, 3);
			} else if (num.match(/^0[3-68]/)) {
				output += num.substr(1, 3) + ' ' + num.substr(4, 3) + '-' + num.substr(7, 4);
			} else if (num.match(/^05/)) {
				output += '5' + num.substr(2, 1) + ' ' + num.substr(3, 4) + '-' + num.substr(7, 4);
			} else if (num.match(/^09/)) {
				output += '9' + num.substr(2, 3) + ' ' + num.substr(5, 3) + '-' + num.substr(8, 3);
			} else {
				output = num;
			}
		} else {
			output = '(0';

			if (num.match(/^02/)) {
				output += '2' + num.substr(2, 1) + ') ' + num.substr(3, 4) + '-' + num.substr(7, 4);
			} else if (num.match(/^011[3-8]/)) {
				output += '11' + num.substr(3, 1) + ') ' + num.substr(4, 3) + '-' + num.substr(7, 4);
			} else if (num.match(/^01[2-9]1/)) {
				output += '1' + num.substr(2, 1) + '1) ' + num.substr(4, 3) + '-' + num.substr(7, 4);
			} else if (num.match(/^01[2-9]/)) {
				output += '1' + num.substr(2, 3) + ') ' + num.substr(5, 3) + '-' + num.substr(8, 3);
			} else if (num.match(/^07/)) {
				output += '7' + num.substr(2, 3) + ') ' + num.substr(5, 3) + '-' + num.substr(8, 3);
			} else if (num.match(/^0[3468]/)) {
				output += num.substr(1, 3) + ') ' + num.substr(4, 3) + '-' + num.substr(7, 4);
			} else if (num.match(/^05/)) {
				output += '5' + num.substr(2, 1) + ') ' + num.substr(3, 4) + '-' + num.substr(7, 4);
			} else if (num.match(/^09/)) {
				output += '9' + num.substr(2, 3) + ') ' + num.substr(5, 3) + '-' + num.substr(8, 3);
			} else {
				output = num;
			}
		}
	} else if (num.match(/^\+44/)) {
		if (convert_mode == 'intl_to_uk') {
			output = '(0';

			if (num.match(/^\+442/)) {
				output += '2' + num.substr(4, 1) + ') ' + num.substr(5, 4) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+4411[3-8]/)) {
				output += '11' + num.substr(5, 1) + ') ' + num.substr(6, 3) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+441[2-9]1/)) {
				output += '1' + num.substr(4, 1) + '1) ' + num.substr(6, 3) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+441[2-9]/)) {
				output += '1' + num.substr(4, 3) + ') ' + num.substr(7, 3) + '-' + num.substr(10, 3);
			} else if (num.match(/^\+447/)) {
				output += '7' + num.substr(4, 3) + ') ' + num.substr(7, 3) + '-' + num.substr(10, 3);
			} else if (num.match(/^\+44[3468]/)) {
				output += num.substr(3, 3) + ') ' + num.substr(6, 3) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+445/)) {
				output += '5' + num.substr(4, 1) + ') ' + num.substr(5, 4) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+449/)) {
				output += '9' + num.substr(4, 3) + ') ' + num.substr(7, 3) + '-' + num.substr(10, 3);
			} else {
				output = num;
			}
		} else {
			if (include_zero_in_intl_uk) {
				output = '+44(0)';
			} else {
				output = '+44';
			}

			if (num.match(/^\+442/)) {
				output += '2' + num.substr(4, 1) + ' ' + num.substr(5, 4) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+4411[3-8]/)) {
				output += '11' + num.substr(5, 1) + ' ' + num.substr(6, 3) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+441[2-69]1/)) {
				output += '1' + num.substr(4, 1) + '1 ' + num.substr(6, 3) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+447/)) {
				output += '7' + num.substr(4, 3) + ' ' + num.substr(7, 3) + '-' + num.substr(10, 3);
			} else if (num.match(/^\+44[3468]/)) {
				output += num.substr(3, 3) + ' ' + num.substr(6, 3) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+445/)) {
				output += '5' + num.substr(4, 1) + ' ' + num.substr(5, 4) + '-' + num.substr(9, 4);
			} else if (num.match(/^\+449/)) {
				output += '9' + num.substr(4, 3) + ' ' + num.substr(7, 3) + '-' + num.substr(10, 3);
			} else {
				output = num;
			}
		}
	} else if (num.match(/^\+/)) {
		output = '+';

		if (num.match(/\+1/)) {
			output += '1.' + num.substr(2, 3) + '.' + num.substr(5, 3) + '.' + num.substr(8, 4);
		} else {
			output = num;
		}
	} else {
		output = num;
	}

	return output;
}
