(function($) {
  $.fn.athleteSearch = function(options) {
    var opts = $.extend({}, $.fn.athleteSearch.defaults, options);
    return $(this).each(function() {
      var athletesearch = $(this);
      athletesearch.addClass("athlete-search");

      var closeButton = $('<div style="cursor: pointer; position: absolute; margin-top: -1.3em"><img src="/seaside/files/ASLibrary/x.gif"></img></div>')
        .click(function() {
          chooser.hide();
          selected.show() 
      });
      
      var selected = $('<div class="athlete-search-selected">' + opts.noSelectionText + '</div>')
        .css("width", opts.width)
        .click(function() {
          closeButton.css("left", (athletesearch.offset().left + athletesearch.width() - 12) + "px");
          selected.hide();
          chooser.show();
          input.select();
        });

      var chooser = $('<div style="display: none" class="athlete-search-panel"></div>')
        .css("width", opts.width);
    
      var input = $('<input style="background-image: url(../../misc/throbber.gif); background-position: 100% 2px; background-repeat: no-repeat" type="text"/>')
        .css("width", opts.width)
        .keyup(function(event) {
          if(event.keyCode == 27) {
            chooser.hide();
            selected.show();
          } else if(!athletesearch.data("searchRequest") && (athletesearch.data("searchText") != input.val())) {
            athletesearch.data("searchText", input.val());
            athletesearch.stopTime("search");
            athletesearch.oneTime(500, "search", function() { athletesearch.trigger("search") });
          }
        });

      if ($.browser.msie) {
        input.css("padding", "0px 3px");
      }

      var table = $("<table/>");
     
      chooser.append(closeButton);
      chooser.append(input);
      chooser.append($("<div class=\"athlete-search-chooser\" style=\"display: none\"></div>").append(table));

      athletesearch
        .bind("choose", function(event, id, text) {
          athletesearch.data("id", id);
          chooser.hide();
          selected
            .text(text)
            .show();
          opts.onChoose(id);
        })
        .bind("search", function() {
          table.parent().hide();
          table.empty();
          if ($.trim(athletesearch.data("searchText")) == "") {
            return;
          }
          input.css("background-position", "100% -18px");
          athletesearch.data(
            "searchRequest", 
            $.get("/nodereference/autocomplete/athletesearch/" + encodeURIComponent(athletesearch.data("searchText"))));
          athletesearch.ajaxComplete(function(request, settings) {
            input.css("background-position", "100% 2px");
            if((athletesearch.data("searchRequest") != settings)) {
              return;
            }
            athletesearch.data("searchRequest", null);
            if(athletesearch.data("searchText") == input.val()) {
              var json = JSON.parse(settings.responseText);
              var bestScore = parseFloat(json[0][5]);
              table.empty();
              table.parent()
                .show()
                .css("height", Math.min(200, json.length * 21) + "px");
              $.each(json, function(i, athlete) {
                if(athlete[0]) {
                  if (!bestScore) {
                    bestScore = parseFloat(athlete[5]);
                  }
                  var row = $("<tr class=\"" + (athlete[6] == "t" ? "male" : "female") + "\"><td>" + athlete[1] + "</td><td>" + athlete[2] + "</td><td>" + athlete[3] + "</td><td>" + athlete[4] + "</td></tr>") 
                    .data("id", athlete[0])
                    .css("font-weight", Math.floor(9.0 * parseFloat(athlete[5]) / bestScore) * 100)
                    .children()
                      .click(function() {
                        athletesearch.trigger(
                          "choose", [ 
                            row.data("id"), 
                            $.map(
                              $.makeArray(row.children()), function(ea) { return $(ea).text() }
                            ).join(" ") ]);
                      })
                    .end();
                  table.append(row);
                }
              });
            } else {
              athletesearch.data("searchText", input.val());
              athletesearch.trigger("search");
            }
          });
        })
      athletesearch
        .append(selected)
        .append(chooser)
    });
  }
  $.fn.athleteSearch.defaults = {
    noSelectionText: "Choose an athlete!",
    onChoose: function(id) {},
    width: "290px"
  };
})(jQuery);

