/**
 * Watermark plugin 1.0
 *
 * Copyright (c) 2008 Blit, Inc (http://blit.com/)
 * MIT license (blit.com/licenses/mit.html)
 */
/**
  * Uses custom element attributes to watermark input fields.
  * 
  * example usage:
  *
  * <form id="form1"><input type="text" class="watermark" watermark="first name"/></form>
  *
  * $(function() {
  *   $('#form1').watermark();
  * });
  *
  */

jQuery.fn.watermark = function(options) {
    options = jQuery.extend({
      color: '#aaa',
      text: undefined,
      clear: false
    }, options);
    
    function clear_watermark($element) {
      if ($element.attr('wm_color_cache') && $element.css('color') != $element.attr('wm_color_cache')) $element.css('color',$element.attr('wm_color_cache'));
      if ($element.val()==$element.attr('watermark')) $element.val('');
    }
  
    if (!this.is('form')) return this;
    var $selection = this.find(':text.watermark, textarea.watermark')
    if (options.clear==true) return $selection.each(function(){
      clear_watermark(jQuery(this));
      });
    
    if (this.data('wm_form_submit')==null) this.data('wm_form_submit',this.bind('submit',function(){
      jQuery(this).watermark({clear:true});
      return true;
      }));
    
    return $selection.bind('focus blur change watermark',function(event) {
      var $this = jQuery(this);
      //console.log(event.type);
      if (event.type=='focus') return clear_watermark($this);
      if (!$this.attr('watermark')) $this.attr('watermark',options.text);
      if (!$this.attr('wm_color_cache')) $this.attr('wm_color_cache',$this.css('color'));
      if ($this.val().length==0 || $this.val()==$this.attr('watermark')) {
        $this.css('color',options.color);
        $this.val($this.attr('watermark'));
      } else clear_watermark($this);
      //console.log();
    }).trigger('watermark');
};