(function(){

var selectCity;

$(function(){
	$('select.geo-city').change(function(){
		var elm = $(this);
		if (elm.val() == 0) {
			selectCity.open(elm);
			elm[0].selectedIndex = 0;
		}
	});

});


// selectCity
(function(){
	var inited = false,
		path,
		win, btnOk, btnCancel,
		select,
		city, country, region;

	var self = selectCity = {
		open: function(_select)
		{
			init();
			select = _select;
			voile.open(win);
		},
		close: function()
		{
			voile.close();
		}
	};

	function init()
	{
		if (inited) return;
		inited = true;

		path = document.getElementsByTagName('script')[0].src.split('/');
		path.pop();
		path.pop();
		path = path.join('/');

		win = $('<div id="geo-window">');
		win.html([
			'<h3>Выберите город</h3>',
			'<form>',
				'<div class="field">',
					'<label>Страна</label>',
					'<select name="country_id"></select>',
				'</div>',
				'<div class="field">',
					'<label>Регион</label>',
					'<select name="region_id"></select>',
				'</div>',
				'<div class="field">',
					'<label>Город</label>',
					'<select name="city_id"></select>',
				'</div>',
				'<div class="buttons">',
					'<button class="ok" type="button" disabled="disabled">Выбрать</button>',
					'<button class="cancel" type="button">Отмена</button>',
				'</div>',
			'</form>'
		].join(''));

		btnOk = $('button.ok', win).click(function(){
			setValue(city.val());
			self.close();
		});
		btnCancel = $('button.cancel', win).click(function(){
			self.close();
		});

		country = $('select[name="country_id"]', win).change(function(){
			load('/geo/regions/id/' + country.val(), region);
		});
		region = $('select[name="region_id"]', win).disable().change(function(){
			load('/geo/cities/id/' + region.val(), city);
		});
		city = $('select[name="city_id"]', win).disable().change(function(){
			btnOk.enable();
		});

		load('/geo/countries', country);
	}

	function setValue(id)
	{
		select.val(id);
		if (select.val() == id) return;
		select.loading(true);
		$.getJSON(path+'/geo/city/id/'+id, function(data) {
			select.prepend('<option value="' + data.id + '">' + data.location_name + '</option>');
			select.val(data.id);
			select.loading(false);
		});
	}

	function load(url, select)
	{
		select.loading(true);
		select.empty();
		$.getJSON(path+url, function(data) {
			var options = [];
			for (var i in data) {
				options.push('<option value="', i, '">', data[i], '</option>');
			}
			select.append(options.join(''));
			select.loading(false);
			select.change();
		});
	}
})();


})();