1Search = function(data, input, result) {
2  this.data = data;
3  this.$input = $(input);
4  this.$result = $(result);
5
6  this.$current = null;
7  this.$view = this.$result.parent();
8  this.searcher = new Searcher(data.index);
9  this.init();
10}
11
12Search.prototype = $.extend({}, Navigation, new function() {
13  var suid = 1;
14
15  this.init = function() {
16    var _this = this;
17    var observer = function() {
18      _this.search(_this.$input[0].value);
19    };
20    this.$input.keyup(observer);
21    this.$input.click(observer); // mac's clear field
22
23    this.searcher.ready(function(results, isLast) {
24      _this.addResults(results, isLast);
25    })
26
27    this.initNavigation();
28    this.setNavigationActive(false);
29  }
30
31  this.search = function(value, selectFirstMatch) {
32    value = jQuery.trim(value).toLowerCase();
33    if (value) {
34      this.setNavigationActive(true);
35    } else {
36      this.setNavigationActive(false);
37    }
38
39    if (value == '') {
40      this.lastQuery = value;
41      this.$result.empty();
42      this.setNavigationActive(false);
43    } else if (value != this.lastQuery) {
44      this.lastQuery = value;
45      this.firstRun = true;
46      this.searcher.find(value);
47    }
48  }
49
50  this.addResults = function(results, isLast) {
51    var target = this.$result.get(0);
52    if (this.firstRun && (results.length > 0 || isLast)) {
53      this.$current = null;
54      this.$result.empty();
55    }
56
57    for (var i=0, l = results.length; i < l; i++) {
58      target.appendChild(this.renderItem.call(this, results[i]));
59    };
60
61    if (this.firstRun && results.length > 0) {
62      this.firstRun = false;
63      this.$current = $(target.firstChild);
64      this.$current.addClass('current');
65    }
66    if (jQuery.browser.msie) this.$element[0].className += '';
67  }
68
69  this.move = function(isDown) {
70    if (!this.$current) return;
71    var $next = this.$current[isDown ? 'next' : 'prev']();
72    if ($next.length) {
73      this.$current.removeClass('current');
74      $next.addClass('current');
75      this.scrollIntoView($next[0], this.$view[0]);
76      this.$current = $next;
77    }
78    return true;
79  }
80
81  this.hlt = function(html) {
82    return this.escapeHTML(html).
83      replace(/\u0001/g, '<em>').
84      replace(/\u0002/g, '</em>');
85  }
86
87  this.escapeHTML = function(html) {
88    return html.replace(/[&<>]/g, function(c) {
89      return '&#' + c.charCodeAt(0) + ';';
90    });
91  }
92
93});
94
95