// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var LiveSearch = Class.create({
  initialize: function(field, results) {
    this.field = $(field);
    this.setDefault();
    this.results = $(results);
    this.choices = 10;
    this.no_match = "<div class=\"no-results\">No Matches Found</div>";
    this.field.observe('focus', this.removeDefault.bindAsEventListener(this));
    this.field.observe('blur', this.setDefault.bindAsEventListener(this));
    this.field.observe('keyup', this.search.bindAsEventListener(this));
  },

  search: function() {
    if (!this.field.present() || /^( )+$/.test($F(this.field)) || $F(this.field) == "Search Site" ) {
      this.results.hide();
      return;
    }
    var results = this.artistSelector($F(this.field).toLowerCase()) + this.workSelector($F(this.field).toLowerCase());

    this.results.innerHTML = (results != "") ? results : this.no_match;
    this.results.show();
  },

  selector: function(entry, collection) {
    var searchWords = $A(entry.toLowerCase().split(" ").uniq());
    var selected = $A([]);

    collection.each( function(element) {
    // for (var i = 0; i < collection.length && selected.length <= this.choices; i++) {
      // var element = collection[i];

      var match = searchWords.length && searchWords.all( function(s) {
        return element.keywords.any( function(k) {
          var foundPos = k.indexOf(s);
          return foundPos == 0; //only matches at beginning of word
        });
      });

      if (match) {
        selected.push(element);
      }
    });

    var ret = selected.map( function(element){
      return "<li><a href=\"" + element.link +"\">" + element.text + "</a></li>";
    });

    if (ret.length > this.choices) {
      ret = ret.slice(0, this.choices);
      ret.push("<li class=\"no-results\">More matches found, please narrow your search...</li>");
    }

    return ret;
  },

  artistSelector: function(entry) {
    var ret = this.selector(entry, artists);

    if (ret.length) return "<ul class=\"artists\"><h3>Artists</h3>" + ret.join('') + "</ul>";
    return "";
  },

  workSelector: function(entry) {
    var ret = this.selector(entry, works);

    if (ret.length) return "<ul class=\"works\"><h3>Products</h3>" + ret.join('') + "</ul>";
    return "";
  },

  getScores: function(term, arr) {
    var scores = $A([]);

    term = term.toLowerCase();

    // loop through the cache and get the score for each item
    // appending them to the return set if they have a score
    // greater than 0; basically building an array like this:
    // [[0.69, 2], [0.33, 34], ...] where the first element is
    // the string score and the second is the index of the item
    // that scored that
    for (var i=0; i < arr.length; i++) {
      var score = arr[i].name.toLowerCase().score(term);
      if (score > 0) { scores.push([score, i]); }
    }

    // sort the scores descending by the algorithm score (the first element in the array)
    return scores.sort(function(a, b) { return b[0] - a[0]; });
  },
  
  setDefault: function() {
    if (/^$/.test($F(this.field))) {
      this.field.addClassName('default');
      this.field.value = 'Search site';
    }
  },
  
  removeDefault: function() {
    if (/^Search site$/.test($F(this.field))) {
      this.field.removeClassName('default');
      this.field.value = '';
    }
  }

});

document.observe('dom:loaded', function() {
  new LiveSearch('search-text', 'search-results');
});
