// JavaScript Document

var sfsIndex       = new Object;
sfsIndex.populated = false;

/*
Typing a name into the suburb entry field will scroll the suburb select
field to a matching suburb name (if any).
*/
function sfsComplete () {
	if (!document.getElementById) return;
	var text   = document.getElementById('tb');
	var select = document.getElementById('u');

	if (!sfsIndex.populated) sfsBuildIndex();
	var suburb = text.value.match(/,*([^,]+)$/);

	if (suburb) {
		var name = suburb[1].toUpperCase().replace(/^\s*/, '').replace(/\s*$/, '');
		for (var i = sfsIndex[name.charAt(0)]; i < select.options.length; i++) {
			if (select.options[i].text.toUpperCase().indexOf(name) == 0) {
				select.selectedIndex = i;
				break;
			}
			else {
				select.selectedIndex = -1;
			}
		}
	}
}

 /*
 On click event for the suburb select box. When clicked it populates
 the suburb entry field then deselects the clicked suburb. Focus is
 returned to the suburb entry field.
 */
 function sfsInsert () {
	if (!document.getElementById) return false;

	var text    = document.getElementById('tb');
	var select  = document.getElementById('u');

	// An IE bug means we need another event before select.selectedIndex
	// will update from -1. Since we need to swap the focus anyway we'll
	// do it before we look at what was clicked in the select box.
	text.focus();
	var suburb = select.options[select.selectedIndex];
 
	// short circuit on 'show all suburbs'
	if (select.selectedIndex == 0) {
		text.value = '';
		return true;
	}
  
	// see if the selected suburb is in the list already
	var textSuburbs = text.value.split(/\s*,\s*/);
	if (!textSuburbs) return false;

	var pattern = new RegExp('\s*' + suburb.text + '\s*$');
	for (var i = 0; i < textSuburbs.length; i++) {
		// if it's in the list don't do anything
		if (pattern.exec(textSuburbs[i])) return false;
	}

	// its not in the list so lets add it replacing any incomplete words
	var newvalue = text.value.replace(/(^|,)([^,]*)$/,"$1 " + suburb.text + ', ');
	text.value = newvalue;
	return false;
 }

 /*
 Builds an index based on the first occurrence of suburb starting with a
 letter. This speeds up the 'for' search of the select because we can
 then skip straight to suburbs starting with that letter.
 */
 function sfsBuildIndex () {
	 if (!document.getElementById) return;
	 var select = document.getElementById('u');

	 for (var i = select.options.length; i--;) {
		 sfsIndex[select.options[i].text.toUpperCase().charAt(0)] = i;
	 }
	 sfsIndex.populated = true;
 }
