(function ($) {
Drupal.behaviors.mercySelectbox = {
  attach: function(context, settings) {

    // Only perform this Javascript on page load.
    if (context != document) {
      return;
    }

    function createDropDown(){
      var source = $('#mercy-search-form select');
      var selected = source.find("option:first-child");
      var options = $("option", source);
      $('#mercy-search-form select').after('<dl id="target" class="dropdown"></dl>');
      $("#target").append('<dt><a href="#">' + selected.text() +
        '<span class="value">' + selected.val() +
        '</span></a></dt>');
      $("#target").append('<dd><ul></ul></dd>');
      options.each(function() {
        $("#target dd ul").append('<li><a href="#">' +
          $(this).text() + '<span class="value">' +
          $(this).val() + '</span></a></li>');
      });
    }

    createDropDown();

    $(".dropdown dt a").click(function() {
      $(".dropdown dd ul").toggle();
      return false;
    });

    $(document).bind('click', function(e) {
      var $clicked = $(e.target);
      if (! $clicked.parents().hasClass("dropdown")) {
        $(".dropdown dd ul").hide();
      }
    });

    $(".dropdown dd ul li a").click(function() {
      var text = $(this).html();
      $(".dropdown dt a").html(text);
      $(".dropdown dd ul").hide();

      var source = $('#mercy-search-form select');
      source.val($(this).find("span.value").html());
    });

    $('#mercy-search-form select').hide();

  }
};
})(jQuery);;

