// contains basic javascript functions used throughout the site

//use this function to add events to the window.onload event
function addLoadEvent(func) {
	var oldonload = window.onload;
	if(typeof window.onload != 'function')
	{
		window.onload = func;	
	}
	else
	{
		window.onload = function() 
		{
			oldonload();
			func();
		}
	}
}


//loops through all of the forms on a page and add an onsubmit handler to them so they will be validated on submit
function prepareForms() 
{
	for (var i=0; i<document.forms.length; i++)
	{
		var thisform = document.forms[i];
		thisform.onsubmit = function()
		{
			return validateForm(this);
		}		
	}
	
}

//when used in conjunction with prepareForms(), this function validates form fields upon submission
//all you have to do inside the html form is designate 
//class="required" for any field that has to be filled in and 
//designate class="email required" for any email fields you want validated
function validateForm(whichform)
{
	for (var i=0; i<whichform.elements.length; i++)
	{
		var element = whichform.elements[i];
		if(element.className.indexOf("required") != -1)
		{
			var strField = element.name;
			//to handle user_name and user_email in a friendly way
			if (strField == 'user_name')
			{
				strField = 'Name';	
			}
			else if (strField == 'user_email')
			{
				strField = 'Email';	
			}
			
			if(!isFilled(element))	
			{
				
				alert("Please fill in the "+strField+" field.");
				return false;
			}
			if(element.className.indexOf("email") != -1)
			{
				if(!isEmail(element)) 
				{
					alert("The "+strField+" field must be a valid email address.");
					return false;	
				}
			}
		}
	}
	return true;
}

//simple check to see if a form field is filled in
function isFilled(field)
{
	if(field.value.length < 1)	
	{
		return false;	
	}
	else
	{
		return true;	
	}
}

//simple check to see if the value is an email address
function isEmail(field)
{
	if(field.value.indexOf("@") == -1 || field.value.indexOf(".") == -1)	
	{
		return false;	
	}
	else
	{
		return true;	
	}
}

addLoadEvent(prepareForms);