Event.observe(window,'load', function() {
  new ClearOnSubmit($$('input.clearonfocus').map(function(element) {
      return new ClearOnFocus(element)
  }))
})

var ClearOnSubmit = Class.create()
Object.extend(ClearOnSubmit.prototype, {
  initialize: function(clearOnFocusElements) {
    if(clearOnFocusElements.size() > 0) {
      this.clearOnFocusElements = clearOnFocusElements
      this.form = $(this.clearOnFocusElements.first().element.up('form'))
      this.originalOnSubmit = this.form.onsubmit
      this.form.onsubmit = function(){return false}
      this.form.observe('submit', this.onSubmit.bind(this))
    }
  },
  onSubmit: function(event) {
    this.clearOnFocusElements.each(function(element) {
      element.onFocus()
    })
    this.originalOnSubmit.bind(this.form)()
  }
})

var ClearOnFocus = Class.create()
Object.extend(ClearOnFocus.prototype, { 
  initialize: function(element) { 
    this.element = $(element)
    this.originalValue = $F(element)
    this.element.observe('blur', this.onBlur.bind(this))
    this.element.observe('focus', this.onFocus.bind(this))
  }, 
  onFocus: function(event) { 
    if($F(this.element) == this.originalValue) { 
      this.element.value = ''
      this.element.removeClassName('clearonfocus')
    } 
  }, 
  onBlur: function(event) { 
    if($F(this.element).match(/^\s*$/)) { 
      this.element.value = this.originalValue
      this.element.addClassName('clearonfocus')
    } 
  } 
})
