var DependentReference = new Class
(
	{
		initialize: function(elementId, options)
		{
			this.element = $(elementId);
			this.targetElement = $(this.element.getProperty('rel'));
			this.first = true;
			
			this.childrenBackup = this.element.getChildren().clone();
			
			if($defined(this.targetElement))
			{
				
				this.targetElement.addEvent('change', this.rebuildList.bind(this));
				this.rebuildList();
			}
		},
		
		rebuildList: function()
		{
			if(this.first)
			{
				selectedIndex = this.element[this.element.selectedIndex].value;
				this.first = false;
			}
			else
				selectedIndex = 0;
		
			newIndex = 0;
			this.element.empty();
		
			i = 0;
		
			this.childrenBackup.each(function (option) {
				if(option.getTag() == 'option')
				{
					if(option.value > 0)
					{
						if(option.getProperty('rel') == this.targetElement.getValue())
						{
							this.element.adopt(option.clone());
							
							if(selectedIndex == option.value)
							{
								newIndex = i;
							}
							i++;
						}
					}
					else
					{
						this.element.adopt(option.clone());
						i++;
					}
				}
			}.bind(this));
			
			this.element.selectedIndex = newIndex;
			this.element.fireEvent('change', this.element);
		}
	}
);


window.addEvent('domready', function() {
	$$('.dependentReference').each(function(element)
	{
		
		new DependentReference(element.id,null);
	}
	);
});

