var SubmitBun = Class.create({
  initialize: function(input, options) {
    this.input = input;

    if (options)
      this.options = options;
    else
      eval('this.options = ' + input.className.substr(SubmitBun.CLASS_TEXT.length));

    this.form = this.input.up('form');
  },

  replace: function() {
    var classes = $w(this.input.className);
    var hiddenInput = new Element('input', {
      'type': 'hidden',
      'value': this.input.getValue(),
      'name': this.input.name
    });
    this.input.replace(hiddenInput);
    this.input = hiddenInput;

    this.link = new Element('a', {
      'class': 'submit-bun-link',
      'href': '#'
    });

    if (this.options['class'])
      this.link.addClassName(this.options['class']);
    this.link.observe('click', this.submit.bindAsEventListener(this));
    this.link.observe('mouseover', this.over.bindAsEventListener(this));
    this.link.observe('mouseout', this.out.bindAsEventListener(this));
    this.form.observe('keypress', this.keyPressHandler.bindAsEventListener(this));

    for (var i = 0; i < classes.length; i++)
      this.link.addClassName(classes[i]);

    if (this.options.src) {
      this.image = new Element('img', {
        'src': this.options.src,
        'border': 0,
        'class': 'submit-bun-image'
      });
      this.link.insert(this.image);
      var preload = new Element('img', {
        'src': this.options.over,
        'border': 0,
        'width': 1,
        'height': 1,
        'style': 'display: none'
      })
      this.link.insert(preload);
    } else {
      this.link.update(this.input.value);
    }

    this.input.insert({before: this.link});
  },

  keyPressHandler: function(event) {
    if (event.keyCode == 13) this.submit(event);
  },

  submit: function(event) {
    event.stop();

    if (this.form.onsubmit)
    if (this.form.onsubmit() == false) return false;
    this.form.submit();

    return false;
  },

  over: function() {
    if (this.options.over)
      this.image.src = this.options.over;
  },

  out: function() {
    if (this.options.src)
      this.image.src = this.options.src;
  }
});

SubmitBun.replace = function(element, options) {
  var bun = new SubmitBun(element, options);
  bun.replace();
}

SubmitBun.CLASS_TEXT = 'submit-bun';

subms = [];

function loadSubmitm() {
  $$('input').each(function(input) {
    if (input.className.substr(0, SubmitBun.CLASS_TEXT.length) == SubmitBun.CLASS_TEXT) {
      subms.push(new SubmitBun(input));
    }
  });

  subms.each(function(subm) {
    subm.replace();
  });
}

$(document).observe('dom:loaded', function() {
  loadSubmitm();

  $$('.bun').each(function(button) {
    (new SubmitBun(button, {})).replace();
  });
});