SizeConverter = function() {
	return {
		init: function() {
			this.unitField = Ext.getDom('size-converter-unit');
			Ext.EventManager.addListener(this.unitField, 'change', this.onUnitChange, this);
			this.sizeField = Ext.getDom('size-converter-sizes');
			Ext.EventManager.addListener(this.sizeField, 'change', this.onSizeChange, this);
			this.extraField = Ext.getDom('size-converter-extra');
			Ext.EventManager.addListener(this.extraField, 'change', this.onSizeChange, this);
			this.resultEl = Ext.get('size-converter-result');
		},
		onUnitChange: function() {
			var unit = this.unitField.value;
			this.clearSizes();
  		this.resultEl.update('');
			if (unit) {
				var factor = unit == 'cm' ? 1 : 0.3937;
				var unitName = unit == 'cm' ? 'cm' : 'inches';
		  	var sizes = SizesConfig;
		  	for (var size in sizes) {
	  			this.addOption(this.sizeField, size, (Math.round(size*factor*10)/10) + ' ' + unitName);
	  		}
				if (unit == 'cm') {
					for (var extra = 0; extra <= 2; extra += 0.5) {
						this.addOption(this.extraField, extra, extra + ' ' + unitName);
					}
				} else {
					for (var extra = 0; extra <= 1; extra += 0.25) {
						this.addOption(this.extraField, Math.round(extra * factor * 10)/10, extra + ' ' + unitName);
					}
				}
	  	}
		},
		addOption: function(field, value, text) {
			var option = document.createElement('option');
			option.text = text;
			option.value = value;
			try {
				field.add(option, null);
			} catch (e) {
				field.add(option);
			}
		},
		clearSizes: function() {
			while (this.sizeField.options.length > 0) {
				this.sizeField.remove(0);
			}
			this.addOption(this.sizeField, '', 'Select length');
			while (this.extraField.options.length > 0) {
				this.extraField.remove(0);
			}
			this.addOption(this.extraField, '', 'Select extra space');
		},
		onSizeChange: function() {
			var size = this.sizeField.value;
			var extra = this.extraField.value;
			var html = '';
			if (size && extra) {
				var rdSize = null;
				size = size*1+extra*1;
				for (var s in SizesConfig) {
					if (s >= size) {
						rdSize = SizesConfig[s];
						break;
					}
				}
				if (rdSize) html = '<b>Your Rubber Duck size is:</b> <span style="font-size: 15px;">' + rdSize + '</span>';
			}
  		this.resultEl.update(html);
		}
	}
}();
Ext.onReady(SizeConverter.init, SizeConverter);

