var Widget = new Class({
	
	Implements: [Options, Events],
	
	options: {
	},
	
	initialize: function(){
	}
	
});

Widget.AdvSelect = new Class({
	
	Implements: [Options, Events],
	
	options: {
		label: {
			'tag': 'span',
			'className': 'swLabel'
		},
		cont: {
			'tag': 'div',
			'className': 'swCont'
		},
		labelLimit: 13
	},
	
	initialize: function(widgets, options){
		this.widgets = widgets;
		this.setOptions(options);
		this.label = [];
		
		// no custom Widgets for IE
		if (!Browser.Engine.trident) this.checkWidgets();
	},
	
	checkWidgets: function(){
		this.widgets.each(this.prepare, this);
	},
	
	prepare: function(widget, index){
		
		widget.set('styles', {
			'opacity': 0.01
		});
		
		this.label[index] = new Element(this.options.label.tag, {
			'text': widget.getSelected().get('text'),
			'class': this.options.label.className
		});
		
		new Element(this.options.cont.tag, {
			'class': this.options.cont.className
		}).wraps(widget).adopt(this.label[index]);
		
		this.attachListener(widget, index);
		
		widget.fireEvent('change');
	},
	
	attachListener: function(widget, index){
		widget.addEvents({
			change: function(){
				var limitMode = widget.get('class').split(/(\[|\])/);
				
				if (limitMode.length > 1){
					limitMode = limitMode[limitMode.indexOf('[') + 1];
				} else {
					limitMode = null;
				}

				var newLabel = widget.getSelected().pop().get('text');
				newLabel = (newLabel.length > $pick(limitMode, this.options.labelLimit) ? newLabel.substring(0, $pick(limitMode, this.options.labelLimit)) + '...' : newLabel);
				this.label[index].set('text', newLabel);
			}.bind(this)
		});
	},
	
	update: function(widget, newOption){
		widget.getElements('option').each(function(option){
			option.selected = false;
			
			if (option.hasClass('newOption')){
				option.destroy();
			}
		});
		
		var newOption = new Element('option', {
			'text': newOption.text,
			'value': newOption.value,
			'class': 'newOption'
		}).inject(widget);
		
		newOption.selected = true;
		
		widget.fireEvent('change');
	},
	
	replace: function(widget, newOption){
		this.update(widget, newOption);
	}
	
});
