/* **********************************************
 * jquery Form Validation
 * Date: 		10/25/2009
 * Last Update 12/28/2009
 * Version		0.5
// ********************************************** */

(function ($) {
	$.fn.validate = function (options) {

		var defaults = {
			 tooltip: 	'false'
			,shaker: 	'true'
			,shakers:		5
			,ajax:		'false'
			,ajaxPage: 	''
			,message: 	''
			,func:		''
		};
		var opts = $.extend(defaults, options);

		return this.each(function () {
			var $this = $(this);
			
			$this.submit(function(){

				var error 	= false;
				var $inputs = $(this).find('input, select, textarea, checkbox').filter('.required');
				var $mail	= $(this).find('input').filter('.required').filter('.mail');
				var $errors = $(this).find('input').filter('.error');
			
				var values = {};
				
				// text checker
				$inputs.each(function(i, el) {
					var $this 	= $(el);
					var type		= $this.attr('type');

					if( ( !$this.val() ) || ( (type == 'checkbox') && (! $this.is(':checked')) ) ){
						$this.addClass('error');
						if(opts.shaker){
							for (i=0; i<opts.shakers; i++) { 
								$this.animate({ marginLeft: "2px"}, 100 );
								$this.animate({ marginLeft: "-2px"}, 100 );
							}
							$this.animate({ marginLeft: "0"}, 100 );
						}
						error = true;
					}else{
						$this.removeClass('error');
					}					
				});

				// mail checker
				$mail.each(function(i, el) {
					var $this 	= $(el);
					var at 		= $this.val().indexOf("@");
					var dot 		= $this.val().indexOf(".");
			
					if( $this.val() == '' || (at == -1) || (dot == -1) ){
						$this.addClass('error');
						if(opts.shaker){
							for (i=0; i<opts.shakers; i++) { 
								$this.animate({ marginLeft: "2px"}, 100 );
								$this.animate({ marginLeft: "-2px"}, 100 );
							}
							$this.animate({ marginLeft: "0"}, 100 );
						}
						error = true;
					}else{
						$this.removeClass('error');
					}
					
				});
				
				// form submit
				if( !error ){
					if(!opts.ajax){
						$this.submit();
					}else{
						opts.func(opts.message);
						return false;
					}
				}else{
					return false;
				}


			});
		});
	};
})(jQuery);
