var Selects = new Class({
	Implements: [Options, Events],
	options: {
		url: 'index.php',
		method: 'post',
		extraData: ''
	},
	id: 0,
	actual: 0,
	initialize: function(id, opciones)
	{
		this.id = id;
		this.setOptions(opciones)
		this.addJxs();
	},
	
	addJxs: function()
	{
		var selects = $$('#' + this.id + ' select', '#' + this.id + ' input');
		selects.each(function(el, i)
		{
			this.addJx(el, i);
		}.bind(this));
		this.actual = selects.length;
	},
	
	addJx: function(el, i)
	{
		el.addEvent('change', function()
		{
			if(el != null && el != undefined && el.retrieve('estado') != 'ocupado') {
				el.store('estado', 'ocupado');
				var li = el.getParent();
				li.set('id', this.id + '-' + (i + 1));
				
				var id = new Number(li.get('id').replace(this.id + '-', ''));
				var value = el.get('value');
				
				this.removeNexts(id);
				this.fireEvent('change');
				
				if(value != -1)
				{
					var proxId = this.actual + 1;
					var newId = this.id + '-' + (proxId);
					var newLi = new Element('li', {'id': newId });
					newLi.adopt(new Element('img', {'src': 'img/ajax-loader.gif'}));
					$(this.id).adopt(newLi);
					var rqt = new Request.HTML({
						update: newLi,
						url: this.options.url,
						method: this.options.method,
						link: 'cancel',
						data: el.get('name') + '=' + value + this.options.extraData,
						onComplete: function()
						{
							this.addNext();
							el.store('estado', 'desocupado');
						}.bind(this)
					});
					rqt.send();
				}else{
					el.store('estado', 'desocupado');
					this.fireEvent('init');
				}
			}
		}.bind(this));
	},
	
	addNext: function()
	{
		this.actual++;
		var el = $$('#' + this.id + '-' + this.actual + ' select')[0];
		if(el != undefined)
		{
			this.fireEvent('init');
			this.addJx(el, this.actual - 1);
		}else{
			var tt = $$('#' + this.id + '-' + this.actual + ' div.msgerror')[0];
			if(tt == undefined)
			{
				var el = $$('#' + this.id + '-' + (this.actual - 1) + ' select')[0];
				var value = el.get('value');
				this.fireEvent('complete', [value]);
			}else{
				this.fireEvent('init');
			}
		}
	},
	
	removeNexts: function(desde)
	{
		for(var c = desde + 1; c <= this.actual; c++)
			$(this.id + '-' + c).dispose();			
		this.actual = desde;
	}
});
