$(document).ready(
	function()
	{	
		//set up variables
		var fromname = $("#fromname");
		var toname = $("#toname");
		var fromemail = $("#fromemail");
		var toemail = $("#toemail");
		var message = $("#message");
		
		var checkfromname = $("#checkfromname");
		var checktoname = $("#checktoname");
		var checkfromemail = $("#checkfromemail");
		var checktoemail = $("#checktoemail");
		var processing = $("#processing");
		
		var problems = 0;
		
		function init() 
		{
			initVars();
			document.getElementById("fromname").focus();
			writeTextArea();
		}
		
		//fill in the textarea with retained value
		function writeTextArea()
		{
			message.val($("#restoreMessage").val());
		}
		
		//initialize the views
		//using css for checks because we
		//don't want them to show while the page
		//is loading
		function initVars()
		{
			checkfromname.hide();
			checkfromemail.hide();
			checktoname.hide();
			checktoemail.hide();
			
			processing.hide();	
		}
				
		//Be sure the name only includes letters, spaces
		//periods and commas and that's it's at least 5
		//characters long
		function validateName()
		{
			var filter = /^[\w\s.,]*$/i;
			if(fromname.val().length < 5 || !filter.test(fromname.val()))
			{
				
				problems++;
				checkfromname.show();
			}
			
			if(toname.val().length < 5 || !filter.test(toname.val()))
			{
				
				problems++;
				checktoname.show();
			}
		}
		
		//validate email addresss
		function validateEmail()
		{
			var filter = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(\+?[\w-]+)?(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
			
			if(!filter.test(fromemail.val()))
			{
				problems++;
				checkfromemail.show();
			}
			
			if(!filter.test(toemail.val()))
			{
				problems++;
				checktoemail.show();
			}
		}
				
		//check required fields
		$("#submit").click(
			function()
			{
				initVars();

				problems = 0;
				validateName();
				validateEmail();
							
				if(problems > 0) {
					return false;
				}
				else {
					$("#buttons").hide();
					processing.show();
					return true;
				}
			}
		);
		
		//close the popup window when this button is clicked
		$("#cancelContact").click(
				function() {
					self.parent.$("#DOMWindow").closeDOMWindow();
				}
	    );
		
		//initialize
		init();
	}
);