/*
---
description: Parent-child select elements.

license: MIT-style

authors:
- Christopher Pitt
- Arieh Glazer

requires:
- core/1.2.4: Class.Extras
- core/1.2.4: Element

provides: [LinkedSelect]

...
*/

var LinkedSelect = new Class({
	'Implements': [Options],
	'options': {
		'parent-attribute': 'data-parent',
		'child-attribute': 'value',
		'child-offset': 1
	},
	'initialize': function(child, options) {
		this.setOptions(options);
		
		var self = this,
			offset = self.options['child-offset'],
			child = document.id(child),
			ghost = new Element('select', {
				'styles': {
					'display': 'none'
				}
			}).inject(document.body);
		
		while(child.options.length > offset) {
			ghost.adopt(child.options[offset]);
		}
		
		self.child = child;
		self.ghost = ghost;
	},
	'filter': function(value, selected) {
		
		var self = this,
			parentattr = self.options['parent-attribute'],
			childattr = self.options['child-attribute'],
			offset = self.options['child-offset'],
			child = self.child,
			ghost = self.ghost;
			
		while(child.options.length > offset) {
			document.id(child.options[offset]).destroy();
		}
		
		child.selectedIndex = 0;
			
		for (var i = 0; i < ghost.options.length; i++) {
			var option = document.id(ghost.options[i]).clone();
			
			if (option.get(parentattr) == value) {
				child.adopt(option.set('selected', ''));
			}
			
			if (option.get(childattr) == selected) {
				option.set('selected', 'selected');
			}
		}
		
		if (child.options.length > offset) {
			child.set('disabled', '');
		}
		else {
			child.set('disabled', 'disabled');
		}
		
	}
});