//defines validation functions for the various forms on the site
//validates for where user enters review
function validateCarSearch(theForm)
{
	//check model is under 50 letters
	if (theForm.model.value != "" && theForm.model.value.length > 50)
	{
                alert("Please enter less than 50 letters in the \"model\" field.");
		theForm.model.focus();
		return false;
	}
	//check manufacturer selected
	if (theForm.postCode.value != "" && theForm.postCode.value.length > 10)
	{
                alert("Please enter less than 10 letters in the \"Post Code\" field.");
		theForm.postCode.focus();
		return false;
	}
        //if all is correct, allow the form to be sent
	else return true;
}

//validate carWanted form
function validateCarWanted(theForm) {

        if(theForm.manufacturer.value=="Please select...")
	{
		alert("Please select a manufacturer");
		theForm.manufacturer.focus()
		return false
	}
	if(theForm.model.value=="")
	{
		alert("Please enter car details");
		theForm.model.focus()
		return false
	}
	if(theForm.name.value=="")
	{
		alert("Please enter a Contact Name");
		theForm.name.focus()
		return false
	}
	if (theForm.phoneNumber.value=="")
	{
		alert("Please enter a contact Tel No");
		theForm.phoneNumber.focus()
		return false
	}
	if (! isNumberOrSpace(theForm.phoneNumber.value))
 	 {
  	  alert("Your Tel. No must be a numeric value");
  		theForm.phoneNumber.focus()
		return false
        }
	if (theForm.email.value=="")
	{
		alert("Please enter a contact e-mail address");
		theForm.email.focus()
		return false
	}

  // remove all spaces from aText text field 
  // and place the result into the right text field
   theForm.email.value = 
   theForm.email.value.replace(/ /g, "");

	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	var matchArray=theForm.email.value.match(emailPat)
	if (matchArray==null) {
		alert("Email address is invalid(check @ and .'s)")
		theForm.email.focus()
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	if (user.match(userPat)==null) {
	    alert("Email address is invalid, Please correct.")
	    theForm.email.focus()
	    return false
	}
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        alert("Email address is invalid, Please correct.")
		    theForm.email.focus()
			return false
		    }
	    }
	}
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Email address is invalid, Please correct.")
		theForm.email.focus()
	    return false
	}
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 ||
	    domArr[domArr.length-1].length>3) {
	   alert("Email address is invalid, Please correct.")
	   theForm.email.focus()
	   return false
	}
	if (len<2) {
	   var errStr="Email address is invalid, Please correct."
	   alert(errStr)
	   theForm.email.focus()
	   return false	}
	if (theForm.budget.value=="")
		{
		alert("Please enter your budget");
		theForm.budget.focus()
		return false
		}

	if (theForm.postCode.value=="")
		{
			alert("Please enter a valid post code");
			theForm.postCode.focus()
			return false
		}
        if (!isPositiveWholeNumber(theForm.budget.value))
        {
			alert("Please enter a numeric budget");
			theForm.budget.focus()
			return false

        }



}

