﻿
	// check for scriptacolous libraries
	if(typeof Ajax.Autocompleter == 'undefined') {
		throw("td.library.js requires including script.aculo.us' controls.js library");
	}

	/**
	 * This class extends the original Ajax.Autocompleter provided by
	 * scriptacolous and used in the TechDivision.streetSearchForm by 
	 * adding a option called autoSelect that checks the number of 
	 * found results and if only one result was found it preselects it.
	 * It also overwrites the onComplete method.
	 *
	 * @author Tim Wagner <t.wagnert@techdivision.com>
	 * @see TechDivision.Autocompleter
	 */
	TechDivision.StreetAutocompleter = Class.create(Ajax.Autocompleter, {
	     
	      /**
	       * Constructor to initialize the parent class and to
	       * set the autoSelect option.
	       *
	       * @param element The element this class is bound to
	       * @param hiddenElement The hidden element this class is bound to
	       * @param update The name of destination element
	       * @param url The url to send the AJAX request to
	       * @param options Additional options
	       */
		  initialize: function(element, hiddenElement, update, url, options, ortstext) {
		  		this.baseInitialize(element, update, options);
		  		this.options.asynchronous = true;
		  		this.options.onComplete = this.onComplete.bind(this);
		  		this.options.defaultParams = this.options.parameters || null;
		  		// initialize the custom members
		  		this.url = url;
		  		this.hiddenElement = hiddenElement;
		  		// set the autoSeletect option
		  		this.options.autoSelect = true;
		  		this.ort = ortstext;
		  },
	
		  /**
		   * This is the callback function invoked to handle
		   * the result of the AJAX request sended to load the
		   * data for the suggestion functionality.
		   * 
		   * @param request The AJAX request with the response
		   * @return void
		   */
		  onComplete: function(request) {
			  //No suggestions if the user changed the town search field
			  if(this.ort != document.getElementById('search1').value) {
				  this.hiddenElement.value = '-1';
				  return;
			  }
			  // evaluate the JSON encoded string and initialize the HTML with the suggestions
		  		var json = request.responseText.evalJSON(); 
		  		var html = '<ul>';
		  		// add the search suggestions to the HTML
		  		for(i = 0; i < json.length; i++) {
		  			html += '<li class=\'even\' id="' + json[i].point + '" title="' + json[i].street + '">' + json[i].street + '<br/><small>(' + json[i].postcode + ' ' + json[i].quarter + ')</small></li>';
		  		}
		  		// update the suggestion list
		  		this.updateChoices(html + '</ul>');
		  		// if at least on value is found preset the first one
		  		if(json.length > 0) { 
		  			this.hiddenElement.value = json[0].point;
		  		}
		  }
	});
