/**
 * This is the javascript wordpress error checker
*/
var wpCommentCheck = {

	// object : the html form element
	commentForm : {},
	
	// ojbects : the html elements
	nameField : {},
	emailField : {},
	commentField : {},
	submitField : {},	
	
	
	/*
	 * initialisation function
	 */
			init: function() {

				// get form container and set initial styles
				this.commentForm = document.getElementById('commentform');
				if (!this.commentForm) return false;

				// get each required field
				this.nameField = document.getElementById('author');
				this.emailField = document.getElementById('email');
				this.commentField = document.getElementById('comment');
				this.submitField = document.getElementById('submit');
				

				// set listeners for hovering over each tab
				$('#submit').click(function(e){
				    wpCommentCheck.checkComments();
				    e.preventDefault();
				});
			},
				
			
	
	/*
	 * function to check text areas
	 */		
			checkComments: function() {
				
				// start a string to contain any missing fields
				var missingFields = "";
				
				// condition : check name
				if (wpCommentCheck.nameField != null &&  wpCommentCheck.nameField.value == "") {
					missingFields += "name, ";
				}
				
				// condition : check comment
				if (wpCommentCheck.commentField.value == "") {
					missingFields += "comment, ";
				}

				// condition : check email
				if(wpCommentCheck.emailField != null && 
				    //wpCommentCheck.checkEmail(wpCommentCheck.emailField.value) === true) {
			        wpCommentCheck.emailField.value == "") {
					missingFields += "email, ";
				}

				// condition : if no errors are detected
				if (missingFields.length < 1) {
					
					// submit form
					var commentForm = document.getElementById('commentform');
					commentForm.submit();
				
				// else, alert which fields are empty
				} else {
					
					// remove last two characters from string
					missingFields = missingFields.replace(/, $/,"");
					
					alert('Please complete the following fields: ' + missingFields);
				}
			},
			
			
	/**
	 * Check for the correct formatting on an email address
	 *
	 * @param string email the inputted email address
	 *
	 * @return boolean whether there is an error in the email address (false === error)
	 */
 		   checkEmail: function(email) {

				// email test
				var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

				// if the email address passes validation, it's real
				if (filter.test(email)) {
					return true;

				// error detected
				} else {
		            return true;
		        }
		    }
};
