/*
 * validateForms
 *
 * validates email addresses : look in woodchipper or talk to sean for more
 */
function validateForms(form) {
	// assume the form is valid
	var valid = true;

	// hide error messaging
	hideErrors(form);

	// validate email
	if(!validEmail(form.email.value)) {
		showError('email');
		valid = false;
	}

	return valid;
}

/*
 * showError
 *
 * adds the .error class and removes the error element at the top of the page
 *
 * @id : the id of the element that the error class will be added to
 */
function showError(id) {
	// set the background back to yellow and text to red
	var elem = document.getElementById(id);
	elem.style.background = '#FFFFcc';
	elem.style.color = '#D00';
	elem.style.fontWeight = 'bold';
}

/*
 * hideErrors
 *
 * hides all form errors and top error paragraph
 */
function hideErrors(form) {
	// check to see if the form was passed, if not set it equal to the first form in the page
	if(form != form.constructor) {
		form = document.getElementsByTagName('form')[0];
	}

	// iterate through all the form elements
	for(var i=0; i < form.elements.length; i++) { //form.elements is an array of form fields
		// set the background back to white and text back to grey
		form.elements[i].style.background = '#FFF';
		form.elements[i].style.color = '#545454';
		form.elements[i].style.fontWeight = 'bold';
	}
}

/*
 * validEmail
 *
 * validates email addresses : look in woodchipper or talk to sean for more
 */
function validEmail(mail) {
  // Build our regex
  var qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  var dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  var atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  var quoted_pair = '\\x5c[\\x00-\\x7f]';
  var domain_literal = "\\x5b("+ dtext +"|"+ quoted_pair +")*\\x5d";
  var quoted_string = "\\x22("+ qtext +"|"+ quoted_pair +")*\\x22";
  var domain_ref = atom;
  var sub_domain = "("+ domain_ref +"|"+ domain_literal +")";
  var word = "("+ atom +"|"+ quoted_string +")";
  var domain = sub_domain +"(\\x2e"+ sub_domain +")*";
  var local_part = word +"(\\x2e"+ word +")*";
  //var addr_spec = "("+ local_part +"\\x40(?:[-a-z0-9]+\.)+[a-z]{2,})";
  var addr_spec = "("+ local_part +"\\x40(?:[-a-z0-9]+\\.)+[a-z]{2,})";
  //"+ domain +"
  var regex = new RegExp(addr_spec);  
  var match = regex.exec(mail);
  
  if (match == null) {
    return false;
  } else {
    return true;
  }
  //  if (match == null) {
  //return mail.match(/!^$strict_addr_spec$!/);
  //return mail.match(/s/);
}
