/*

EmptyText decorator for <input type="text"> elements.
Given an input DOM element and the default "empty text" to display:
- Displays the "empty text" when nothing is entered in the input
- Hides the "empty text" when cursor enters the input, re-shows on blur
Sample usage:
var x = new EmptyText(document.getElementById('myInput'), 'Type Here!');
That's all. The EmptyText object manages everything else via events.

Also:
var x = new EmptyText(document.getElementById('myInput'), 'Type Here!', 'placeholder');
This will add the CSS class 'placeholder' to the input element whenever the 
"empty text" placeholder text is visible. This allows you to style the input 
differently when the placeholder is visible.

Author: Mike Mertsock, mmertsock@fusionproductions.com
Change log:
2010-02-18 mmertsock: Created
2010-06-17 mmertsock: added cssClass option.
*/

var EmptyText = function(elem, text, cssClass) {
  this.elem = elem;
  this.text = text;
  this.cssClass = cssClass ? cssClass : '';
  this.setEnabled();
  this.origOnFocus = this.elem.onfocus;
  this.origOnBlur = this.elem.onblur;
  if (this.enableEmptyText)
    this.showPlaceholder();
  var self = this;
  this.elem.onfocus = function() { self.doFocus(); };
  this.elem.onblur = function() { self.doBlur(); };
};

EmptyText.prototype.setEnabled = function() {
  this.enableEmptyText = (this.elem.value.length === 0);
  return this.enableEmptyText;
};

EmptyText.prototype.removePlaceholder = function() {
  this.elem.value = "";
  this.elem.className = this.elem.className.replace(' ' + this.cssClass, '');
};

EmptyText.prototype.showPlaceholder = function() {
  this.elem.value = this.text;
  this.elem.className += ' ' + this.cssClass;
};

EmptyText.prototype.doFocus = function() {
  if (this.origOnFocus) this.origOnFocus();
  if (this.enableEmptyText && (this.elem.value == this.text)) {
    this.removePlaceholder();
  }
};

EmptyText.prototype.doBlur = function() {
  if (this.origOnBlur) this.origOnBlur();
  if ( this.setEnabled() ) {
    this.showPlaceholder();
  }
};

