/*
We provide a third input box, if the browser supports it
*/

var urlopener = null;
if (document.getElementsByTagName) {
    /* we need to read remote files */
    try {
	/* IE */
	urlopener = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
	/* Mozilla */
	try {
		urlopener = new XMLHttpRequest();
	} catch (e) {
		// a browser that doesn't support XML requests
		urlopener = null;
	}
    }
}

if (urlopener) {
    // create a new input, in a div
    var select = document.createElement('select');
    select.name = 'town';
    select.style.position = 'absolute';
    select.style.left = '10%';
    select.style.width = '25ex';
    var option = document.createElement('option');
    option.appendChild(document.createTextNode('All towns'));
    option.value = '*';
    select.appendChild(option);
    var div = document.createElement('div');
    div.style.marginBottom = '1em';
    div.appendChild(document.createTextNode('Town:'));
    div.appendChild(select)
    document.query.insertBefore(div,document.query.submit);
    // now set an event handler for changes to the county
    document.query.county.onchange = countyChange;
    // the user may have used the back button
    if (document.query.county.options[document.query.county.selectedIndex].value != '*') {
	document.query.county.onchange();
    }
}

function countyChange() {
    // the county has changed. Update the towns select
    var county = this[this.selectedIndex].value;
    // get the select
    var select = document.query.town;
    if (!select) {
        select = document.query.elements[2];
    }
    if (county && county != '*') {
        var url = '/service_finder/towns.py?county=' + county;
        urlopener.open('GET',url,false);
        urlopener.send('');
        towns = urlopener.responseXML.getElementsByTagName('town');
        select.options.length = 1;
        for (i = 0; i < towns.length; i++) {
            var option = document.createElement('option');
            option.text = option.value = towns.item(i).firstChild.nodeValue;
            //append after the first ("All towns") entry.
            select.options[i + 1] = option;
        }
    }
}
