// JavaScript Document

function formCheck(form) {
	var firstName = trimString(form.first_name.value);
	form.first_name.value = firstName;
	var phone = trimString(form.phone.value);
	form.phone.value = phone;
	var company = trimString(form.company.value);
	form.company.value = company;
	var email = trimString(form.email.value);
	form.email.value = email;
	
	if ((firstName == "") || (phone == "") || (company == "") || (email == "")) {
		alert("Please fill required fields.");
		return false;
	}
	if (phoneNumber(form.phone, "Phone") == false)
		return false;
	else if (phone.length < 7) {
		alert("Phone number too short.");
		return false;
	}
	if (emailCheck(form.email.value) == false)
		return false;

	return true;
}
//---------------------------------------------------------------

/*
	Removes the spaces from begin of string and from end.
	It means, if string is "  string   " it makes "string"
	Params:
		str string [string witch need to check]
*/
function trimString (str) {

	while (str.charAt(0) == ' ')
		str = str.substring(1);
	while (str.charAt(str.length - 1) == ' ')
		str = str.substring(0, str.length - 1);

	return str;
}
//---------------------------------------------------------------

function phoneNumber(valField, valName) {
	var fieldValue = valField.value;
	var numbers = "0123456789 ";
	var returnVal = true;
	
	for (var i=0; i<fieldValue.length && returnVal == true; i++) {
		if (numbers.indexOf(fieldValue.charAt(i)) == -1) {
			returnVal = false;
			alert(valName + " number should contain only numbers.");
		}
	}
	
	return returnVal;
}
//---------------------------------------------------------------

function emailCheck(email) {
	if (email.indexOf('@', 0) == -1) {
		alert("Please enter a valid email address.");
		return false;
	}
	
	if (email.indexOf('.', 0) == -1) {
		alert("Please enter a valid email address.");
		return false;
	}
	
	if (email.length<7) {
		alert("Email address too short.");
		return false;
	}
	
	return true;
}
//---------------------------------------------------------------
