﻿/*
 * jQuery Form Watermark
 *
 * Author: Damian Janowski
 * E-mail: damian.janowski@citrusbyte.com
 * Downcoded by: Juan Pieres
*/

$.widget("ui.watermark", {
  init: function() {
    var watermark = this;

    var form = this.element;

    this.elements = $("input:text, textarea", form);

    this.elements.focus(this.handlerOff);
    this.elements.blur(this.handlerOn);

    this.refresh();

    $(form).submit(function() {
      this.elements.each(watermark.handlerOff);
      return true;
    });
  },

  refresh: function() {
    this.elements.each(this.handlerFirst);
  },
  
  handlerFirst: function() {
    $(this).addClass("watermark");
    if (this.value == '') {
      this.value = this.title;
    }
    return true;
  },

  handlerOn: function() {
    this.elements = $("input:text, textarea", $("form").element);
    var hasValue = false; 
    this.elements.each(function(){
        if (this.value != this.title && this.value != ''){
            hasValue = true;
        }
    });
    this.elements.each(function(){
        if (this.title && this.title != '' && (this.value == '' || this.value == this.title) && !hasValue) {
          $(this).addClass("watermark");
          this.value = this.title;
        }
    });
    return true;
  },

  handlerOff: function() {
    $(this).click();
    this.elements = $("input:text, textarea", $("form").element);
    this.elements.each(function(){
        var initialValue = this.value;
        if (this.type == 'text' || this.type == 'textarea') {
          if ((this.title && this.title != '')) {
            if (initialValue == this.title)
            {
                this.value = '';
            }
            $(this).removeClass("watermark");
          }
        }
        return true;
    });
  }
});
