var curSelection = null;
var curPosition = -1;
var curList = [];
var done = false;
var cc = [];

jQuery.fn.liveUpdate = function(oform,olist,choices){

  list = jQuery(olist);
 // form = jQuery(oform);

  for (var i=0;i<choices.length;i++) {
	cc.push(choices[i].toLowerCase()); //for quicksilver scoring
  }
  
  this
     .keyup(buildList).keyup().parents('form').submit(function(){
	showTrendPage();
        return false;
      });

  
   
  return this;

  function showTrendPage() {
	done = true;
	location.href = "/tag/" + jQuery(curSelection).html().replace(/^#/,'_');
  }

  function switchSelection(sel) {
	if (sel == null) {
		return;
	}
	if (curSelection!=null) {
		jQuery(curSelection).css("background-color","white");
	}
	jQuery(sel).css("background-color","#9fffff");
	curSelection = sel;
	curPosition = curList[jQuery(sel).html().toLowerCase()];
  }
   
  function buildList(event){

	if (done) return;
	if(event.keyCode==40 && curSelection != null) {
		switchSelection(list.children('li')[curPosition+1]);
		return;
	}
	if(event.keyCode==38 && curSelection != null) {
		switchSelection(list.children('li')[(curPosition-1)]);

		return;
	}
	
    	var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];
   	if (term == '') {
		list.html('');
		return;
	}

	for (var i=0;i<cc.length;i++) {
		var co = cc[i];
        	var score = co.score(term);
        	if (score > 0) { scores.push([score, i]); }

      	 }

	scores.sort(function(a, b){return b[0] - a[0];});
	curList=[];
       
	out = '';
	for (var j=0;j<scores.length && j<=16 && scores[j][0]>0;j++) {
		var sco = scores[j];
		out += '<li>' + choices[sco[1]] + '</li>';
		curList[cc[sco[1]]] = j;
	}
	
	list.html(out);
	switchSelection(list.children('li')[0]);
	list.children('li').hover(
		function(){
			switchSelection(this);
		},
		function(){}
	);
	list.children('li').click(
		function(){
			showTrendPage();
		}
		
	);


   }
     
  
};
