/*  Validation onsubmit
	- appends error to document
------------------------------------------------------ */

$(document).ready(function() { 
	$('form').submit(function() { 
		$('#submit-message').remove(); 
		$(':input.required').trigger('blur');
		$(':input#email').trigger('blur');
	
		var numWarnings = $('.warning', this).length;
		if (numWarnings) { 
	 		$('<div></div>').attr({'id': 'submit-message', 'class': 'warning'}).append('Please correct errors with ' + numWarnings + ' fields ' + 'and resubmit the form').insertBefore('#submit-btn');
	 		return false;
		};
	});  
}); 

/*  Validation onblur
------------------------------------------------------ */
$(document).ready(function() { 
	
	//append error html + msg
	function errorMsg(item, error) {
		var $listItem = $(item).parents('li:first'); 
		$('<span></span>') 
			.addClass('error-message') 
		    .text(error) 
		    .appendTo($listItem);
		$listItem.addClass('warning');
	}
	
	//Inputs
	$('form :input').blur(function() { 
	    $(this).parents('li:first').removeClass('warning') 
		.find('span.error-message').remove();
		
		// required fields
		if ($(this).is('.required')) { 
	    	var $listItem = $(this).parents('li:first'); 
	    	if (this.value == '') { 
				errorMsg(this, 'This field is required');
	      	} 
	    };
	 	
	 	//email address
		if ($(this).is('#email')) { 
			var $listItem = $(this).parents('li:first');
			if (this.value != ' ' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value)) {
				errorMsg(this, 'Please enter a valid e-mail');
			};
		};
  	});
  	
  	//select boxes
  	$('form select.required').blur(function() { 
  		$(this).find('option').each(function(){
  			var $listItem = $(this).parents('li:first');
        	if(this.selected && this.value==' '){
				errorMsg(this, 'Please Select an option');
        	}
		}) 
  	});
   	$('form select.required').change(function() { 
  		$(this).find('option').each(function(){
  			$(this).parents('li:first').removeClass('warning') 
			.find('span.error-message').remove();
  			var $listItem = $(this).parents('li:first');
        	if(this.selected && this.value==' '){
            	errorMsg(this, 'Please Select an option');
        	}
		}) 
  	});
  	
});
/* ---------------------------------------------------- */
/* Enable 'other' options in select box */
$(document).ready( function () {
	$('.leader').each( function () {
		var name = $(this).attr('name');
	 	
		if ($(this).val()!='other') {
	 		$(this).next().removeAttr('name').hide();
		 }
	});
			
	$('.leader').change(onChange);		
	
	function onChange(){
		var desiredName = $(this).attr('name');
		if ($('#'+desiredName).val()=='other') {
			$('#'+desiredName).next().attr('name',desiredName).fadeIn('fast');
		}
		else {
			$('#'+desiredName).next().removeAttr('name').fadeOut('fast');
		}
	}
});
/* ---------------------------------------------------- */



