/*
 * jQuery Form Helper
 * Version: .5 (September-23-2011)
 * Requires: jQuery v1.5 or later
 * 
 * Usage:
 * ---------
 * 
 * Use class to add validation to the field. 
 * 
 * Example:
 * 
 * class="required" :: Check if it's empty.
 * class="email-required" :: Check if it's a valid email address.
 */

(function($){
	// Settings
	var AppSetting = {	};
	
	// Main Class
	/*
	 * @param element - css target
	 * @param options - optional parameter
	 */
	var FormHelper = function(element, options)
	{
		var thisClass = this;
		var $this = $(element);
		var $form = $(element);
		var rules = {};
		var settings = {
			rules : rules,
			success : null,
			html : 'html'
		};
		
		if (options)
		{
			settings = $.extend(true, settings, options);
		}
		
		$form.submit(function(event)
		{
			event.preventDefault();

			var action = $this.attr('action');
			

			if ($this.isValid())
			{
				var form_data = $this.serialize();
				
				ajaxCall($this, action, form_data);
			}
		});

		function ajaxCall($form, action, data)
		{
			$.post(action, data, settings.success);
		}

		this.valid = function()
		{
			return false;
		}
		
	};
	
	var methods = {
		clearForm : function()
		{
			return this.each(function(){
				clearForm(this);
			});
		},

		addRule : function(name, rule){
			rules[name] = rule;
		}
	};
	
	function clearForm ($form)
	{
		$form.find('input').each(function() {
			var $this = $(this);
			if($this.attr('type') != 'submit')
			{
				$this.val('');
			}
		});
	}
	
	function attachMsg($elem, mgs)
	{
		// Remove the old message
		$elem.parent().find('.error-msg').replaceWith('');
		$elem.after('<p class="error-msg"> &nbsp  <- &nbsp ' + mgs + '</p>').show('slow');
	}
	
	$.fn.isValid = function()
	{
		// Gets all of the inputs
		this.find('.required, .email-required').each(function(index, elem)
		{
			var $thisField = $(this);

			if ($thisField.hasClass('required'))
			{
				if ($.trim($thisField.val()) == '')
				{
					attachMsg($thisField, 'This field cannot be empty.');
					$thisField.addClass('field-error');
				}
				else
				{
					$thisField.removeClass('field-error');
					$thisField.parent().find('.error-msg').replaceWith('');
				}
			}

			if ($thisField.hasClass('email-required'))
			{
				if ($.trim($thisField.val()) == '')
				{
					attachMsg($thisField, 'This field cannot be empty.');
					$thisField.addClass('field-error');
				}
				else
				{
					var thisFieldVal = $thisField.val();
					if (thisFieldVal != '' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(thisFieldVal))
					{
						attachMsg($thisField, 'Please enter a valid email address.');
						$thisField.addClass('field-error');
					}
					else
					{
						$thisField.removeClass('field-error');
						$thisField.parent().find('.error-msg').replaceWith('');
					}
				}
			}
		});
		
		// Check if there's any field with error.
		return (this.find('.field-error')[0] == undefined) ? true : false;
	}
	
	// Extending the jQuery
	$.fn.formHelper = function(options)
	{
        return this.each(function(key, value)
	   {
            var $element = $(this);
            // Return early if this element already has a plugin instance
            if ($element.data('formHelper')) return $element.data('formHelper');
            // Pass options to plugin constructor
            var formHelper = new FormHelper(this, options);
            // Store plugin object in this element's data
            $element.data('formHelper', formHelper);
        });
	};
	
})(jQuery);
