// Example usage
// Make sure /jslib/mootools/mootools.js is included!
/*

// EXAMPLE GLOBAL DATASERVICE
window.addEvent('domready', function()
{
	var oDomainSelect = new ParentChildSelect('iParentElementID', 'iChildElementID', {'type':'getSubDomainsByDomain', 'iChildSelectedValue':1} );
});

// EXAMPLE EIGEN DATASERVICE
window.addEvent('domready', function()
{
	var oDomainSelect = new ParentChildSelect('iParentElementID', 'iChildElementID', {'type':'getSubDomainsByDomain', 'iChildSelectedValue':1, 'sDataservice':'dataservice.php'} );
});
*/

var ParentChildSelect = new Class({
	
	Implements: [Events, Options],
	
	options: {
		sDataservice : '/phplib/form_controls/parentchildselect.php',
		sFirstOption : ''
	},
	
	initialize: function(vParentElement, vChildElement, options)
	{
		this.setOptions(options);
		this.oParentSelect = $(vParentElement);
		
		this.oChildSelect  = $(vChildElement);
		if (this.oChildSelect != null) //Check if child dropdown exists
		{
			this.oChildSelect.disabled = true;
			// Initially fill childselector?
			if (((typeof(this.options.iChildSelectedValue) != 'undefined' && this.options.iChildSelectedValue > 0) 
			    || this.oParentSelect.value > 0) && !this.oParentSelect.disabled) 
			{		
				this._fillChildSelect();
			}
			
			// onchange fill childselector
			this.oParentSelect.addEvent('change', function()
			{			
				this._fillChildSelect();
			}.bind(this));
		}
	},

	_addOptions: function(aOptions)
	{
		var i = 0;
		if (this.options.sFirstOption != '')
		{
			this.oChildSelect.options[i] = new Option(this.options.sFirstOption, -1); //Add first option			
			i++;
		}
		//Loop trough options collection
		aOptions.each(function(oOption) 
		{ 
			this.oChildSelect.options[i] = new Option(oOption.text, oOption.value); //Add option to child dropdown			
			
			oSelectOption = $(this.oChildSelect.options[i]);
			if (oOption.classname)
			{
				oSelectOption.addClass(oOption.classname);
			}
			
			if (typeof(oOption.selected) != 'undefined' && oOption.selected == 1)
			{				
				oSelectOption.selected = true;
			}
						
			i++;
		}.bind(this));
	},
	
	_fillChildSelect: function()
	{		
		var iParentKey = this.oParentSelect.value;
		this.options.iParentKey = this.oParentSelect.value;
		var oRequest = new Request.JSON({url: this.options.sDataservice, 
			onSuccess: function(oJson) 
			{
				if (oJson.error && oJson.error.length > 0) 
				{
					alert(oJson.error);
				}
				else if (oJson.options) 
				{
					this.oChildSelect.disabled = false;
					this.oChildSelect.options.length = 0;
					this._addOptions(oJson.options);
				}
			}.bind(this)
		}).send('data='+JSON.encode(this.options));
		
		//oRequest.setHeader('Content-type', 'application/x-www-form-urlencoded');
	}	
});