var x_country = null;
var x_region = null;
var x_city = null;
var x_metro = null;
var regions = [];
var cities = [];
var metro = [];

function qLocation (f, sess_name, sess_id)
{
	var app_country = 1;
	var app_region = 2;
	var app_city = 3;
	var id = f.options[f.selectedIndex].value;
	var cCountry = x_country.options[x_country.selectedIndex].value;
	var cRegion = x_region.options[x_region.selectedIndex].value;
    if(x_city) var cCity = x_city.options[x_city.selectedIndex].value; else var cCity = 0;

	switch (f.name)
	{
		case 'country_id': app = app_country; break;
		case 'region_id': app = app_region; break;
		case 'city_id': app = app_city; break;
		default: return;
	}

	function xLoc (app)
	{
		if (app == app_country && x_region) cRegion = setList(app, x_region, regions[cCountry]);
		if ((app == app_region || app == app_country) && x_city) cCity = setList(app, x_city, cities[cRegion]);
		if (app <= app_city && x_metro) setList(app, x_metro, metro[cCity]);
	}

	function setList (app, x_field, x_arr)
	{
		x_field.length = 1;
		
		if (!x_arr || x_arr.length == 0)
		{
			x_field.disabled = true;
			return;
		}
		
		for (i = 0; i < x_arr.length; i ++)
		{
			var split_array = x_arr[i].split(':');
			var oid = split_array[0];
			var ocnt = split_array[1];

			x_field.options[i+1] = new Option(ocnt, oid);
		}
		
		x_field.selectedIndex = 0;
		x_field.disabled = false;
		
		return x_field.options[1].value;
	}

	if (id == 0)
	{
		if (app == app_country && x_region) {x_region.disabled = true; x_region.selectedIndex = 0;}
		if ((app == app_region || app == app_country) && x_city) {x_city.disabled = true; x_city.selectedIndex = 0;}
		if (app <= app_city && x_metro) {x_metro.disabled = true; x_metro.selectedIndex = 0;}
	}
	else if ((app == app_country && !regions[id]) || (app == app_region && !cities[id]) || (app == app_city && !metro[id]))
	{
		$.get('/sys/php/h/location.php?'+sess_name+"="+sess_id, {'app': app, 'id': id, 'mt':(x_metro ? 1 : 0)},
			function(rt) {
				eval(rt);
				xLoc(app);
			}
		);
	}
	else
	{
		if (app == app_country) cCountry = id;
		if (app == app_region) cRegion = id;
		if (app == app_city) cCity = id;
		xLoc(app);
	}
}
