dojo.declare("AreaLoader", null, {
	elDepends: {
		country: "region",
		region: "city"
	},
	
	connections: [],
	
	ct: null,
	
	countryEl: null,
	regionEl: null,
	cityEl: null,
    
	select_region: 'Все регионы',
	select_city:   'Все населённые пункты',
	
    constructor: function(ct){
    	var tmpEl, k, v;
    	
        this.ct = ct;
        this.countryEl = dojo.query("select[name='country']", this.ct)[0]||null;
        
        if (this.countryEl) {
        	this.connections.push(dojo.connect(this.countryEl, "onchange", this, this.onChange));
        	this.countryEl.originalDisplay = dojo.style(this.countryEl, 'display');
        }
        
        for (k in this.elDepends) {
        	v = this.elDepends[k];
        	tmpEl = dojo.query("select[name='"+ v +"']", this.ct)[0]||null;
        	if (null !== tmpEl) {
        		this[v + 'El'] = tmpEl;
        		this.connections.push(dojo.connect(tmpEl, "onchange", this, this.onChange));
        		tmpEl.originalDisplay = dojo.style(tmpEl, 'display');
        	}
        }
    },
	
    hasHandle: function(select, type, handle) {
    	for (var i = 0; i < this.connections.length; i++) {
    		if (this.connections[2] == type && this.connections[3] == handle) {
    			return true;
    		}
    	}
    	
    	return false;
    },
    
	onChange: function(e) {
		var select  = e.target,
			name	= select.name,
			content = {"__name": name},
			relSelectName;
		
		content[name + "_id"] = select.options[select.selectedIndex].value;
		
		relSelectName = this.elDepends[name]||null;
		if (relSelectName) {
			relSelectName += "El";
			if (this[relSelectName]) {
				this.clearArea(this[relSelectName]);
			}
		}
			
		if (!(!content[name + "_id"] || content[name + "_id"] == "")) {
			dojo.xhrPost({
				url: '/core/list/country/combo/list/' + this.elDepends[name],
				content: content,
				handleAs: 'json',
				sync: false,
				load: dojo.hitch(this, "onLoadList")
			});
		}
	},
	
	onLoadList: function(response, callbackArgs) {
		var records = response.records||null;

		if (null !== records && records.length) {
			var name = callbackArgs.args.content.__name;
			
			var area = this.getNextArea(name);
			
			this.setAreaVisible(area, true);
			this.fillArea(area, records);
		}
	},
	
	clearArea: function(area) {
		if (area) {
			if (area.options && area.options.length > 1) {
				var length = area.options.length - 1;
				for (var i = length; i >= 1; i--) {
					area.remove(i);
				}
			}
			
			var nextArea = this.elDepends[area.name]||null;
			if (nextArea && this[nextArea + "El"]) {
				this.clearArea(this[nextArea + "El"]);
			}
			
			this.setAreaVisible(area, false);
		}
	},
	
	setAreaVisible: function(area, visible) {
		var gd = dojo.style(area, "display");
		var sd = (true === visible) ? area.originalDisplay : "none";
		
		if (gd != sd) {
			dojo.style(area, "display", sd);
		}
	},
	
	fillArea: function(area, records) {
		var option,
			record,
			doc  = dojo.doc,
			type = area.name,
			valueProperty = type + '_id',
			textProperty  = 'name',
			length = records.length;
		
		if (length) {
			//this.setAreaVisible(area, true);
			
			for (var i = 0; i < length; i++) {
				record = records[i];
	
				area.appendChild(doc.createElement("option"));
				
				option = area.options[i + 1];
	
				option.text  = record[textProperty];
				option.value = record[valueProperty];
			}
			
			option = null;
		}
	},
	
	getNextArea: function(name, records) {
		var prevSelect = this[name + "El"],
			name = this.elDepends[name],
			selectPropertyName = name + "El";
		
		if (null === this[selectPropertyName]) {
			var select,
				option,
				afterEl,
				doc = dojo.doc;
			
			this[selectPropertyName] = dojo.query("select[name='" + name + "']", this.ct)[0]||null;
			select = this[selectPropertyName];
			
			if (!select) {
				//Если элемент не существует, создаём его
				select = this[selectPropertyName] = doc.createElement("select");

				afterEl = prevSelect.nextSibling;
				if (afterEl) {
					this.ct.insertBefore(select, afterEl);
				} else {
					this.ct.appendChild(select);
				}
                
                this.onAreaCreate(select);
				
				select.name = name;
				
				//Добавляем первую опцию с предложением выбора
				select.appendChild(doc.createElement("option"));
				option = select.options[0];
				
				option.text  = this["select_" + name];
				option.value = '';
			}
			
			select.originalDisplay = dojo.style(select, 'display');
			
			if (this.elDepends[name] && !this.hasHandle(select, "onchange", this.onChange)) {
				this.connections.push(dojo.connect(select, "onchange", this, this.onChange));
			}
			
			select	= null;
			afterEl = null;
		}
		
		return this[selectPropertyName];
	},
    
    onAreaCreate: function() {}
});

AreaLoader._areas = [];

AreaLoader.init = function() {
	var cts = dojo.query('.area-loader');
	if (cts) {
		cts.forEach(function(ct) {
			AreaLoader._areas.push(new AreaLoader(ct));
		});
	}
}

dojo.addOnLoad(AreaLoader.init);
