/**
 * FormHelpers - defaultValuedInput plugin for jQuery 1.3.2+
 * 
 * Author: Johannes Wüller
 * Created On: 16.04.2010
 *
 * Ensures that a given value is restored if an <input> loses focus and the
 * default value is removed if the <input> gains focus. This function can be
 * chained. It overrides existing bindings of this plugin so it is possible to
 * apply it multiple times to change the parameters.
 *
 * Usage:
 *    // This adds "username" as the default value that is present until the
 *    // user attempts to write something else in there.
 *    $("input.username").defaultValuedInput('username');
 *
 * Parameters:
 *    defaultValue   value to be maintained as the default
 *    activeClass    class used to indicate if the input is not default-valued.
 *                   default: "active"
 */
;(function($) {
   var pluginName = 'defaultValuedInput';

   $.fn[pluginName] = function(defaultValue, activeClass) {
      activeClass = activeClass || 'active';

      // Ensure that the selected elements are not influenced by earlier
      // bindings from this plugin.
      return $(this).unbind('.'+pluginName).each(function() {
         var e = $(this),
            data = e.data(pluginName),

            focusAction = function() {
               var e = $(this);
               
               if (e.val() === defaultValue) {
                  e.val('');
               }
               
               e.addClass(activeClass);
            },
            
            blurAction = function() {
               var e = $(this);

               if (e.val() === defaultValue || e.val() === '') {
                  e.val(defaultValue).removeClass(activeClass);
               }
            };
         
         if (data) {
            // Remove stuff from previous bindings.
            e.removeClass(data.activeClass);

            if (e.val() === data.defaultValue) {
               e.val('');
            }
         } else {
            data = {};
            e.data(pluginName, data);
         }

         // Save these for future use.
         data.defaultValue = defaultValue;
         data.activeClass = activeClass;

         // Set initial state by simulating a usage cycle.
         focusAction.call(e);
         blurAction.call(e);
         
         // Bind events. They are namespaced to avoid unbinding conflicts.
         e.bind('focus.'+pluginName, focusAction).bind('blur.'+pluginName, blurAction);
      });
   };
}(jQuery));
