var xmlHttp;
var tpt; 

function ajax_removeAllOptions(selectbox) {
	var i;
	for(i=selectbox.options.length-1;i>=0;i--) {
		selectbox.remove(i);
	}
}
function ajax_addOption(selectbox, value, text, index) {
	selectbox.options[index] = new Option(text, value);
}

function Request(listingstatus, estabname) { 
	xmlHttp=GetXmlHttpObject();
	
	if (xmlHttp==null) {
		alert ("Your browser does not support AJAX - Please use the Advanced Search!");
		return;
	} 
	
	tpt = estabname;
	var url="ajaxsearch.php?" + "listingstatus=" + listingstatus ;

	xmlHttp.onreadystatechange=stateChanged
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
	
}

function stateChanged() { 
	ajax_removeAllOptions(document.ajaxsearch.elements['area[]']);
	ajax_addOption(document.estabsearch.elements['refnum'], "", "Select An Establishment", 0);
	
	if (xmlHttp.readyState==4) { 
	
		data = xmlHttp.responseText.split("^");
	
		for (i=0; i<data.length; i++) {
			elementoptions = data[i].split("!");
			for (n=0; n<elementoptions.length; n++) {
				theoption = elementoptions[n].split("~");
				
				if(i==0) {
					ajax_addOption(document.estabsearch.elements['refnum'], theoption[0], theoption[1], n+1);
					if(tpt==theoption[0]) {
						
                        document.estabsearch.elements['refnum'].selectedIndex = n+1;
                    }
				} else {
					theoptiontype = theoption[0].split("|");
					(theoptiontype[0] == "suburb") ? fmted_area = "\ \ " + theoption[1] : fmted_area = theoption[1];
					ajax_addOption(document.ajaxsearch.elements['area[]'], theoption[0], fmted_area, n);
				}
			}
		}
	}
}

function GetXmlHttpObject() {
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
	return xmlHttp;
}

