(function(){
	
	var errorMessages = {
		header: 'The following errors were found in your form:',
		nosymptoms: 'You did not select any symptoms.',
		mismatchedfollowup: 'You selected "{0}" in the {1} section, but you did not indicate the type of {2}.'
	};
	
	var re = {
		format: /\{\d+\}/g,
		formatInt: /\d+/,
		forField: /for([^ ]+)/,
		titleCase: /^[a-z]|(?:[ \t\r\n])[a-z]/g
	}
	
	function format(string, values){
		return string.replace(re.format, function(match, index, string){
			var i = parseInt(re.formatInt.exec(match)[0]);
			return typeof values[i] !== 'undefined' ? values[i] : '';
		});
	}
	
	/**
	 * 
	 * @param {String} string
	 */
	function titleCase(string){
		return string.replace(re.titleCase, function(match, position, string){
			return match.toUpperCase();
		});
	}
	
	$('#coldsAndFluForm').submit(function(e){
		//cancel default action
		e.preventDefault();
		//clear errors
		$('.errors', this).remove();
		
		var errors = [];
		
		//determine whether any symptoms were selected
		if(($('fieldset :checkbox:checked', this).length > 0 || $(':radio:checked:not([value=false])', this).length > 0) === false){
			errors[errors.length] = errorMessages.nosymptoms;
		}
		
		//determine whether followup questions are valid
		var followups = $('p.followup :checkbox:checked');
		for(var i = 0; i < followups.length; i++){
			if($(':input:checked[name=' + re.forField.exec(followups[i].parentNode.className)[1] + ']', this).val() === 'false'){
				var section = followups.eq(i).closest('fieldset').find('p.legend').text(); 
				errors[errors.length] = format(
					errorMessages.mismatchedfollowup,
					[
						$('label[for=' + followups[i].id + ']', this).text(),
						titleCase(section),
						section.toLowerCase()
					]);
			}
		}
		
		//if errors occur, display
		if(errors.length > 0){
			var errorContainer = $('<div/>').addClass('errors').append($('<p/>').text(errorMessages.header));
			var list = $('<ul/>');
			for(var i = 0; i < errors.length; i++){
				list.append($('<li/>').text(errors[i]));
			}
			$(this).prepend(errorContainer.append(list));
			document.location = '#ghc_header';
		}else{
			this.submit();
		}
	});
})();
