var RecaptchaFixer = Behavior.create({
  initialize: function() {
    Recaptcha.widget = Recaptcha.$("recaptcha_widget_div");
    Recaptcha.challenge_callback();
    
    /* The non JavaScript version of recaptcha displays it's own error message */
    $("recaptcha_widget_div").insert(
      {
        before: $p("Please demonstrate that you're a real person by entering \
                    the two words shown below before running your search.")
      }
    );
  }
});

var Tooltip = Behavior.create({
  initialize: function() {
    this._createToolTip(this.element);
    this._bindEventListeners();
  },
  _createToolTip: function(link) {
    this.clickable = $a({ href: "#", title: "What's this?" }, "?");
    link.insert({
      after: $span({ "class": "help" }, " (", this.clickable, ") ")
    });
    this.tooltip = $div({ "class": "tooltip" }, link.title);
    this.tooltip.hide();
    link.title = "";
    link.insert({ after: this.tooltip });
  },
  _bindEventListeners: function() {
    this.clickable.observe("click", this._onClick.bindAsEventListener(this));
    this.clickable.observe("mouseout", this._hide.bindAsEventListener(this));
  },
  _onClick: function(event) {
    Event.stop(event);
    if (this.tooltip.visible())
      this._hide(event);
    else
      this._show(event);
  },
  _show: function(event) {
    var offset = this.clickable.positionedOffset();
    var tipWidth = parseInt(this.tooltip.getStyle("width"), 10);
    this.tooltip.setStyle({
      top: offset["top"] + 20 + "px",
      left: (offset["left"] - tipWidth / 2) + "px"
    });
    this.tooltip.show();
  },
  _hide: function(event) {
    this.tooltip.hide();
  }
});

Event.addBehavior({
  "#recaptcha_widget_div": RecaptchaFixer(),
  "a.help": Tooltip,
  "input#seed": function() { this.activate(); }
});
