

Autocompleter.Suburb = Class.create(Ajax.Autocompleter, {
  initialize: function($super, element, update, msg, url, options) {	
	$super(element, update, url, options);	
	this.validationMsgArea = $(msg);
	this.options.afterUpdateElement = this.suburbSelected;
	this.options._hasSelectedOption = false;
	Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
	Event.observe(this.element, 'change', this.onChange.bindAsEventListener(this));
  },

  onBlur: function(event) {
	  setTimeout(this.validateValue.bind(this), 350);
  }, 
  
  onChange: function(event) {
	  this.options._hasSelectedOption = false;
	  this.removeClassName('suburb_error');
  }, 

  suburbSelected : function(element, selectedOption) {
      this._hasSelectedOption = true; 
  },
  
  validateValue: function() {
	  if (this.element.value == "") {
		  this.element.removeClassName('suburb_error');
		  this.validationMsgArea.update("");
		  
	  } else if ((!this.options._hasSelectedOption) && (!this.isSuburbValid())) {
		  var errormsg = "What you've entered is incomplete. Read the instructions above and either select from the list or click 'Search'.";
		  if (this.isPostcode()) {
			  errormsg = "What you've entered is incomplete. Read the instructions above and either select from the list or click 'Search'.";
		  }
		  this.validationMsgArea.update(errormsg);
		  this.element.addClassName('suburb_error');
	  } else {
		  this.element.removeClassName('suburb_error');
		  this.validationMsgArea.update("");
	  }
  },
  
  isSuburbValid: function() {
	  var re = new RegExp(/(.)+,\s[0-9]{4}/);
	  var value = this.element.value;
	  return value.match(re);
  },
  
  isPostcode: function() {
	  var re = new RegExp(/[0-9]{4}/);
	  var value = this.element.value;
	  return value.match(re);
  }

});