var LocationSelector = $.inherit({
	cache: {},
	url: null,
	urlBase: '/dircon/geo/load_cities',
	primE: null,
	secEId: null,
	secE: null,
	axajIndicator: false,
	
	__constructor: function(primEId, secEId, ot_id, attr_id){
		$('#'+primEId).change(function(e){
			e.currentTarget.geo_location_selector.refreshSecondary(e.currentTarget.value);
		});
		
		if(secEId){
			this.secE = $('#' + secEId);
			if(!this.secE.length){
				this.secE = false;
			}
		}

		this.secEId = secEId;
		this.url = new Url(this.urlBase);
		this.url.setParams({ot_id: ot_id, attr_id: attr_id});
	},

	refreshSecondary: function(primValue){
		if(primValue in this.cache){
			this.makeCities(primValue);
			return;
		}

		this.url.setParam('iid', primValue);
		this.createRequestIndicator();
		$.ajax({
			url: this.url,
			dataType: 'json',
			context: this,
			success: function(data, textStatus, XMLHttpRequest){
				//alert(data.result)
				if(data.result){
					this.cache[primValue] = data.data;
				}else if(!(primValue in this.cache)){
					this.cache[primValue] = {};
				}
				this.makeCities(primValue);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				return;
			},
			complete: function(XMLHttpRequest, textStatus){
				this.removeRequestIndicator();
			}
		});
	},

	makeCities: function(primValue){
		if(!this.secE) return false;

		this.secE.children('.geo-location-value').remove();
		
		if($.isEmptyObject(this.cache[primValue])){
			return;			
		}

		var primSet = this.cache[primValue];
		for(var city_index in primSet){
			if(primSet[city_index].pred_id){
				$('<option>')
				.attr({value: primSet[city_index].pred_id})
				.text(primSet[city_index].ru)
				.addClass('geo-location-value')
				.appendTo(this.secE);
			}
		}
	},
	createRequestIndicator: function(){
		if(!this.secE || this.ajaxIndicator) return false;
		this.ajaxIndicator = $('<img src="/images/ajax/ajax-loader.gif">').insertAfter(this.secE);
	},
	removeRequestIndicator: function(){
		if(this.ajaxIndicator){
			this.ajaxIndicator.remove();
			this.ajaxIndicator = false;
		}
	}
});

