var settings_cache = {}

// настройка телефонов
$(function() {
	var vendors = $("select#id-vendor");
	var models  = $("select#id-model");
	var types   = $("select#id-type");

	var params = {
		'regid' : $("input[name='regid']").val()
	};

	var updateSelect = function(data, sel) {
		sel.empty();
		sel.append($("<option>").attr("value", "0").html("-- выберите --"));

		var counter = 0;

		for(i in data) {
			sel.append($("<option>").attr("value", i).html(i));
			counter++;
		}

		var isType = sel.attr("id") == 'id-type';
		sel.attr("multiple", isType && counter > 1 ? "multiple" : "");

		if (isType && counter <= 1) {
			try {
				sel.children().filter(function() { return $(this).val() != '0' }).first().attr("selected", "selected");
			} catch(e) {
			}
		}

		sel.attr("disabled", "");
	};

	var loadData = function(type, value, waitUpdateName, waitUpdate) {
		if(type == 'vendor' && params['model']) {
			params['model'] = null;
		}
		
		if(type == 'model' && params['type']) {
			params['type'] = null;
		}

		params[type] = value;

		if(value == '0') {
			return;
		}

		var no_a = false;

		if(settings_cache[waitUpdateName]) {
			if(settings_cache[waitUpdateName][value]) {
				updateSelect(settings_cache[waitUpdateName][value], waitUpdate);
				no_a = true;
			}
		}

		if(!no_a) {
			$.getJSON('/phones.settings.json', params, function(data) {
				if (params['vendor']) {
					if(!settings_cache['model']) settings_cache['model'] = {};
					settings_cache['model'][params['vendor']] = data['model'];
				}

				if(params['model']) {
					if(!settings_cache['type']) settings_cache['type'] = {};
					settings_cache['type'][params['model']] = data['type']
				}

				updateSelect(data[waitUpdateName], waitUpdate);
			});
		}
	};

	vendors.change(function() {
		types.empty();
		types.attr("disabled", "disabled");
		types.attr("multiple", "");
		types.append($("<option>").attr("value", "0").html("-- выберите --"));

		loadData("vendor", $(this).find("option:selected").val(), "model", models);
	});

	models.change(function() {
		loadData("model", $(this).find("option:selected").val(), "type", types);
	});
});


