/**
 * fhInputClear - Freshheads Input Clear
 *   http://www.freshheads.com
 *
 * Copyright (c) 2009 Freshheads
 * 
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 
 *
 * Default Usage:
 * The function works on text input field or textareas given to it by a selector:
 * $('input[type=text], textarea').fhInputClear();
 * From each selected element the title is taken and put in as the default value. A class 'fhInputClear' is given to each element on empty.
 *
 
 *
 * Usage with options: *
 * $.fhInputClear({
 *   className: 'fhInputClear'
 * });
 *
 
 *
 * Authors: Gijs van Zon MA
 * Return: Object (this)
 * Params:
 *   className: String ('fhInputClear')
 */

(function($) {

  $.fn.fhInputClear = function(options) {

    var _this = this;
    
    var defaults = {
      className: 'fhDefaultValue'
    }

    defaults = $.extend({}, defaults, options || {});
    
    var elements = this.each(function () {
            
      var $this = $(this);

      if($this.attr('title')){
        $this.data('originalValue', $this.attr('title'));
        if($this.attr('maxlength')){
          $this.data('maxlength', $this.attr('maxlength'));
          if($this.data('maxlength') <= 0)
            $this.data('maxlength', 1000);
        }

       if($this.data('originalValue')) {
          if($this.val() == '' || $this.val() == $this.data('originalValue')) {
            if($this.attr('maxlength')){
              $this.attr('maxlength', 100);
            }
            $this.val($this.data('originalValue'));
            $this.addClass(defaults.className);
          }
 
          $this
            .bind('focus', function() {
              if($this.val() == $this.data('originalValue')) {
                $this.val('');
                $this.removeClass(defaults.className);
                if($this.attr('maxlength')){
                  $this.attr('maxlength', $this.data('maxlength'));
                }
              }
            })
            .bind('blur', function() {
              if($this.data('originalValue') != '' && $this.val() == '') {
                if($this.attr('maxlength')){
                  $this.attr('maxlength', 100);
                }
                $this.val($this.data('originalValue'));
                $this.addClass(defaults.className);
              }
            });
        }
      }
            
    });
      
    $('form').bind('submit', function(e) {
      _this.each(function() {
        $this = $(this);
        if($this.val() == $this.data('originalValue')) {
          $this.val('');
        }
      });
    });
    
    return elements;
    
  }
  
})(jQuery);

