var mzAjaxCombo = new Class({

	options: {
		autoComplete:true,
		filters:{},
		loadingString:"loading...",
		onStart: Class.empty,
		onComplete: Class.empty,
		onChange: Class.empty
	}, 

	initialize: function(combo, remoteurl, options) {

		this.setOptions(options);
		this.combo = combo;
		this.combo.addEvent('change',function(){this.fireEvent('onChange')}.bind(this));
		this.remoteurl = remoteurl;
				
		if(this.options.autoComplete) this.refresh();
	},
	
	refresh: function(filters) {
		
		var allfilters=$merge(this.options.filters,filters)
		this.start(allfilters);
		
		var remoteurl = this.remoteurl + ((this.remoteurl.indexOf("?")>=0) ? "&" : "?" ) + Object.toQueryString(allfilters)
		new Json.Remote(remoteurl, {onComplete: function(result){this.complete(result)}.bind(this)}).send(allfilters);

	},
	
	start: function(allfilters) {
	
		this.fireEvent('onStart',allfilters);
		this.setdisabled(true);
		this.clear();
		this.add(this.options.loadingString,"",true,true)
	
	},

	complete: function(result) {

		this.clear();
		for(var i=0;i<result.options.length;i++){
			this.add(result.options[i].text,result.options[i].value,result.options[i].defaultSelected,result.options[i].selected);
		}
		this.setdisabled(false);
		this.fireEvent('onComplete');

	},
	
	add: function(text,value,defaultSelected,selected) {

		this.combo.options[this.combo.options.length] = new Option(text,value,defaultSelected,selected);

	},

	remove: function(value) {

		for(var i=0;i<this.combo.length;i++){
			if(this.combo.options[i].value==value) {
				this.combo.options[i]=null;
				return;
			}
		}
	
	},
	
	removeIndex: function(index) {
	
		this.combo.options[index]=null;
	
	},

	clear: function() {

		this.combo.options.length=0;

	},

	getselected: function() {

		return this.combo.options[this.combo.selectedIndex]
	
	},
	
	getselectedIndex: function() {
	
		return this.combo.selectedIndex
	
	},

	setselected: function(value) {

		for(var i=0;i<this.combo.length;i++){
			if(this.combo.options[i].value==value) {
				this.setselectedIndex(i);
				return;
			}
		}
	
	},
	
	setdisabled: function(state) {
	
		this.combo.disabled = state;
	
	},

	setselectedIndex: function(index) {
	
		this.combo.selectedIndex=index;
	
	}

});

mzAjaxCombo.implement(new Events, new Options);
