// JavaScript Document

function checkEmail(id) {
	var mail = document.getElementById(id);
	// Make sure that something was entered and that it looks like a valid email address
	var error = '';
	if (!mail) {
		return false;
	}
	
	
	var mailstring = mail.value;
	
	if (mailstring.length == 0) {
		error = 'You didn\'t enter an email';
		alert(error);
		return false;
	}
	if (mailstring.indexOf('@') == -1) {
		error = 'This email has no @ sign';
		alert(error);
		return false;
	} else if (mailstring.lastIndexOf('@') != mailstring.indexOf('@')) {
		error = 'An email may only contain one @ sign.';
		alert(error);
		return false;
	}
	
	var chunks = mailstring.split('@');
	var n = chunks[0];
	
	if (n.length == 0) {
		error = 'There is no username part in the email';
		alert(error);
		return false;
	}
	
	if (n.substring(0, 1) == '.' || n.substring(0, 1) == '-' ||
		n.substr(n.length - 1, 1) == '.') {
			error = 'The user name may not start with a period or hyphen';
			error += ' and may not end with a period';
			alert(error);
			return false;
	}
	
	if (!checkValidCharacters(n)) {
		error = 'The email name contains invalid characters';
		alert(error);
		return false;
	}
	
	n = chunks[1];
	if (n.length == 0) {
		error = 'There is no domain';
		alert(error);
		return false;
	}
	
	if (n.indexOf('.') == -1) {
		error = 'The domain has no . sign';
		alert(error);
		return false;
	} 
	
	if (n.substring(0, 1) == '.' || n.substring(0, 1) == '-' ||
		n.substr(n.length - 1, 1) == '-' ||
		n.substr(n.length - 1, 1) == '.') {
			error = 'The domain name may not start or end with a hyphen or period';
			alert(error);
			return false;
	}
	
	if (!checkValidCharacters(n)) {
		error = 'The domain name contains invalid characters';
		alert(error);
		return false;
	}
	return true;
}

function checkValidCharacters(n) {
	for (var i = 0; i < n.length; i++) {
		currentCode = n.charCodeAt(i);
		if (currentCode == 45 || currentCode == 46 ||
			currentCode == 95 ||
			( currentCode > 96 && currentCode < 123) ||
			(currentCode > 47 && currentCode < 58)) {
				continue;
		} else {
			return false;
		}
	}
	return true;
}


function checkComments(id) {
	var comment = document.getElementById(id);
	
	return comment.value.length > 0;
}

function validate() {
	if (!checkEmail("email")) {
		return false;
	}
	
	if (!checkComments("message")) {
		alert("Fill out a comment.");
		return false;
	}
	
	
	return true;
}
