AjaxURL = "/lib/ajax.php";
Ext.override(Ext.form.Field, {
	showContainer: function() {
               this.enable();
               this.show();
               //this.getEl().up(".x-form-item").setDisplayed(true); // show entire container and children (including label if applicable)
	},
	hideContainer: function() {
               this.disable(); // for validation
               this.hide();
               //this.getEl().up(".x-form-item").setDisplayed(false); // hide container and children (including label if applicable)
	},
	setContainerVisible: function(visible) {
		if (visible) {
		       this.showContainer();
		} else {
		       this.hideContainer();
		}
		return this;
	},
	fireKey : function(e) {
		if(((Ext.isIE && e.type == 'keydown') || e.type == 'keypress') && e.isSpecialKey()) {
			this.fireEvent('specialkey', this, e);
		}
		else {
			this.fireEvent(e.type, this, e);
		}
	},
	initEvents : function() {
		//                this.el.on(Ext.isIE ? "keydown" : "keypress", this.fireKey,  this);
		this.el.on("focus", this.onFocus,  this);
		this.el.on("blur", this.onBlur,  this);
		this.el.on("keydown", this.fireKey, this);
		this.el.on("keypress", this.fireKey, this);
		this.el.on("keyup", this.fireKey, this);

		// reference to original value for reset
		this.originalValue = this.getValue();
	}
});
Ext.override(Ext.form.ComboBox, {
	doQuery : function(q, forceAll){
		if(q === undefined || q === null){
			q = '';
		}
		var qe = {
			query: q,
			forceAll: forceAll,
			combo: this,
			cancel:false
		};
		if(this.fireEvent('beforequery', qe)===false || qe.cancel){
			return false;
		}
		q = qe.query;
		forceAll = qe.forceAll;
		if(forceAll === true || (q.length >= this.minChars || (qe.noremote))){
			if(this.lastQuery !== q){
				this.lastQuery = q;
				if(this.mode == 'local' || (qe.noremote)){
					this.selectedIndex = -1;
					if(forceAll){
						this.store.clearFilter();
					}else{
						this.store.filter(this.displayField, q);
					}
					this.onLoad();
				}else{
					this.store.baseParams[this.queryParam] = q;
					this.store.load({
						params: this.getParams(q)
					});
					this.expand();
				}
			} else{
				this.selectedIndex = -1;
				this.onLoad();
			}
		}
		else if(q.length == 0) {
			this.store.baseParams[this.queryParam] = q;
			this.store.load({
				params: this.getParams(q)
			});
			if(this.store.getTotalCount() > 0) {
				this.expand();
			}
		}
		else {
			this.collapse();
		}
	},
	onTriggerClick : function () {
		if (this.disabled) {
			return;
		}
		if (this.isExpanded()) {
			this.collapse();
			this.el.focus();
		} else {
			this.onFocus({});
			if (this.triggerAction == "all") {
				this.doQuery(this.allQuery, true);
			}
			else if(this.lastQuery != undefined) {
				if(this.store.getTotalCount() > 0) {
					this.expand();
					this.restrictHeight();
					if(!this.selectByValue(this.value, true)){
						this.select(0, true);
					}
				}
			}
			else {
				this.doQuery(this.getRawValue(), true);
			}
			this.el.focus();
		}
	}
});

