var OnstuimigSuggest = Class.create();
OnstuimigSuggest.prototype = {

 initialize: function(inputBox, results, header) {

  this.form = $(inputBox.form);
  this.inputBox = $(inputBox);
  this.selectBox = $('onstuimigSuggestVakgebied');
  this.results = results;
  this.url = this.form.action;
  this.method = this.form.method;
  this.stopSubmit = true;
  this.searchString = this.inputBox.value;
  this.starterText = this.searchString;
  this.searchingMessage = 'Zoeken...';
  this.minLength = 2;
  this.timeoutID = 0;
  this.delay = 250;
  this.vakgebied = this.selectBox.getValue();
  this.header = $(header);
  this.header.style.display = 'none';
  
  this.form.addEvent('submit', this.submit.bind(this));
  this.inputBox.addEvent('keyup', this.update.bind(this));
  this.inputBox.addEvent('focus', this.handleStarterText.bind(this));
  this.inputBox.addEvent('blur', this.handleStarterText.bind(this));
  
	this.selectBox.addEvent('change', this.update.bind(this));
  
	var temp = Cookie.get("query");
	if(temp){
		this.inputBox.value = temp;
		this.update();
	}
 },

 handleStarterText: function(event) {

  switch(event.type) {
   case 'focus':
    if(this.inputBox.value == this.starterText) {
     this.inputBox.value = '';
    }
    break;
   
   case 'blur':
    if(this.inputBox.value == '') {
     this.inputBox.value = this.starterText;
    }
    break;

  }
  
 },

 update: function() {
 		
  if(this.searchString != this.inputBox.value && this.inputBox.value != this.starterText || this.vakgebied != this.selectBox.getValue()) {
		Cookie.set("query", this.inputBox.value);
   this.searchString = this.inputBox.value;
   this.vakgebied = this.selectBox.getValue();
   clearTimeout(this.timeoutID);
   //if(this.searchString.length >= this.minLength || this.vakgebied != this.selectBox.getValue() ) {
   	this.header.style.display = 'block';
   	
    this.results.innerHTML = this.searchingMessage;
    this.timeoutID = setTimeout(this.search.bind(this), this.delay);
    
   //} else {
   // this.results.innerHTML = '';
   // this.header.style.display = 'none';
   //}
   
  }
  
 },
 

 
 parseSelected: function(result){
 	var object = this.options.obj;
 	/*var values = result.test(, "ig");
 	values.forEach(function(val){
	});
	result = result.replace(object.searchString, "<b>" + object.searchString + "</b>")
	//result = result.replace(object.searchString, "" + object.searchString + "")
	*/
	 	
 	var regEx = new RegExp (object.searchString, 'gi') ;

  result = result.replace(regEx, function(match){
		//return "<b>" + match + "</b>";
		return "" + match + "";
		});
	 	
 	object.results.innerHTML = result;
 },
 
 search: function() {
  new Ajax(this.url, { method: this.method, onComplete:this.parseSelected, postBody:this.form, obj:this }).request(); //update:this.results
 },

 submit: function(event) {
  if(this.stopSubmit) { return false; }
 }

};

