// Basic form validation using jQuery
// Copyright 2008 by Ryan Cramer Design, LLC

function getFieldLabel(field) {
	var label = $(field).parent("label").html();
	if(!label) label = $(field).attr("name"); 
	var pos = label.indexOf('<'); 
	if(pos > 0) label = label.substring(0, pos-1); 
	return $.trim(label); 
}

var validateForm = function() {

	var errors = '';
	var firstField = false;

	$("form.rcdform :input.required").each(function() {
		var str = $.trim($(this).val()); 	
		if(!str.length) {
			errors += getFieldLabel($(this)) + "\n";
			if(!firstField) firstField = $(this); 
			$(this).parent("label").addClass("required");
		}
	}); 

	$("form.rcdform fieldset.required").each(function() {
		var label = $(this).children("legend").text(); 
		if(!label) label = $(this).attr("title"); 
		if($(this).is(".radios")) {
			if($(this).find(":checked").size() == 0) {
				errors += label + "\n";
				if(!firstField) firstField = $(this).find(":input").get(0); 
			}
		}
	}); 

	$("form.rcdform input.email").each(function() {
		var val = $(this).val(); 
		if(val.length == 0) return;
		if(val.indexOf('@') < 1 || val.indexOf('.') < 1) {
			errors += getFieldLabel($(this)) + ": Invalid email address\n";
			if(!firstField) firstField = $(this); 
			$(this).parent("label").addClass("required"); 	
		}
	}); 

	$("form.rcdform input.numeric").each(function() {
		var val = $(this).val(); 
		if(val == null || !val.toString().match(/^[\d ]*$/)){
			errors += getFieldLabel($(this)) + ": Only numbers are allowed in this field\n"; 
			if(!firstField) firstField = $(this); 
			$(this).parent("label").addClass("required"); 	
		}
	}); 

	if(errors.length) {
		alert("Please complete the following required fields:\n\n" + errors); 
		firstField.focus(); 
		return false;
	}

	return true; 
}

$(document).ready(function() {

	$("form.rcdform").submit(validateForm).css("display", "block"); 
	$("form.rcdform :input.required").before("<span class='required'>*</span>"); 
	$("form.rcdform").append("<input type='hidden' name='rcdform' value='save' />"); // per requires_javascript directive

	$("form.rcdform :input").change(function() {
		var str = $.trim($(this).val()); 	
		if($(this).is(".required") && str.length) $(this).parent("label").removeClass("required"); 
	}); 

	$("form.rcdform :radio").click(function() {
		$(this).parent("label").parent().children("label").removeClass("on"); 
		if($(this).is(":checked")) $(this).parent("label").addClass("on"); 
	}); 
}); 
