//Check for valid email.
//Valid emails are formatted user@host.domain,
//such as joebloggs@host.com or joebloggs@host.co.uk
//
//Version: 1.0
//Author: Christoffer Jerrebo
//History: 
//Version 1.0
//- First release
function checkEmail(email) {
  var sEmail = new String(email);
  if (sEmail.length == 0) {
    //Empty string
    return true;
  }
  sEmail = sEmail.toLowerCase()
  
  var sAcceptedChars = new String("abcdefghijklmnopqrstuvwxyz_-.0123456789");
  var aEmailArray = sEmail.split('@');  
  var iLength = 0;
  var iCounter = 0;
  var cChar;
  
  //Check for missing @ or multiple @
  if (aEmailArray.length != 2) {
    return false;
  }
  
  //Check first part (user@)
  iLength = aEmailArray[0].length;
  if (iLength <= 0) {
    return false;
  }
  //Check characters
  //Only "abcdefghijklmnopqrstuvwxyz_-." characters and the ten digits are allowed
  for (iCounter = 0; iCounter < iLength; iCounter++) {
    cChar = aEmailArray[0].charAt(iCounter);
    if (sAcceptedChars.indexOf(cChar) == -1) {
      return false;
    }
  }

  //Check second part (@host.aa)
  var aHostArray = aEmailArray[1].split('.');
  var iPartCounter = 0;
  //Check for missing .
  if (aHostArray.length < 2) {
    return false;
  }
  
  //Check characters
  for (iPartCounter = 0; iPartCounter < aHostArray.length; iPartCounter++) {
    iLength = aHostArray[iPartCounter].length
    if (iLength <= 0) {
      return false;
    }
    for (iCounter = 0; iCounter < iLength; iCounter++) {
      cChar = aHostArray[iPartCounter].charAt(iCounter);
      if (sAcceptedChars.indexOf(cChar) == -1) {
        return false;
      }    
    }
  }
  //Length of domain (.uk, .com, .info) must be 2-4 characters
  if ((aHostArray[(aHostArray.length - 1)].length < 2) || 
      (aHostArray[(aHostArray.length - 1)].length > 4)) {
    return false;
  }
  return true;
}