DynControl = function (params) {
	//---------------------
	// Private Properties
	//---------------------

	var _id = (params["id"] != undefined) ? params["id"] : false;
	var _transform = (params["transform"] != undefined) ? params["transform"] : false;
	var _name = params["name"];
	var _masters = params["dependencies"];
	var _elementsToClear = params["elementsToClear"];
	var _css = params["css"];
	var _minListWidth = params["minListWidth"]
	var _defaultvalue = (params["defaultvalue"] != undefined) ? params["defaultvalue"] : false;
	var _width = params["width"];
	var _tpl = params["tpl"];
	var _extrafields = params["extrafields"];
	var _showdesc = params["showdesc"];
	var _minChars = (params["minChars"] != undefined) ? params["minChars"] : 0;
	var _type = (params["type"] != undefined) ? params["type"] : false;
	var _minCharsLocal = 0;
	var _onSelect = (params["onSelect"] != undefined) ? params["onSelect"] : false;
	var _loadSlavesOnEmpty = (params["loadSlavesOnEmpty"] != undefined) ? params["loadSlavesOnEmpty"] : false;

	var _ajaxurl = AjaxURL + "?out=xml&action=dynsel&field=" + _name;
	var _slaves = new Array();
	var _this = this;
	var _value = null;
	var _store = null;
	var _combo = null;
	var _loaded = false;

	var _search = false;

	if(_type == 'search')
		_search = true;

	//---------------------
	// Public Properties
	//---------------------

	this.Name = _name;
	this.Default = _defaultvalue;
	this.remoteMode = true;
	this.LoadSlavesOnEmpty = _loadSlavesOnEmpty;

	//---------------------
	// Public Methods
	//---------------------

	this.switchToLocalMode = function() {
		if(_search) {
			_this.remoteMode = false;
			_combo.queryDelay = 10;
		}
	};
	this.switchToRemoteMode = function() {
		if(_search) {
			_this.remoteMode = true;
			_combo.queryDelay = 500;
		}
	};

	this.isLoaded = function () {
		return _loaded;
	};
	this.setValue = function (value) {
		return _combo.setValue(value);
	}

	this.getValue = function () {
		_value = _combo.getValue();
		return (_value != undefined) ? _value : null;
	};
	this.getName = function () {
		return _name;
	};

	this.setSlave = function (slave) {
		if(!_slaves.inArray(slave))
			_slaves.push(slave);
	};

	this.Load = load;

	//------------------
	// Private Methods
	//------------------
	function MastersLoaded() {
		var loaded = true;
		if(_masters != undefined) {
			if(_masters.length > 0) {
				for(var i=0; i<_masters.length; i++) {
					var m = _masters[i];
					if(m.constructor.xtype == "combo" || m.constructor.xtype == "textfield" || m.constructor.xtype == "numberfield") {
						if(!m.rendered) {
							loaded = false;
						}
					}
					else if(!m.isLoaded() && m.Combo.disabled != true) {
						loaded = false;
					}
				}
			}
		}
		return loaded;
	}
	function createCombo() {
		var fields = [{name: 'id'}, {name: 'entry'}];
		if(_extrafields) {
			for(var i=0; i<_extrafields.length; i++) {
				fields.push(_extrafields[i]);
			}
		}
		_store = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({url: _ajaxurl}),
			reader: new Ext.data.XmlReader({
				totalRecords: "results",
				record: "row",
				id: "id"
			}, Ext.data.Record.create(fields))
		});
		var config = {
			store: _store,
			displayField:'entry',
			valueField: 'id',
			typeAhead: false,
			loadingText: 'Laden...',
			minChars: _minChars,
			selectOnFocus:true,
			hiddenName: _name,
			width:_width,
			forceSelection: true,
			resizable: true
		};
		if(_id) {
			config["renderTo"] = _id;
			clearContainer(_id);
		}
		if(_transform) {
			config["transform"] = _transform;
		}
		if(_minListWidth) {
			config["minListWidth"] = _minListWidth;
		}
		if(_tpl) {
			config["tpl"] = _tpl;
		}
		config["emptyText"] = '(Alle)';

		if(_search) {
			config["mode"] = 'remote';
		}
		else {
			config["mode"] = 'local';
			config["triggerAction"] = 'all';
		}
		_combo = new Ext.form.ComboBox(config);
		_this.Combo = _combo;

		var dependend = false;
		if(_masters != undefined) {
			if(_masters.length > 0) {
				if(!_search && !_loadSlavesOnEmpty) {
					_combo.disable();
				}
				for(var i=0; i<_masters.length; i++) {
					var m = _masters[i];
					if(m.constructor.xtype == "textfield" || m.constructor.xtype == "numberfield") {
						if(m.rendered) {
							m.on("keyup", function(el,e){
								if(el.getValue().toString().length >= el.minLength && el.getValue().toString().length <= el.maxLength) {
									_this.Load();
								}
								else if(_this.Combo.store.baseParams[el.name] != "" && _this.Combo.store.baseParams[el.name] != undefined && el.getRawValue().length == 0) {
									_this.Combo.store.baseParams[el.name] = "";
									_this.Load();
								}
							});
						}
						if(m.rendered && m.getValue() != 0) {
							_this.Load();
						};
					}
					else if(m.constructor.xtype == "combo") {
						m.on("select", function(combo,record,index){
							_this.Load();
						});
						if(m.rendered && m.getValue() != 0) {
							_this.Load();
						};
					}
					else {
						m.setSlave(_this);
						if(m.LoadSlavesOnEmpty) {
							_this.Load();
						}
					}
				}
				dependend = true;
			}
		}

		if(!dependend) {
			_combo.store.load();
		}
		_combo.store.on("beforeload", function(ds, opt) {
			if(_search && _defaultvalue) {
				ds.baseParams[_name+"id"] = _defaultvalue;
			}
		});
		_combo.store.on("load", function(ds, recs, opt) {
			if(_search) {
				if(recs.length < 2) {
					_this.switchToRemoteMode();
				}
				else {
					_this.switchToLocalMode();
					if(opt.params["query"].length != undefined)
						_minCharsLocal = opt.params["query"].length;
					else
						_minCharsLocal = 0;
				}
			}
			var defv = _defaultvalue;
			if(defv && MastersLoaded()) {
				if(_search) {
					_combo.store.baseParams["ortid"] = "";
				}

				_combo.setValue(defv);
				if(_combo.getValue() > 0) {
					_defaultvalue = false;
					_loaded = true;
				}

				if(_onSelect !== false) {
					_onSelect.call(this, _combo.getValue());
				}
				if(_slaves != undefined) {
					if(_slaves.length > 0) {
						for(var i=0; i<_slaves.length; i++) {
							var s = _slaves[i];
							s.Load();
						}
					}
				}
			}
			else {
				_loaded = true;
			}
		});

		_combo.on("focus", function(field) {
			if(_combo.getRawValue() == "") {
				_combo.doQuery(_combo.getRawValue(), true);
			}
			if(_combo.store.getTotalCount() > 0) {
				_combo.expand();
				_combo.restrictHeight();
				if(!_combo.selectByValue(_combo.value, true)){
					_combo.select(0, true);
				}
			}
		});

		_combo.on("select", function(combo,record,index){
			if(_onSelect !== false) {
				_onSelect.call(this, _combo.getValue());
			}
			if(_elementsToClear != undefined) {
				if(_elementsToClear.length > 0) {
					for(var i=0; i<_elementsToClear.length; i++) {
						if(_elementsToClear[i].constructor.xtype == "textfield" || _elementsToClear[i].constructor.xtype == "numberfield") {
							_elementsToClear[i].reset();
						}
					}
				}
			}
			if(_slaves != undefined) {
				if(_slaves.length > 0) {
					for(var i=0; i<_slaves.length; i++) {
						var s = _slaves[i];
						s.Load();
					}
				}
			}
		});

		if(_search) {
			_combo.on("beforequery", function(e) {
				if(e.combo.lastQuery != undefined) {
					if(e.query.length < _minChars && e.query.length < _minCharsLocal) {
						_this.switchToRemoteMode();
					}
				}
				if(!_this.remoteMode) {
					e.noremote = true;
				}
			});
		}
	}
	function load(nonmasterparams) {
		_combo.clearValue();
		var paramsobj = new Object();
		if(nonmasterparams != undefined) {
			for (var nonmasterparam in nonmasterparams) {
				paramsobj[nonmasterparam] = nonmasterparams[nonmasterparam];
			}
		}
		var load = true;
		if(_masters != undefined) {
			if(_masters.length > 0) {
				for(var i=0; i<_masters.length; i++) {
					var m = _masters[i];
					var mvalue = m.getValue();
					if(mvalue != 0 && mvalue != null || m.LoadSlavesOnEmpty) {
						paramsobj[m.getName()] = mvalue;
					}
					else {
						load = false;
					}
				}
			}
		}
		if(_combo.getRawValue() != "keine Einträge")
			paramsobj["query"] = _combo.getRawValue();
		if(_search) {
			_combo.enable();
			_combo.store.baseParams = paramsobj;
			_combo.store.load({
				params: paramsobj,
				callback: function(rec, opt, suc) {
						if(rec.length < 1) {
							_combo.disable();
							_combo.setRawValue("keine Einträge");
						}
					}
			});
		}
		else {
			if(load) {
				_combo.enable();
				_combo.store.load({params:paramsobj});
			}
			else {
				_combo.disable();
			}
		}
	}

	//------------
	// Konstruktor
	//------------

	createCombo();
}

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};
