// automatically adds itself using an anonymous function - p452 javascript

( function() {
		   if (window.addEventListener) window.addEventListener( "load", init, false );
		   else if (window.attachEvent) window.attachEvent( "onload", init );
		   
		   function init(){
			   
			   var form = document.forms[0];
			   
			   //	loop through the form elements
			   for ( var i = 0; i < form.elements.length; i++ ){
					var e = form.elements[i];	// the element we're working on
					
					// see if element needs validating
					var pattern = e.getAttribute("pattern");
					
					var required = e.getAttribute("required") != null;
					
					if ( required && !pattern ) {
						
						pattern = "\\S";
						e.setAttribute("pattern", pattern );
					}
				
			   }
			   
			   form.onsubmit = validate;
		   }
		   
		   function validate(){
				
							
				var invalid = false;		// assume everything is correct to start with
				var mismatch = false;
				
				var form = document.forms[0];
				
				var email = "";				// this will hold the email value
				var email2 = "";			// this will hold the repeat email for matching
				
				var len = form.elements.length;
				for ( var j = 0; j < len; j++ ){
					
					var e = form.elements[j];
					
					if ( e.name == "email" )	email = e.value;
					if ( e.name == "email2" )	email2 = e.value;
					
					
					if ( e.getAttribute("type") == "text" ){
						e.className = "";	
					}
					
					if ( e.name == "message" ){
						e.className = "";	
					}
					
					var pattern = e.getAttribute("pattern")
					
					if ( pattern ){
						
						var value = e.value;
						if ( value.search(pattern) == -1 ) {
							e.className = "invalid";
							invalid = true;
							
						}
					}
				}
				// check that emails match
				
				if ( email != email2 )	mismatch = true;
							
				if ( invalid || mismatch ){
					
					var emails = "";
					var incomplete = "";
					
					if ( mismatch )  emails = "<br />The email and repeat email fields do not match.";
					if ( invalid )  incomplete = "Form incomplete - please fill in the highlighted fields"
					var message = document.getElementById("notsent");
					message.innerHTML = incomplete + emails;
					
					form.onsubmit = validate;
					return false;
				}
		   }
		   
		   
		   })();
