﻿(function($) {
    var self = null;

    $.fn.liveUpdate = function(list, outputList) {
		
        return this.each(function() {
            new $.liveUpdate(this, list, outputList);
        });
    };

    $.liveUpdate = function(e, list, outputList) {
        this.field = $(e);
        this.list = $('#' + list);
        this.outputList = $('#' + outputList);
        if (this.list.length > 0) {
            this.init();
        }
    };

    $.liveUpdate.prototype = {
        init: function() {
            var self = this;
            this.setupCache();
            this.field.parents('form').submit(function() { return false; });
            this.field.keyup(function() { self.filter(); });
            self.filter();
        },

        filter: function() {
			
        if ($.trim(this.field.val()) == '') { this.list.hide(); this.outputList.hide(); $("#resultsNo").text(''); this.list.children('li').show(); $(".results_no").css('display','none');return; }
            this.outputList.show();
            this.displayResults(this.getScores(this.field.val().toLowerCase()));
        },
		


        setupCache: function() {
            var self = this;
            this.cache = [];
            this.rows = [];
            this.list.children('li').each(function() {
                self.cache.push(this.innerHTML.toLowerCase());
                self.rows.push($(this));
            });
            this.cache_length = this.cache.length;
        },
		
        displayResults: function(scores) {
            var self = this;
            this.list.children('li').hide();
            $("span", $("li", this.list)).text("");
            $("#outputPosts li").remove();
            $.each(scores, function(i, score) {
                $("#allPosts li:eq(" + score[1] + ")").show().clone().appendTo($("#outputPosts"));
                //$("span", $("li:eq(" + score[1] + ")", $("#allPosts"))).text(i + " - " + score[0] + " - " + score[1]);
            });
			$("#resultsNo").html(scores.length);
			$(".results_no").css('display','block');
			$("#outputPosts li:first").addClass("first"); //LACHLANN ADDED THIS TO APPLY A FIRST CLASS TO THE TOP LI
        },

        getScores: function(term) {
            var scores = [];
            for (var i = 0; i < this.cache_length; i++) {
                var score = this.cache[i].score(term);
                if (score > 0) { scores.push([score, i]); }
            }
            return scores.sort(function(a, b) { return b[0] - a[0]; });
        }
    }
})(jQuery);
