function LiveSearch(field, div, searchSelector) { this.construct(field, div, searchSelector) }

LiveSearch.prototype = {
  field:   null,
  div:     null,
  prevQ:   '',
  prevT:   null,
  timeout: null,
  elms: null,
  
  construct: function(field, div, searchSelector) {
    this.field = field;
    this.div = div;
    this.prevT = new Date();
    this.elms = document.getElementsBySelector(searchSelector);

    var th = this;
    addEvent(field, 'onkeydown', function(e) {
      th.prevT = new Date();
      if (e.keyCode == 13) th.onchangeControl(this.value, 100);
      return true;
    })
    addEvent(field, 'onkeyup', function(e) { 
      if (e.keyCode == 13) return true;
      th.onchangeControl(this.value, e.keyCode==32? 1000 : null);
      return true;
    })
    addEvent(field, 'onfocus', function() {
      // stupid Mozilla sometimes loses focus on DIV repainting :-(
      th.focused = true;
      return true;
    })
    addEvent(field, 'onblur', function() {
      th.onchangeControl(field.value, 0);
      th.focused = false;
      return true;
    })
  },
  
  onchangeControl: function(text, dt) {
    var t = new Date();
    var wait = 0;
    if (dt == null) dt = 1000;
    
    if (t.getTime() - this.prevT.getTime() < dt) {
      this.prevT = t;
      wait = dt;
    }
    
    var th = this;
    if (this.timeout) { clearTimeout(this.timeout); this.timeout=null; }
    this.timeout = setTimeout(function() { th.prevT = t; th.timeout=null; th.onchange(text) }, wait);
  },
  
  onchange: function(text, force) {
    var q = this.clean(text);
    if (q != this.prevQ && q != "") {
      this.prevQ = q;
      var th = this;
      for(var i=0;i<this.elms.length;i++){
	if(this.elms[i].innerText.toLowerCase().indexOf(q)>-1){
		this.elms[i].style.display="block";
	}else{
		this.elms[i].style.display="none";	
	}
      }      
    }else if(q == ""){
      for(var i=0;i<this.elms.length;i++){
		this.elms[i].style.display="block";
      }      
    }
 
  },
  
  clean: function(text) {
    var spl = text.split(/[\s~!@#&$%^*()\[\]{}:\"<>?`=;\',\.\/\\|\-]+/i);
    var words = [];
    for (var i=0; i<spl.length; i++) if (!spl[i].match(/^[a-z -ï_0-9]{0,2}$/)) 
      words[words.length] = spl[i].toLowerCase();
    return words.join(" ");
  }
};


