var countriesAjaxUrl = LANG_ROOT_PATH + 'AJAX/ContinentCountries.aspx';
var xmlCountries = GetXmlRequestObject();
var countriesDropDown = null;

// gets a reference to the xml request object
function GetXmlRequestObject(){
	var obj = null;
	if(window.XMLHttpRequest){
		obj = new XMLHttpRequest();
	}
	else if(window.ActiveXObject){
		try{ obj = new ActiveXObject('Msxml2.XMLHTTP'); }
		catch(e){
			try{ obj = new ActiveXObject('Microsoft.XMLHTTP'); }
			catch(oc){ obj = null; }
		}
	}
	return obj;
}

var Continents = new Object();
function AddCountry(countryName, countryCode, continent){
	var countries = Continents[continent];
	if(!countries)
		countries = Continents[continent] = new Array();
	
	countries.push({name:countryName, code:countryCode});
}

// make a request to the server
function FetchCountries(elemId, continent){
	if(xmlCountries && xmlCountries.readyState != 0)
		xmlCountries.abort();

	countriesDropDown = GetItemById(elemId);
	
	if(countriesDropDown){
		while(countriesDropDown.options.length > 0)
			countriesDropDown.remove(0);

		if(continent != null && continent.length < 2){
			countriesDropDown.options[0] = new Option(TXT_ANY_COUNTRY, '');
			countriesDropDown.disabled = true;
			return;
		}
	}

	var countries = Continents[continent];
	if(countriesDropDown && countries && countries.length > 0){
		renderCountryDropDown(countriesDropDown, countries);
	}
	else if(countriesDropDown && xmlCountries)
	{
		countriesDropDown.options[0] = new Option(TXT_LOADING, '');
		countriesDropDown.disabled = true;

		var pg = countriesAjaxUrl;
		pg += '?continent=' + continent;
		pg += '&lang=' + LANG_CODE;
		
		xmlCountries.open('GET', pg, true);
		xmlCountries.onreadystatechange = function()
		{
			try
			{
				if(xmlCountries.readyState == 4)
				{
					while(countriesDropDown.options.length > 0)
						countriesDropDown.remove(0);

					if(xmlCountries.responseText)
						eval(xmlCountries.responseText);
					
					countries = Continents[continent];
					renderCountryDropDown(countriesDropDown, countries);
				}
			}
			catch(ex){}
		};
		xmlCountries.send(null);
	}
}

function renderCountryDropDown(countriesDropDown, countries){
	if(countries && countriesDropDown){
		countriesDropDown.options[0] = new Option(TXT_ANY_COUNTRY, '');
		for(var i = 0; i < countries.length; i++){
			var newOpt = new Option(countries[i].name, countries[i].code);
			countriesDropDown.options[countriesDropDown.options.length] = newOpt;
		}
	}

	if(countriesDropDown)
		countriesDropDown.disabled = false;
}

function abortFetchCountries(){
	if(xmlCountries && xmlCountries.readyState != 0){
		xmlCountries.abort();
		xmlCountries = null;
	}
}

function GetItemById(id){
	return (document.all ? document.all[id] : document.getElementById(id));
}