function isValidUserName(userName) {
  var len = userName.length;
  
  if (len == 0)
    return false;
  
  var ter1Index = userName.indexOf("@");
  var ter2Index = userName.lastIndexOf(".");
  
  if (ter1Index < 0 || ter2Index < 0)
    return false;
    
  if (ter1Index > ter2Index)
    return false;

  if (ter1Index+1 == ter2Index)
    return false;

  if ((ter1Index+1 == len) || (ter2Index+1 == len))
    return false;
    
  return true;
}

// returns : 0 if success
//           1 if fails isValidUserName
//           2 if fails db check
//           3 if check cannot be performed
function checkUsername(userName, serverRootRelpath) {
  if (isValidUserName(userName)) 
  {
	  var result_raw = new Array();
	  var result_format = new Array();
	  var httpob;

    if (window.XMLHttpRequest) {
      httpob = new XMLHttpRequest();
    } 
    else {
      try { 
        httpob = new ActiveXObject("Msxml2.XMLHTTP"); 
      } 
      catch (e) {
        try { 
          httpob = new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
        catch (e) {
          httpob = false; 
        } 
      }
    }
	  
	  if (!httpob)
	    return 3;
	    
	  httpob.open("POST", "checkAvailability.asp?username=" + userName, false); 
	  
	  var params = "";
	  httpob.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    httpob.setRequestHeader("Content-length", params.length);
    httpob.setRequestHeader("Connection", "close");

//    httpob.onreadystatechange = function() {//Call a function when the state changes.
//	    if(httpob.readyState == 4 && httpob.status == 200) {
//		    alert(httpob.responseText);
//	    }
//    }
    httpob.send(params);
	  
	  result_raw = httpob.responseText;
	  result_format = result_raw.split("^");
	  
	  if(result_format[1] == 'Username.good')
	    //< % =MsgBox("This username is available to be used!",(0+64), "Info") % >
	    return 0;
	  else
	    return 2;
  }
  else 
    return 1;
}

function checkUsernameAvailability(usernameField) {
  var nResult = checkUsername(usernameField.value);

	if(nResult == 0)
	{
	  alert("This username is available to be used!");
	  return true;
	}
	else if (nResult == 1) 
	{
	  usernameField.focus();
	  alert("This username is invalid!");
	}
	else if (nResult == 2)
	{
	  usernameField.focus();
	  alert("The username you chose is already in use. Please select an alternate id!");
	}
	else if (nResult == 3)
	{
	  usernameField.focus();
	  alert("The check cannot be performed at this moment.");
	}
	else
	{
	  usernameField.focus();
	  alert("Unknown Error.");
	}
	
	return false;
}