//validates the form where the user enters car details
function validateCar(theForm)
{
	//check manufacturer selected
	if (theForm.manufacturer.value == "")
	{
                alert("Please select a manufacturer");
		document.carMasterForm.manufacturer.focus();
		return false;
	}
        //check model selected
	if (theForm.model.value == "" || theForm.model.value == "Please select..." )
	{
                alert("Please select a  model.");
		document.carMasterForm.model.focus();
		return false;
	}
        //check that derivative selected
	//else if (theForm.derivative.value == "" || theForm.derivative.value == "Please select...")
	//{
         //       alert("Please select a derivative");
	//	document.carMasterForm.derivative.focus();
	//	return false;
	//}
        //check that year selected
	//else if (theForm.year.value == "")
        //{
	//	alert("Please select a year");
	//	theForm.year.focus();
	//	return false;
	//}/
        //check that plate selected
	//else if (theForm.plate.value == "")
	//{
	//	alert("Please select a plate");
	//	theForm.plate.focus();
	//	return false;
	//}
        //check that number prev owners selected
	//else if (theForm.numberofowners.value == "")
	//{
	//	alert("Please select number of previous owners");
	//	theForm.numberofowners.focus();
	//	return false;
	//}
        //check that category selected
	//else if (theForm.category.value == "")
	//{
	//	alert("Please select a category");
	//	theForm.category.focus();
	//	return false;
	//}
        //check that mileage entered
	//else if (theForm.mileage.value == "")
	//{
	//	alert("Please enter mileage");
	//	theForm.mileage.focus();
	//	return false;
	//}
        if(theForm.mileage.value != "" && !isPositiveWholeNumber(theForm.mileage.value))
        {
		alert("Please the mileage in numbers only, using no letters, \ncommas or spaces, eg: 6000");
		theForm.mileage.value = "";
		theForm.mileage.focus();
		return false;
	}
        //check that motexpiry entered
	//else if (theForm.motexpiry.value == "")
	//{
	//	alert("Please enter MOT expiry date");
	//	theForm.motexpiry.focus();
	//	return false;
	//}
        //check that colour entered
	//else if (theForm.colour.value == "")
	//{
	//	alert("Please enter the body colour");
	//	theForm.colour.focus();
	//	return false;
	//}
        //check that interior colour entered
	//else if (theForm.intcolour.value == "")
	//{
	//	alert("Please enter the interior colour");
	//	theForm.intcolour.focus();
	//	return false;
	//}//
        //check that gears entered
	else if (gearSelection == "")
	{
		alert("Please select gear type");
		return false;
	}
        else if (theForm.photo.value != "")
        {
          return CheckAttach(theForm, theForm.photo.value);
        }
        //check that price entered
	else if (theForm.price.value==0)
	{
                alert("Please enter a price");
		theForm.price.focus();
		return false;
	}
        if(!isPositiveWholeNumber(theForm.price.value))
        {
		alert("Please the price in numbers only, using no letters, \ncommas or spaces, eg: 6000");
		theForm.price.value = "";
		theForm.price.focus();
		return false;
	}

        //if all is correct, allow the form to be sent
	else return true;
}

//validates for where user enters review
function validateReview(theForm)
{
	//check manufacturer selected
	if (theForm.manufacturer.value == "")
	{
                alert("Please select a manufacturer");
		document.carMasterForm.manufacturer.focus();
		return false;
	}
        //check model selected
	if (theForm.model.value == "" || theForm.model.value == "Please select..." )
	{
                alert("Please select a  model.");
		document.carMasterForm.model.focus();
		return false;
	}
        //check that derivative selected
	else if (theForm.derivative.value == "" || theForm.derivative.value == "Please select...")
	{
                alert("Please select a derivative");
		document.carMasterForm.derivative.focus();
		return false;
	}
        //check that year selected
	else if (theForm.year.value == "")
	{
		alert("Please select a year");
		theForm.year.focus();
		return false;
	}
        //check that plate selected
	else if (theForm.milesToGallon.value == "")
	{
		alert("Please enter the approximate mileage to the gallon");
		theForm.milesToGallon.focus();
		return false;
	}
        if(!isPositiveWholeNumber(theForm.milesToGallon.value))
        {
		alert("Please the mileage in numbers only, using no letters, \ncommas or spaces, eg: 6000");
		theForm.milesToGallon.value = "";
		theForm.milesToGallon.focus();
		return false;
	}
        //check that comfort rating selected
	else if (theForm.comfort.value == "")
	{
		alert("Please select a comfort rating");
		theForm.comfort.focus();
		return false;
	}
        //check that mechanics rating entered
	else if (theForm.mechanics.value == "")
	{
		alert("Please select a mechanics rating");
		theForm.mechanics.focus();
		return false;
	}

        //check that runningCost rating entered
	else if (theForm.runningCost.value == "")
	{
		alert("Please select a running cost rating");
		theForm.runningCost.focus();
		return false;
	}
        //if all is correct, allow the form to be sent
	else return true;
}


var userType="";

