$(document).ready(function() {
	
	var EMAIL_REGEXP = new RegExp(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/);
	var ZIP_REGEXP = RegExp(/^[0-9]{5}(-[0-9]{4})?$/);
	var ERROR_MESSAGE = '<p>Please complete or correct the highlighted fields and agree to the official rules.</p>'
	
	function validateOnEnterOrSubmit(e) {
		if (e.which == 13 || $(e.target).attr('id') == 'contest-submit') {
			
			// reset form
			var valid = true;
			$('#contest-form-wrapper .error').each(function(){
				$(this).removeClass('error');
			});
			$('#contest-error-message').html('');
			
			$('#contest-form-wrapper .required').each(function(){
				var $this = $(this);
				if ($.trim($this.attr('value')) == '') {
					valid = false;
					$this.addClass('error');
				}
				
				if ($this.attr('type') == 'checkbox' && !$this.attr('checked')) {
					$this.parents('.form-field').addClass('error');
					valid = false;
				}
			});
			
			$('#contest-form-wrapper .email').each(function(){
				var $this = $(this);
				var value = $.trim($this.attr('value'));
				if (value && !EMAIL_REGEXP.test(value)) {
					valid = false;
					$this.addClass('error');
				}
			});
			
			$('#contest-form-wrapper .zip').each(function(){
				var $this = $(this);
				var value = $.trim($this.attr('value'));
				if (value && !ZIP_REGEXP.test(value)) {
					valid = false;
					$this.addClass('error');
				}
			});
			
			// show error messaging and stop submission
			if (!valid) {
				e.preventDefault();
				$('#contest-error-message').html(ERROR_MESSAGE);
			}
		}
	}
	
	$('#overlay').keypress(validateOnEnterOrSubmit);
	$('#overlay').click(validateOnEnterOrSubmit)
	
	
});


	

