/*
---
description: 
Parent-child select elements. 
If parent has no predefined children then an input is displayed

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, input, options) 
	{
		// child is id of the second select (regions dropdown)
		// input is the id of a textbox which will be displayed for regions that are not predefined
		
		this.setOptions(options);
		
		var self = this,
			offset = self.options['child-offset'],
			child = $(child),
			input = $(input),
			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;
		self.input = input;
	},
	
	'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,
			input = self.input;
			
		while(child.options.length > offset) {
			$(child.options[offset]).destroy();
		}
		
		child.selectedIndex = 0;
			
		for (var i = 0; i < ghost.options.length; i++) {
			var option = $(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', '');
			child.setStyle('display', 'inline');
			input.setStyle('display', 'none');
		}
		else {
			//child.set('disabled', 'disabled');
			child.setStyle('display', 'none');
			input.setStyle('display', 'inline');
		}
		
	}
});