/* Author, Mark VanHolstyn, Mutually Human Software, http://www.mutuallyhuman.com, 2009 */
LabeledInput = Class.create({
  initialize: function(element) {
    this.element = element;
    if (this.element.value == "") {
      this.element.observe("focus", this.clear.bind(this));
      this.element.observe("blur", this.insert.bind(this));

      if (this.element.type == "password") {
        this.labeled_input_type = "password";
      }

      this.insert();
    }
  },

  clear: function() {
    if(this.element.value == this.element.getAttribute("data-label")) {
      this.element.clear();
      this.element.removeClassName("blank");
      this.setPassword();
    }
  },

  insert: function() {
    if (this.element.value.blank()) {
      this.element.value = this.element.getAttribute("data-label");
      this.element.addClassName("blank");
      this.unSetPassword();
    }
  },

  reset: function() {
    this.clear();
    this.insert();
  },

  setPassword: function() {
    if((this.labeled_input_type =='password') && this.element.type == 'text') {
      this.element.type = 'password';
    }
  },

  unSetPassword: function() {
    if((this.labeled_input_type =='password') && this.element.type == 'password') {
      this.element.type = 'text';
    }
  }
});

LabeledInput.clear = function(form) {
  form.select('*[data-label]').each(function(element) {
    element.labeled_input.clear();
  });
};

LabeledInput.initialize = function() {
  $$("form").each(function(element) {
    element.observe("submit", LabeledInput.clear.bind(this, element));
  });

  $$('input[data-label], textarea[data-label]').each(function(element) {
    if(!element.labeled_input) {
      var labeled_input = new LabeledInput(element);
      element.labeled_input = labeled_input;
    }
  });
}

document.observe("dom:loaded", function() {
  LabeledInput.initialize();
});