//validates the registration form
function validateReg(theForm)
{
        //check that userName has been filled in
	if (theForm.userName.value == "")
	{
		alert("Please enter a user name");
		theForm.userName.focus();
		return false;
	}
	if (theForm.userName.value != "" && theForm.userName.value.length > 100)
	{
		alert("Please enter less than 100 letters for your user name.");
		theForm.userName.focus();
		return false;
	}
	//check that userName comtains only characters, dots or numbers
	//else if (!isCharOrDot(theForm.userName.value))
	//{
	//	alert("Please only enter letters or numbers in the userName field");
	//	theForm.userName.focus();
	//	return false;
	//}
	//check that password is filled in
	else if (theForm.password.value == "")
	{
		alert("Please enter a password");
		theForm.password.focus();
		return false;
	}
	//check that password length is at least 4 letters long
	else if (theForm.password.value.length < 3)
	{
		alert("Please enter a password of at least 3 letters");
		theForm.password.focus();
		return false;
	}
	//check that password length is less than 8 letters long
	else if (theForm.password.value.length > 8)
	{
		alert("Please enter a password of less than 8 letters");
		theForm.password.focus();
		return false;
	}
	//check that password only contains characters, dots or numbers
	else if (!isCharOrDot(theForm.password.value))
	{
		alert("Please only enter letters or numbers in the password field");
		theForm.password.focus();
		return false;
	}

	//check that the password has been confirmed
	else if (theForm.confirmPassword.value == "")
	{
		alert("Please confirm your password");
		theForm.confirmPassword.focus();
		return false;
	}
	//check that the confirm password field is the same as the password field
	else if (theForm.confirmPassword.value != theForm.password.value)
	{
		alert("Your password confirmation does not match your password - please re-confirm");
		theForm.confirmPassword.focus();
		return false;
	}
        //check that user type entered
	else if (userType == "")
	{
                if (theForm.role.value == null)
                {
                  alert("Please select user type");
		  return false;
                }
	}
        //if all is correct, allow the form to be sent
	else return true;
}

//validates form for registering member of public

function validatePublic(theForm)
{
	//check that first name has been filled in correctly
	if (theForm.firstName.value == "")
	{
		alert("Please enter your first name");
		theForm.firstName.focus();
		return false;
	}
	if (theForm.firstName.value != "" && theForm.firstName.value.length > 25)
	{
		alert("Please enter less than 25 letters for your first name.");
		theForm.firstName.focus();
		return false;
	}

	//check that surname has been filled in correctly
	else if (theForm.lastName.value == "")
	{
		alert("Please enter your surname");
		theForm.lastName.focus();
		return false;
	}
	else if (theForm.lastName.value != "" && theForm.lastName.value.length > 25)
	{
		alert("Please enter less than 25 letters for your surname.");
		theForm.lastName.focus();
		return false;
	}

	//check that the phone number has been filled in
	else if (theForm.eveningPhone.value == "")
	{
		alert("Please enter a contact phone number");
		theForm.eveningPhone.focus();
		return false;
	}
	//check that the phone number is numbers only
	else if (!isNumberOrSpace(theForm.eveningPhone.value))
	{
		alert("Please only enter numbers in the phone number field");
		theForm.eveningPhone.focus();
		return false;
	}
	//check that the mobile number is numbers only
	else if (theForm.mobilePhone.value != "" && !isNumberOrSpace(theForm.mobilePhone.value))
	{
		alert("Please only enter numbers in the mobile number field");
		theForm.mobilePhone.focus();
		return false;
	}
	else if (theForm.postCode.value == "")
	{
		alert("Please enter your post code");
		theForm.postCode.focus();
		return false;
	}
	else if (!theForm.lowPrice.value==0 && !isPositiveWholeNumber(theForm.lowPrice.value))
	{
		alert("Please the price in numbers only, using no letters, \ncommas or spaces, eg: 6000");
		theForm.lowPrice.value = "";
		theForm.lowPrice.focus();
		return false;
	}
	else if (!theForm.highPrice.value==0 && !isPositiveWholeNumber(theForm.highPrice.value))
	{
		alert("Please the price in numbers only, using no letters, \ncommas or spaces, eg: 6000");
		theForm.highPrice.value = "";
		theForm.highPrice.focus();
		return false;
	}

	//if all is correct, allow the form to be sent
	else return true;
}

