/*********************************************************

Validate
 by AGT of Toucan Internet LLP
 andrew@toucanweb.co.uk
 
A simple jQuery plugin to provide basic form validation
 and highlight errors in a nice way, without having to use
 alert boxes.

************************************************************/

(function($){
	$.fn.Validate = function(options){
	
		var defaults = {
			fieldClass:'req', // The class of the form fields that should be validated
			errorClass:'error', // The class that should be added to form fields when there is an error
			message:'The highlighed fields are required.', // The error message
			messageClass: 'error', // The error message class
			emailFields: Array('email'), // The name(s) of fields that should be validated as email addresses
			invalidValues: Array('') 
		};
		
		var options = $.extend(defaults, options);
		
		return this.each(function(){
			$(this).submit(function(e) {
				//e.preventDefault();			
				var error = false;
				$('input.'+options.fieldClass+', select.'+options.fieldClass+' option:selected, textarea.'+options.fieldClass, this).each(function(e) {
					var value = jQuery.trim($(this).val());
									
					// Handle checkboxes
					if($(this).attr('type') == 'checkbox') {
						if(!$(this).attr('checked')) {
							$('label[for="'+$(this).attr('id')+'"]').addClass('error');
							error = true;
						} else {
							$('label[for="'+$(this).attr('id')+'"]').removeClass('error');
						}
					} 
					
					if(options.invalidValues.indexOf(value) != -1) { // The value is in the invalid list.
						error = true;
						$(this).addClass(options.errorClass);	
					} else {
						if(options.emailFields.indexOf($(this).attr('name')) == -1) {
							// All good as not empty and not an email field
							$(this).removeClass(options.errorClass);
						} else {
							// Need to validate the email field	
							if(emailOk($(this))) {
								$(this).removeClass(options.errorClass);
							} else {
								error = true;
								$(this).addClass(options.errorClass);	
							}
						}
					}
				});
				
				if(error) {
					e.preventDefault();
					$('input[type="submit"]', this).blur();
					$('p.'+options.messageClass, this).remove();
					$(this).prepend('<p class="'+options.messageClass+'">'+options.message+'</p>');
					$('p.'+options.messageClass).hide(0);
					$('p.'+options.messageClass).slideDown(500);
				}
			});
		});
	};
})(jQuery);

// Allow IE support for Array.indexOf
if(!Array.indexOf){
	Array.prototype.indexOf = function(obj){
		for(var i=0; i<this.length; i++){
			if(this[i]==obj){
				return i;
			}
		}
		return -1;
	}
}

function emailOk(field) {
	var emailat = field.val().indexOf("@");
   	var emaildot = field.val().indexOf(".", emailat+1);
   	if(emailat < 0 || emaildot < emailat) {
		return false;
	}	
	return true;
}
