/*
Copyright (c) 2006 eSpeakers.com
*/



//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest(); //Not IE
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP"); //IE
	} else {
		//Display your error message here.
		//and inform the user they might want to upgrade
		//their browser.
		alert("Some features on this page require a newer web browser than you are using. Try our favorite: Firefox, free at http://www.getfirefox.com");
	}
}



//a reqObj needs to have been created and passed in as the last parameter
function populateSelect(url, lookupvalue, selectedvalue, pSelect, receiveReq){
	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
		//receiveReq.onreadystatechange = handleReceiveSelect(receiveReq, pSelect, selectedvalue); 
		receiveReq.open("GET", url+"?lookupvalue="+lookupvalue+"&hash=" + Math.random(), false);
		receiveReq.send(null);
		handleReceiveSelect(receiveReq, pSelect, selectedvalue);
	} else {
		//alert('busy')
	}
}


function handleReceiveSelect(receiveReq, pSelect, selectedvalue) {
	//Check to see if the XmlHttpRequests state is finished.
	if (receiveReq.readyState == 4 && receiveReq.status == 200) {
		//Set the contents of our select to the result of the asyncronous call.
		if (pSelect){
			xml = receiveReq.responseXML;
			
			//clear out old options
			var i;
			for (i = pSelect.length - 1; i>=0; i--) {
				pSelect.remove(i);
			}
			pSelect.length = 0;
			
			//add the new
			var l_Count = xml.getElementsByTagName('option').length;
			for(var i=0;i<l_Count;i++){
				var l_Opt_Xml = xml.getElementsByTagName('option')[i];
				appendToSelect(pSelect, l_Opt_Xml.getAttribute('value'), l_Opt_Xml.firstChild.nodeValue, selectedvalue)
			}
		}
	}
}


function appendToSelect(pSelect, pValue, pContent, selectedvalue) {
	var l_Opt = document.createElement("option");
	l_Opt.value = pValue;
	
	if(document.all){/* for ie */
		pSelect.options.add(l_Opt);
		l_Opt.innerText = pContent;
	}else{
		l_Opt.appendChild(document.createTextNode(pContent));
		pSelect.appendChild(l_Opt);
	}
	if (pValue == selectedvalue) {
		pSelect.selectedIndex = (pSelect.length - 1);
	}

}

/**
 * Same as above, but adds it as the first element in the list rather than the last.
 * 
 * @param pSelect
 * @param pValue
 * @param pContent
 * @param selectedvalue
 * @return
 */
function prependToSelect(pSelect, pValue, pContent, selectedvalue) {
	var optionToInsert = new Option(pContent, pValue);
	pSelect.insertBefore(optionToInsert,pSelect[0]);
	
	if (pValue == selectedvalue) {
		pSelect.selectedIndex = 0;
	}

	//pSelect.options[pSelect.options.length] = optionToInsert;
}

