/* FormLabel by Scott Meves, (c) 2009
 * Stereo Interactive & Design
 *
 * Usage: 
 *   <script src="prototype.js" type="text/javascript"></script>
 *   <script src="form.js" type="text/javascript"></script>
 *
 *   <input id="homeserial" type="text" name="q" size="20" class="serialbox searchbg">
 *   <script type="text/javascript">
 *    //<![CDATA[
 *      var homeserialLabel = new FormLabel('homeserial', {image:'images/bg_esn.png', emptyImage:'images/bg_esn_notext.png'});
 *    //]]>
 *    </script>
 * 
 * You can use destroy() to remove the event observers
 */

var FormLabel = Class.create();

FormLabel.prototype = {
  initialize: function(element) {
    var options = Object.extend({
      image: false,
      emptyImage: false,
      label: false,
      className: 'background'
    }, arguments[1] || {});

    this.element      = $(element);

    this.options      = options;
    
    this.eventFocus = this.hideBackground.bindAsEventListener(this);
    this.eventBlur = this.showBackground.bindAsEventListener(this);
    this.eventSubmit = this.formSubmit.bindAsEventListener(this);
    
    this.initBackground();
    
    this.registerEvents();
  },
  
  registerEvents: function() {
    Event.observe(this.element, "focus", this.eventFocus);
    Event.observe(this.element, "blur", this.eventBlur);
    Event.observe(this.element.form, "submit", this.eventSubmit);
  },
  
  destroy: function() {
    Event.stopObserving(this.element, "focus", this.eventFocus);
    Event.stopObserving(this.element, "blur", this.eventBlur);
    Event.stopObserving(this.element.form, "submit", this.eventSubmit);
  },

  hideBackground: function(event)
  {
    if (this.options.emptyImage) {
      this.element.style.background = 'transparent url('+this.options.emptyImage+') no-repeat';
    }
    if (this.options.label && this.options.label == this.element.value) {
      this.element.value = '';
      if (this.options.className) {
        this.element.removeClassName(this.options.className);
      }
    }
  },
  
  showBackground: function(event)
  {  
    if (this.element.value == '') {
      if (this.options.image) {
        this.element.style.background = 'transparent url('+this.options.image+') no-repeat';
      }
      
      if (this.options.label) {
        this.element.value = this.options.label;
      }
      
      if (this.options.className) {
        this.element.addClassName(this.options.className);
      }
    }
  },
  
  formSubmit: function(event)
  {
    if (this.element.value == this.options.label) {
      this.element.value = '';
    }
  },
  
  initBackground: function()
  {
    this.showBackground();
  }
}
