/**
 * @author Robert
 
 watch another element for changes to its value, and send an ajax call to update
 this elements values 
 */
 
 var fbCascadingdropdown = FbElement.extend({
	initialize: function(element, options) {
		var o = null;
		this.plugin = 'cascadingdropdown';
		this.setOptions(element, options);
		if($(this.options.watch)){
			$(this.options.watch).addEvent('change', this.watch.bindAsEventListener(this));
		}
	},
	
	watch: function(e)
	{
		e = new Event(e);
		this.element.getParent().getElement('.loader').setStyle('display', '');
		var v = $(e.target).getValue();
		var url = this.options.liveSite + 'index.php?option=com_fabrik&format=raw&Itemid=' + this.options.Itemid + '&controller=plugin&task=pluginAjax&plugin=fabrikcascadingdropdown&method=ajax_getOptions&element_id=' + this.options.id;
		var myAjax = new Ajax(url, { method:'post', 
		'data':{'v':v, 'formid':this.form.id, 'fabrik_cascade_ajax_update':1},
		onComplete: function(json){
			this.element.getParent().getElement('.loader').setStyle('display', 'none');
			json = Json.evaluate(json);
			this.element.empty();
			json.each(function(item){
				o = new Element('option', {'value':item.value}).appendText(item.text).injectInside(this.element);
			}.bind(this));
			// $$$ hugh - need to remove/add 'readonly' class ???  Probably need to add/remove the readonly="readonly" attribute as well
			//this.element.disabled = (this.element.options.length == 1 ? true : false);
			if (this.element.options.length == 1) {
				this.element.disabled = true;
				this.element.addClass('readonly');
			}
			else {
				this.element.disabled = false;
				this.element.removeClass('readonly');
			}
		}.bind(this)}).request();
	},
	
	cloned: function(c){
	//c is the repeat group count
	
	if($(this.options.watch)){
		this.options.watch = this.options.watch + '_' + c;
		if($(this.options.watch)){
			$(this.options.watch).removeEvents();
			$(this.options.watch).addEvent('change', this.watch.bindAsEventListener(this));
		}
	}
		
	}
});
