(function($) {  
	var self = null;
 	
	$.fn.liveUpdate = function(list) {	
		return this.each(function() {
			new $.liveUpdate(this, list);
		});
	};
	
	$.liveUpdate = function (e, list) {
		this.field = $(e);
		this.list  = $('#' + list);
		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()) == '' && !(document.frm.judgeChk.checked)) { this.list.children('div').show(); return; }
			this.displayResults(this.getScores(this.field.val().toLowerCase()));
		},
		
		setupCache: function() {
			var self = this;
			this.cache = [];
			this.rows = [];
			this.list.children('div').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('div').hide();
			$.each(scores, function(i, score) { self.rows[score[1]].show(); });
		},
		
		getScores: function(term) {
			if(term.indexOf('$$') == -1){
				if(document.frm.judgeChk.checked) {term='entry-title judge'.concat('$$',term);} 
				else {term=''.concat('$$',term);}
			}
			var temp = new Array();
			temp = term.split('$$');

			var scores = [];
			for (var i=0; i < this.cache_length; i++) {
				var score = 0;
				var score1=0;
				var score2=0;
				if(temp[0] != null){
					if(this.cache[i].search(temp[0]) != -1) {score1=1;}
					else {score1=2;}
				}
				if(temp[1] != null){
					if(this.cache[i].search(temp[1]) != -1) {score2=1;}
					else {score2=2;}
				}
				if(temp[0] != null && temp[1] != null){ 
					if(score1==1 && score2==1) score=1;
				} else if(temp[0] != null){
					if(score1==1) score=1;
				}else if(temp[1] != null){
					if(score2==1) score=1;
				} else {
					score=1;
				}
				//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);
