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

 * jquery Form Validation

 * Date: 		25/10/2009
 * Author: 		Nicolas Gutierrez
 * Mail: 		nicmanzana@gmail.com
 * Version		0.1  
 
// ********************************************** */

(function ($) {
	$.fn.validate = function (options) {

		var defaults = {
			borderColor: 		'red',
			tooltip: 			'false',
			animate: 			'true'
		};
		var opts = $.extend(defaults, options);

		return this.each(function () {
			var $this = $(this);
			
			$this.submit(function(){
				var error 	= false;
				var $inputs = $(this+':input.required');
				var $mail	= $(this+':input.requiredMail');
				var $check	= $(this+':input[type=checkbox]').filter('.required');
			
				var values = {};
				// text inputs
				$inputs.each(function(i, el) {
					var $this 	= $(el);
					var border 	= '1px solid ' + opts.borderColor; 
			
					if( $this.val() == '' ){
						$this.css('border', border );
						if(opts.animate){
							for (i=0; i<5; i++) { 
								$this.animate({ marginLeft: "2px"}, 100 );
								$this.animate({ marginLeft: "-2px"}, 100 );
							}
							$this.animate({ marginLeft: "0"}, 100 );
						}
						error = true;
					}else{
						$this.css('border', '1px solid #ccc');
					}
					
				});

				// text inputs
				$check.each(function(i, el) {
					var $this 	= $(el);
			
					if( !$this.is(':checked') ){
						if(opts.animate){
							for (i=0; i<5; i++) { 
								$this.animate({ marginLeft: "2px"}, 100 );
								$this.animate({ marginLeft: "-2px"}, 100 );
							}
							$this.animate({ marginLeft: "0"}, 100 );
						}
						error = true;
					}else{
						error = false;
					}
					
				});

				// mail inputs
				$mail.each(function(i, el) {
					var $this 	= $(el);
					var border 	= '1px solid ' + opts.borderColor; 
					var at 		= $this.val().indexOf("@");
					var dot 		= $this.val().indexOf(".");
			
					if( $this.val() == '' || (at == -1) || (dot == -1) ){
						$this.css('border', border );
						if(opts.animate){
							for (i=0; i<5; i++) { 
								$this.animate({ marginLeft: "2px"}, 100 );
								$this.animate({ marginLeft: "-2px"}, 100 );
							}
							$this.animate({ marginLeft: "0"}, 100 );
						}
						error = true;
					}else{
						$this.css('border', '1px solid #ccc');
					}
					
				});
				if( !error ){
					$this.submit();
				}else{
					return false;
				}
			});
		});
	};
})(jQuery);
