/*!
 * 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
 */
if(jQuery) // Check if jQuery is loaded
{
  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');
      
      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);
            input.bind('change', function(){
              input.removeClass(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;
      });
    });
  };
}
