// JavaScript Document
function whichItem(theItemID)	{
	if (document.getElementById)
		{ return document.getElementById(theItemID); }
	if (document[theItemID])
		{ return document[theItemID]; }
	if (document.all)
		{ return document.all[theItemID]; }
	if (eval("document." + theItemID))
		{ return eval("document." + theItemID);	}
	return null;
}

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

// Check if the field has a value
function isEmpty(inputStr) {
	if (inputStr == null || inputStr == "")
		return true;
	return false;
}

function echeck(str) {
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		
		if (str.indexOf(at)==-1 || str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr || str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr || str.indexOf(at,(lat+1))!=-1 || str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot || str.indexOf(dot,(lat+2))==-1 || str.indexOf(" ")!=-1){
		   return false;
		}
		
 		 return true;				
	}


function validateForm(pagename)
{
	var formIsValid = true;
	var errorAlert = '';
	
	if (pagename == null){
		pagename = "contactus";
	}

	var f = whichItem(pagename);

	f.name.value = trim(f.name.value);
	if (isEmpty(f.name.value)) {
		errorAlert = 'Please enter your name.';
		formIsValid = false;
	}

	if (pagename == "contactus") {
		f.email.value = trim(f.email.value);
		f.phone.value = trim(f.phone.value);
		f.subject.value = trim(f.subject.value);
		f.comment.value = trim(f.comment.value);
	
		if (isEmpty(f.email.value)) {
			if (errorAlert.length > 3)
				errorAlert = errorAlert + '\nPlease enter your email address.';
			else
				errorAlert = 'Please enter your email address.';
			f.email.focus();
			formIsValid = false;
		} else if (!echeck(f.email.value)) {
			f.email.focus();
			if (errorAlert.length > 3)
				errorAlert = errorAlert + '\nThis email does not appear to be a valid email address.';
			else
				errorAlert = 'This email does not appear to be a valid email address.';
			formIsValid = false;
		}
		if (isEmpty(f.subject.value)) {
			if (errorAlert.length > 3)
				errorAlert = errorAlert + '\nPlease enter a subject.';
			else
				errorAlert = 'Please enter a subject.';
			formIsValid = false;
		}
	} 
	

	if (formIsValid) {
		whichItem(pagename).action = '/scripts/send-form.php';
		whichItem(pagename).submit();
	} else if (errorAlert != "") {
		alert(errorAlert);
	}
	// this must always return false to avoid spawning off another thread and causing duplicate logging
	return false;
}

