
function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
} 

function isEmpty(fld) 
{ 
	var fieldValue = trim(fld.value);

  if (fieldValue.length == 0) 
  {
  	return true;
  } 
		
  return false;  
}

function validateEmail(email)
{
	validateEmail(email, false);
}

function validateEmail(email, modal)
{
	formElV=email.value
	
	var pat = new RegExp("^(\\w|-|\\w\\.\\w)+@(\\w|-|\\w\\.\\w)+\\.\\w") ;
	patmatch = pat.test(formElV);
	if(patmatch)
	{
		email.style.background = "white";
		return true;
	}
	
	email.style.background = "#ffffcc";
	email.focus();
	email.select();
	displayErrors(email.form, "Please enter a valid email address.", modal);
	return false;	
}

function validateForm(theForm)
{

	validateForm(theForm, false);
}

function validateForm(theForm, modal)
{
	var frmElmnts = theForm.elements;
	var emptyFields = new Array();
	
	for (var i=0; i < frmElmnts.length; i++) 
	{
  	if (frmElmnts[i].title == 'Required') 
		{		
			// Text, Textarea
			if (frmElmnts[i].type=='text' || frmElmnts[i].type=='textarea' || frmElmnts[i].type=='password') 
			{
				if (isEmpty(frmElmnts[i])) 
				{
					emptyFields.push(frmElmnts[i]);
					frmElmnts[i].style.background = "#ffffcc";
 				}
				else
				{
					frmElmnts[i].style.background = "white";
				}
			}
		}
	}
	
	if (emptyFields.length > 0)
	{
		//build error message
		var errorMsg = 'The following fields are required:';	 
		for (var i=0; i < emptyFields.length; i++)
		{
			errorMsg += ' ' + emptyFields[i].name;
			if ((i+1) < emptyFields.length)
			{
				errorMsg += ',';
			}
			else
			{
				errorMsg += '.';
			}
		}		
		
		displayErrors(theForm, errorMsg, modal);
		return false;
	}
	
	return true;
}

function displayErrors(theForm, errorMsg, doModal)
{
		if (doModal)
		{
			alert(errorMsg);	
		}
		else
		{
  		if (document.getElementById('_errorMessage')) 
  		{
      	theForm.removeChild( document.getElementById('_errorMessage'));
      }
      var errorDiv = document.createElement('div');
      errorDiv.id = '_errorMessage';
      errorDiv.className = 'errorMessage';
      errorDiv.innerHTML = errorMsg;
      theForm.insertBefore(errorDiv, theForm.childNodes[0]);
		}
}

function checkNewsletterForm(theForm) 
{
	
	if (isEmpty(theForm.name))
	{
			alert('Please enter a name.');
			theForm.name.focus();
			theForm.name.select();
			return false;
	}
	
	if (isEmpty(theForm.email))
	{
			alert('Please enter an email.');
			theForm.email.focus();
			theForm.email.select();
			return false;
	}
	
	return validateEmail(theForm.email, true);
}
