//This function starts the validation of form elements.
//It is passed a jQuery element of the inputs to validate, and the form name that the inputs belong to.
function validate(inputs, form){
	var errors    = new Array();
	
	inputs.each(function(){
		var id    = jQuery(this).attr("id");
		var valid = true;
			switch (id){
				default          : valid = validate_generic(this); break;
				case 'from'      : valid = validate_email(this);   break;
				case 'phone'     : valid = validate_phone(this);   break;
				case 'portfolio' : valid = validate_url(this);     break;
				case 'resume'    : valid = validate_url(this);     break;
			}
		if (!valid){errors.push(this);}
	});
	
	//Remove previous and add new errors and error box
	jQuery('#ErrorMessage').remove();
	jQuery('.error').removeClass('error');
	for (var i in errors){
			jQuery(errors[i]).parent().addClass('error');
	}
	if (errors.length){
		var message;
		if (errors.length == 1){
			message = 'There was an error with the form. ';
		}else{
			message = 'There were ' + errors.length + ' errors with the form. ';
		}
		message += 'Correct any marked fields below.';
		jQuery(form).prepend(make_message(message));
		window.location ='#ErrorMessage';
	}
	
	//Cancel form submission if errors present
	return !errors.length;
}

function make_message(message){
	var message_box = jQuery("<p id='ErrorMessage' class='input-error'>" + message + "</p>");
	return message_box;
}

function validate_generic(input){
	var value    = jQuery(input).val();
	var optional = jQuery(input).hasClass('optional');
	
	if (optional)       {value = true};
	if (value == 'NONE'){value = false};
	return Boolean(value);
}

function validate_email(input){
	var valid_email = /[\s]*[\w]+\@[\w]+\.[\w][\s]*/;
	return valid_email.test(jQuery(input).val());
}

function validate_phone(input){
	var valid_phone = /((\(\d{3}\)?)|(\d{3}))([\s-./]?)(\d{3})([\s-./]?)(\d{4})/;
	return valid_phone.test(jQuery(input).val());
}

function validate_url(input){
	var valid_url = /[\s]*http:\/\/[\w]+[\s]*/;
	return valid_url.test(jQuery(input).val());
}
