/*!
 * jQuery Check Required Plugin
 * Checks if fields marked as required are empty
 * and show error message if they are
 *
 * Copyright (c) 2011 Dmitriy Kubyshkin (http://kubyshkin.ru)
 * Licensed under the MIT license
 */
(function($) { // Making $ accessible even in noConflict
  jQuery.fn.checkRequired = function(options){
    var options = jQuery.extend({
      errorClassName: "error-field"
    },options);

    return $(this).each(function(){
      var hold = $(this);
    
      // Finding all form elements
      inputs = hold.find('input, select, textarea').filter('.required');
    
      // We don't know if there's an error after form changed
      inputs.bind('change', function(){
        $(this).removeClass(options.errorClassName);
      });
    
      hold.bind('submit', function(){
        // At first assuming that all went smoothly
        var returnValue = true;
      
        // Then we check each required field if it has some value
        inputs.each(function(){
          var input = $(this);
          // If field doesn't have a value
          if(input.val() == "" || input.val() == input.get(0).defaultValue)
          {
            // We make sure form won't get submitted
            returnValue = false;
            // Add appropriate css class for error
            input.addClass(options.errorClassName);
          }
          else
          {
            // Need to cleanup if form was previously had errors
            input.removeClass(options.errorClassName);
          }
        });
      
        // If there are errors we need to tell the user
        if(!returnValue)
        {
          alert("Some required fields are missing.\nPlease check your input and try again.");
        }
        return returnValue;
      });
    });
  };
})(jQuery);