//validates form for registering trader
function validateTrader(theForm)
{
	//check that first name has been filled in correctly
	if (theForm.tradeName.value == "")
	{
		alert("Please enter your company name");
		theForm.tradeName.focus();
		return false;
	}
	if (theForm.tradeName.value != "" && theForm.tradeName.value.length > 100)
	{
		alert("Please enter less than 100 letters for your company name.");
		theForm.tradeName.focus();
		return false;
	}

	//check that first contact has been filled in correctly
	else if (theForm.contact1.value == "")
	{
		alert("Please enter a first contact name");
		theForm.contact1.focus();
		return false;
	}
	else if (theForm.contact1.value != "" && theForm.contact1.value.length > 50)
	{
		alert("Please enter less than 50 letters for the contact name.");
		theForm.contact1.focus();
		return false;
	}
	//check that second contact has been filled in correctly
	else if (theForm.contact2.value == "")
	{
		alert("Please enter a second contact name");
		theForm.contact2.focus();
		return false;
	}
	else if (theForm.contact2.value != "" && theForm.contact2.value.length > 50)
	{
		alert("Please enter less than 50 letters for the contact name.");
		theForm.contact2.focus();
		return false;
	}
	//check that the phone number has been filled in
	else if (theForm.phoneNumber.value == "")
	{
		alert("Please enter a contact phone number");
		theForm.phoneNumber.focus();
		return false;
	}
	//check that the phone number is numbers only
	else if (!isNumberOrSpace(theForm.phoneNumber.value))
	{
		alert("Please only enter numbers in the phone number field");
		theForm.phoneNumber.focus();
		return false;
	}
	//check that the address has been filled in
	else if (theForm.address1.value == "")
	{
		alert("Please enter the address");
		theForm.address1.focus();
		return false;
	}
	//check that the town has been filled in
	else if (theForm.town.value == "")
	{
		alert("Please enter the town");
		theForm.town.focus();
		return false;
	}
	//check that the postCode has been filled in
	else if (theForm.postCode.value == "")
	{
		alert("Please enter the post code");
		theForm.postCode.focus();
		return false;
	}
	//check that the email has been filled in
	else if (theForm.email.value == "")
	{
		alert("Please enter a contact email address");
		theForm.email.focus();
		return false;
	}

	//if all is correct, allow the form to be sent
	else return true;
}

extArray = new Array(".gif", ".jpg", ".png");

//function to check that a filename is the correct type
function CheckAttach(form, file)
{
  allowSubmit = false;
  if (!file) return;
  while (file.indexOf("\\") != -1)
  file = file.slice(file.indexOf("\\") + 1);
  ext = file.slice(file.indexOf(".")).toLowerCase();
  for (var i = 0; i < extArray.length; i++)
  {
    if (extArray[i] == ext) { allowSubmit = true; break; }
  }
  if (allowSubmit) return true;
  else
    alert("Please only upload files that end in types:  "
    + (extArray.join("  ")) + "\nPlease select a new "
    + "file to upload and submit again.");
    return false;
}

//checks that a string is positive whole numbers only
function isPositiveWholeNumber(string)
{
  var validChars="1234567890"
  var valid = true;
  for (var i = 0;  i < string.length;  i++)
  {
	for (var j = 0; j < validChars.length; j++)
		if (string.charAt(i) == validChars.charAt(j)) break;
	if (j == validChars.length) valid = false;
  }
  if (parseInt(string) <= 0) valid = false;
  return valid;
}
//checks if a string contains characters, dots or numbers only
function isCharOrDot(string)
{
  var validChars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.@"
  var valid = true;
  for (var i = 0;  i < string.length;  i++)
  {
	for (var j = 0; j < validChars.length; j++)
		if (string.charAt(i) == validChars.charAt(j)) break;
	if (j == validChars.length)	valid = false;
  }
  return valid;
}

//checks that a string contains numbers or spaces only
function isNumberOrSpace(string)
{
  var validChars="1234567890 "
  var valid = true;
  for (var i = 0;  i < string.length;  i++)
  {
	for (var j = 0; j < validChars.length; j++)
		if (string.charAt(i) == validChars.charAt(j)) break;
	if (j == validChars.length)	valid = false;
  }
  return valid;
}

function disableEnterKey()
{
	if(event.keyCode == 13) event.returnValue = false;
	event.cancelBubble = true
}

