// Form validation for 1-step signup
//
submitOnce=false;   // has the user tried to submit already? if not, don't show alerts on keypress
asynchronous=true;  // whether to use synchronous (final submit) or asynchronous (real time) calls

// Clear all alerts and messages before a new validation check
//
function clearAlerts(checkType) {

  document.getElementById('alertmssg').style.display='none';
  errorFound=false;
  mssg="";
  numAlertLines=0;
  
  // only clear site name field if you are actively checking it (checkType=1), otherwise leave it as is
  if (checkType==1) document.forms.signupForm.username.className='input';
  document.forms.signupForm.password.className='input';
  document.forms.signupForm.password2.className='input';
  document.forms.signupForm.fname.className='input';
  document.forms.signupForm.lname.className='input';
  document.forms.signupForm.email.className='input';
  document.forms.signupForm.tos.className='input';
  document.getElementById('tosText').className = 'notes';
}

// Called by submit button
//
function trySubmit() {
	asynchronous=false;  // do a synchronous site name check to make sure it returns before unload
	submitOnce=true;     // flag that the submit button has been hit and errors are displayed

	// checkForm(0): skips site name check, reduces AJAX calls to server, called by non-site name fields
	// checkForm(1): called by site name field, enables AJAX checking of site name
	checkForm(1);      
	if(!errorFound) {
		document.forms.signupForm.submit();
	}

	asynchronous=true; // reset to asynchronous AJAX calls since we must be back on the page with errors
}

// The main validation method for 1-step signup. Called by trySubmit and key press in form.
// Sets errorFound to true if any errors are found and keeps it at false if no errors are found.
// checkType is a flag which determines if the AJAX sitename test is run. Only want this when
// someone is typing in that field or on the final form submit, otherwise each keypress in each
// form field generates an AJAX request asking if the site name is valid.
//
function checkForm(checkType) {
  if (submitOnce) {  // Only check for errors if the submit button has been hit and errors are displayed

	// Start the check with a clear slate
	clearAlerts(checkType);
	
	checkSiteName(checkType);  
	checkPass();
	checkName();
	checkEmail();
	checkTOS();
  }
}

// Check that the sitename is formatted correctly and is available
//
function checkSiteName(checkType) {
  sitename = document.forms.signupForm.username.value;
  
  if (sitename == "") {
    highlightAlert("username","* Please enter a site name.\n");
  } else if (sitename.length < 3) {
    highlightAlert("username","* Site name must be at least 3 chars.\n");
  } else if (!checkChars(sitename,'strict')) {
    highlightAlert("username","* Site name must be letters & numbers only.\n");
  } else {
	if (checkType==1) checkUsername(); // Only do AJAX check on type 1 checks and after other tests have passed
  }
}

// AJAX check if Site Name (aka username) is already taken
//
function checkUsername() {
	var target = document.getElementById("username"); 
	var url = "/ps/Validation?username=" + encodeURIComponent(target.value);
	var oXMLHttpRequest	= new XMLHttpRequest;
	oXMLHttpRequest.open("GET", url, asynchronous);
	oXMLHttpRequest.onreadystatechange	= function() {
		if (this.readyState == XMLHttpRequest.DONE) {
		   var msg = oXMLHttpRequest.responseXML.getElementsByTagName("valid")[0].firstChild.nodeValue;			
		   if (msg == "false") { // Chosen name is already in use, show an error
				highlightAlert("username","* This site name is already in use.\n");
		   }
		}
	}
	oXMLHttpRequest.send(null);
}

// Check that a password has been entered and matches the verify field
//
function checkPass() {
  passStr = document.forms.signupForm.password.value;
  confirmStr = document.forms.signupForm.password2.value;
  
  if (confirmStr == "") {
    highlightAlert("password2","");
  }

  if (passStr == "") {
    highlightAlert("password","* Please enter a password.\n");
  } else if (passStr.length < 3) {
    highlightAlert("password","* Password must be at least 3 chars.\n");
  } else if (!checkChars(passStr,'loose')) {
    highlightAlert("password","* Password can not contain spaces.\n");
  } else if (passStr != confirmStr) {
    highlightAlert("password2","* Two password entries do not match.\n");
  }
}

// Check that a password has been entered and matches the verify field
//
function checkName() {
	if (document.forms.signupForm.fname.value == "") {
		highlightAlert("fname","* Please enter your first name.\n");
	}
	
	if (document.forms.signupForm.lname.value == "") {
		highlightAlert("lname","* Please enter your last name.\n");
	}
}

// Check that a email has been entered and is correctly formatted
//
function checkEmail() {
  if (document.forms.signupForm.email.value == "") {
	highlightAlert("email","* Please enter your e-mail address.\n");
  } else {
	var email = document.forms.signupForm.email.value;
	var filter  = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) {
		highlightAlert("email","* Please enter a valid email address.\n");
	}
  }
}
	
// Check if TOS has been agreed to, show an alert if it hasn't
//
function checkTOS() {
  if (!document.forms.signupForm.tos.checked) {
    document.getElementById('tosText').className = 'notesAlert';
	highlightAlert("tos","* Please agree to our Terms of Service.\n");
  } else {
  	document.forms.signupForm.tos.value="agreed";
  }
}

// Handle when an error is found
//
function highlightAlert(field,errMssg) {
	// set some error params
	mssg+=errMssg;    // text which fills the alert box at bottom of page
	errorFound=true;  // flag to determine if any errors were found
	// Crazy formula because alert box was too tall. First alert has to be at least 1 tall or IE croaks
	// so smallest line ht is 1...all other errors add at a 0.9 line ht, which works out
	if (numAlertLines==0) {  // count the number of errors to determine correct alert box height
		numAlertLines++;
	} else {
		numAlertLines=numAlertLines+.9;
	}
	
	// highligh the form field with the error
	eval("document.forms.signupForm." + field + ".className='alertOn'");
	
	// display alert box
	document.getElementById('alertmssg').style.display='block';
	document.getElementById('alertmssg').rows=numAlertLines;
	document.getElementById('alertmssg').value=mssg;
}

// Check that field only contains the correct type of characters.
//    strict: letters and numbers only, no spaces (sitenames)
//    loose: letters, numbers or characters, no spaces (passwords)
//
function checkChars(field, mode) {
 	exclude = "";
	
	// list of illegal characters, add new characters to this string.
	if (mode=='strict') {		// strict test
		exclude = "~`! #$%^&*()+=|\\}]{[':;?/><,@-_.\"";
	} else {  					// loose test
		exclude = " ";
	}
	
	// check submitted field vs. the exclude list
	for (i = 0; i < exclude.length; i++) {
		if (field.indexOf(exclude.charAt(i)) != -1) {
			return false;
		}
	}
	return true;
}