// Based on prototype livesearch.js from Orderedlist.com
// http://orderedlist.com/demos/quicksilverjs/javascripts/livesearch.js
// 
// Port author: Oskar Krawczyk - http://blog.olicio.us/

var QuicksilverLiveSearch = new Class({

    Implements: Options,

    options: {
        field: $empty,
        list: $empty
    },

    initialize: function(options) {
        this.setOptions(options);
        this.field = $(this.options.field);
        this.list = $(this.options.list);

        if (this.field && this.list) {
            this.rows = $A([]);
            this.cache = $A([]);
            this.setupCache();
            this.form = this.field.getParent('form');
            this.form.addEvent('submit', function(e) { e.stop(); });
            this.field.addEvent('keyup', this.filter.bind(this));
            this.filter();
        }
    },

    setupCache: function() {
        this.list.getChildren().each(function(child) {
            this.cache.push(child.get('text').toLowerCase());
            this.rows.push(child);        
        } .bind(this));
        this.cache_length = this.cache.length;

    },

    filter: function() {
        if (!this.field.get('value')) { $$(this.rows).set('styles', { display: 'block' }); return; }
        this.displayResults(this.getScores(this.field.value.toLowerCase()));
    },

    displayResults: function(scores) {
        $$(this.rows).set('styles', { display: 'none' });
        scores.each(function(score) { this.rows[score[1]].set('styles', { display: 'block' }); } .bind(this))
    },

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

        for (var i = 0; i < this.cache_length; i++) {
            var score = this.cache[i].score(term);
            if (score > 0.8) { scores.push([score, i]); }
        }

        return scores.sort(function(a, b) { return b[0] - a[0]; });
    }
});
