// Contact us form validation functions
var errorCount = 0;

function isBlank(value , error2display)
{
  if (parseInt(removeLeadingspaces(value).length)== 0)
  {
      displayMessage (error2display);
	  return 1;
  }else{
	  return 0;
	  }
}

function removeLeadingspaces(value)
{
  var i = 0 ;
  var blnDone = false;
  var strReturnString = "";
  var intNumspace = 0
  while ((!blnDone) && (i < value.length))
    {
      var c = value.charCodeAt(i);
      if (c == 32)
      {
        intNumspace = intNumspace + 1;
        if (value.charCodeAt(i+1) == 32)
        {
          blnDone = false;
        }
        else
        {
          blnDone = true;
        }
      }
      i = i + 1
    }  

  strReturnString  = value.substring(intNumspace , value.length);

  return strReturnString ;
}

function hasInvalidChars(strEmail , strInvalidChars)
{
  var blnError = false;
  var i = 0;
  while ((!blnError) && (strInvalidChars.length > i))
  {
    if (strEmail.indexOf(strInvalidChars.charAt(i) , 0) > -1)
    {
      blnError = true;
    }
     i = i + 1
  }
  return blnError;
  
}
function validateEmail (strEmail)
{
	var blnError = 0;
  var intIndexofAt = strEmail.indexOf("@", 0)
  var intIndexofDot = strEmail.indexOf(".", parseInt(intIndexofAt) + 1)
    if(intIndexofAt == -1)
    {
        displayMessage ("There must be an at symbol (@) in your email address.");
		 blnError = 1;
    }
    else
    {
      if(intIndexofDot == -1)
      {
        displayMessage ("There was no domain specified (i.e. mydomain.com) in your email address.");
		 blnError = 1;
      }
      else
      {
        if (hasInvalidChars(strEmail , "/!£$%^&*()'+=") )
        {
            displayMessage ("There are invalid characters in your email address.");
			 blnError = 1;
        }
      }
  }
    return blnError;
}

function displayMessage(msg){
	var errors = document.getElementById("errors");
	if(errors.innerHTML==""){
			errors.innerHTML = "<p><h2 class=red>The following error(s) have occurred:</h2><ul>";
	}
	errors.innerHTML += msg +"<br>";
}

function validateForm(frm){
	var errors = document.getElementById("errors");
	errors.innerHTML="";
	
	/*
	frm.name.value
	frm.email.value
	frm.Company.value
	frm.Address.value
	frm.City.value
	frm.Country.value
	frm.Postcode.value
	*/
	errorCount = isBlank(frm.name.value, "Please enter your name"); 
	
   	errorCount = isBlank(frm.email.value, "Please enter an email address"); 
	
	//if there is an email check it's a valid one...
	if(errorCount == 0)	errorCount = validateEmail(frm.email.value);
	
    //errorCount = isBlank(frm.Company.value, "Please enter a company name"); 
	errorCount = isBlank(frm.Address.value, "Please enter an address"); 
	errorCount = isBlank(frm.City.value, "Please enter a city"); 
	errorCount = isBlank(frm.Country.value, "Please enter a country"); 
	errorCount = isBlank(frm.Postcode.value, "Please enter a postcode"); 

	if(errors.innerHTML!="") return false;
	else return true;
}
