Ext.ns('MyLib');

//Ext.BLANK_IMAGE_URL = './extjs/images/default/s.gif'
Ext.BLANK_IMAGE_URL = '/ipack/extjs/images/default/s.gif'
// global Target der Fehlermeldungen setzen
Ext.form.Field.prototype.msgTarget = 'side';

// RowExpander Erweiterung
MyLib.MyRowExpander = Ext.extend(Ext.grid.RowExpander, {
	constructor: function(config){
		MyLib.MyRowExpander.superclass.constructor.call(this, config);
	},
	getBodyContent : function(record, index){
        var usedtpl;
        if (Ext.isFunction(this.onGetTemplate))
        	usedtpl = this.onGetTemplate(record, index);
        else
        	usedtpl = this.tpl;

		if(!this.enableCaching){
            return usedtpl.apply(record.data);
        }
        var content = this.bodyContent[record.id];
        if(!content){
            content = usedtpl.apply(record.data);
            this.bodyContent[record.id] = content;
        }
        return content;
    }
});

// Erweiterte E-Mail Validierung
Ext.apply(Ext.form.VTypes, {
	emailrepeat : function(val, field) {
		if (field.refField) {
			var email1 = Ext.getCmp(field.refField);
			return (val == email1.getValue());
		}
		return true;
	},
	emailrepeatText : 'Die wiederholte e-Mail Adresse stimmt nicht mit der vorher eingegebenen überein',
	passwordrepeat : function(val, field) {
		if (field.refField) {
			var email1 = Ext.getCmp(field.refField);
			return (val == email1.getValue());
		}
		return true;
	},
	passwordrepeatText : 'Das wiederholte Kennwort stimmt nicht mit der vorher eingegebenen überein'
});

MyLib.SearchGridPanel = Ext.extend(Ext.Panel, {
	constructor : function(config, pNLS) {
		MyLib.SearchGridPanel.superclass.constructor.call(this);
		config.layout = 'border';
		Ext.apply(this, config);
		this.title = this.viewname;
		this.store = new Ext.data.ArrayStore({
					fields : this.cfgFields
				});

		var expanderRow = null;
		if (this.cfgExpander) {
			expanderRow = new MyLib.MyRowExpander({
						tpl : new Ext.Template(this.cfgExpander)
					});
			this.cfgGridCols.unshift(expanderRow);
			this.expander = expanderRow;
		}
		var sm = {singleSelect: true};
		if (Ext.isFunction(config.onRowSelected)){
			sm.listeners = {selectionchange: config.onRowSelected,
							scope: this};
		}
		var gridCnf = {
			autoSizeColumns : true,
			store : this.store,
			cm : new Ext.grid.ColumnModel({
						columns : this.cfgGridCols,
						defaultSortable : true
					}),
			stripeRows : true,
			width : this.width,
			title : this.viewname,
			region : 'center',
			selModel : new Ext.grid.RowSelectionModel(sm)
		};
		if (Ext.isDefined(config.gridToolbar)){
			gridCnf.tbar = config.gridToolbar;
		}
		if (config.forceFit){
			gridCnf.viewConfig = {forceFit:true};
		}
		if (expanderRow !== null) {
			gridCnf.plugins = expanderRow;
		}
		if (Ext.isArray(this.cfgSearchFields)){
			var i;
			for (i = 0; i < this.cfgSearchFields.length; i++)
				this.cfgSearchFields[i].restless = this.restless;
			this.form = new Ext.FormPanel({
						animCollapse : false,
						region : 'north',
						autoScroll : true,
						labelWidth : 130,
						collapsible : true,
						split : true,
						frame : true,
						//title : this.viewname + ' - Suchen',
						title : 'Suchen',
						bodyStyle : 'padding:5px 5px 0',
						width : this.width,
						//autoHeight: true, //funktioniert nicht
						height : 200,
						defaults : {
							width : 230
						},
						defaultType : 'textfield',
						items : this.cfgSearchFields,
						grid : this.grid,
						buttonAlign : 'left',
						buttons : [{
									text : pNLS.tr('ALLGEMEIN', 'Absenden'),
									handler : this.loadDataToGrid,
									scope : this
								},{
									text : pNLS.tr('ALLGEMEIN', 'Zurücksetzen'),
									handler : function() {
										this.form.getForm().reset();
									},
									scope : this
								}]
					});
			this.add(this.form);
		}
		else
			this.form = null;
		this.grid = new Ext.grid.GridPanel(gridCnf);
		this.add(this.grid);
		if (this.form == null)
			this.loadDataToGrid();
	},
	loadDataToGrid : function() {
		if (this.form == null || this.form.getForm().isValid()) {
			var pparams = {};
			if (this.form != null)
				pparams = this.form.getForm().getFieldValues(true);
			if (this.extraparams)
				Ext.apply(pparams, this.extraparams);
			MyLib.doJsonRequest(this, {
						url : this.restless + '/' + this.qrymethod,
						params : pparams,
						method : 'GET',
						handlesuccess : function(res) {
							var pcfgdata = res.data;
							this.store.loadData(pcfgdata.rs);
							this.grid.setTitle(this.viewname + ' (' + pcfgdata.rscount + ' Datensätze)');
							if (Ext.isFunction(this.afterDataLoaded))
								this.afterDataLoaded.call(this);
							// wegen grid auf hidden tab-panel geht das nicht
							//this.grid.getView().refresh();
						}
					});
		}
	}
});
Ext.reg('x_searchgridpanel', MyLib.SearchGridPanel);

MyLib.SearchGridPanel2 = Ext.extend(MyLib.SearchGridPanel, {
	constructor : function(pTarget, pNLS, pLang, pFormName, pCfg) {
		this.target = pTarget;
		this.NLSStrings = pNLS;
		this.Lang = pLang;
		this.FormName = pFormName;
		this.cfg = pCfg;
		var i, j;
		this.translate(this.cfg);
		for (i = 0; i < this.cfg.cfgGridCols.length; i++) {
			this.translate(this.cfg.cfgGridCols[i]);
		};
		if (Ext.isArray(this.cfg.cfgSearchFields))
			for (i = 0; i < this.cfg.cfgSearchFields.length; i++) {
				this.translate(this.cfg.cfgSearchFields[i]);
			};
		MyLib.SearchGridPanel2.superclass.constructor.call(this, this.cfg, pNLS);
		if (Ext.isString(this.target) && this.target != ""){
			this.render(this.target);
		}
	},
	tr: function(pForm, pVal, pDefault){
		var f = pForm.toUpperCase();
		if (Ext.isDefined(pVal) && Ext.isDefined(this.NLSStrings[this.Lang]) &&
			Ext.isDefined(this.NLSStrings[this.Lang][f]) && Ext.isDefined(this.NLSStrings[this.Lang][f][pVal]) &&
			this.NLSStrings[this.Lang][f][pVal] != ''){
			return  this.NLSStrings[this.Lang][f][pVal];
		}
		else
			return pDefault;
	},
	translate: function(pObj){
		// das geht nicht so einfach objektorientierter, weil wir hier mit den cfg-objekten arbeiten.
		if (Ext.isDefined(pObj.fieldLabel))
			pObj.fieldLabel = this.tr.call(this, this.FormName, pObj.fieldLabel, pObj.fieldLabel);
		if (Ext.isDefined(pObj.header))
			pObj.header = this.tr.call(this, this.FormName, pObj.header, pObj.header);
	}
});
Ext.reg('x_searchgridpanel', MyLib.SearchGridPanel);

MyLib.doJsonRequest = function(pscope, pcfg) {
	var loadingMask = new Ext.LoadMask(Ext.getBody(), {
				msg : "Daten werden geladen, bitte warten...",
				id : "loadingMask"
			});
	loadingMask.show();
	Ext.Ajax.request({
		scope : pscope,
		url : pcfg.url,
		method : pcfg.method,
		params : pcfg.params,
		success : function(result, request) {
			try {
				var res = Ext.decode(result.responseText);
				if (res.error == '' || res.error == null) {
					try {
						pcfg.handlesuccess.call(this, res);
					} catch (e) {
						Ext.MessageBox.alert('Ausnahme-Fehler bei der Verarbeitung', e.description);
					}
				} else {
					Ext.MessageBox.alert('Aufruf fehlgeschlagen', res.error);
				}
			} catch (e) {
				Ext.MessageBox.alert('Exception caught', 'Server-Antwort ungültig: ' + result.responseText);
			}
			loadingMask.hide();
			loadingMask = null;
		},
		failure : function(result, request) {
			Ext.MessageBox.alert('Failed', result.responseText);
			loadingMask.hide();
			loadingMask = null;
		}
	});
};

//Form Field Erweiterung
Ext.override(Ext.form.Field, {
	initComponent : Ext.form.Field.prototype.initComponent.createSequence( function(){
		if (this.allowBlank == false && this.fieldLabel != ""){
			this.fieldLabel = this.fieldLabel + "*";
			this.labelStyle = "font-weight:bold;"; // "font-weight:bold;color:#15428B";
		};
	}),
	afterRender : Ext.form.Field.prototype.afterRender.createSequence( function(){
		if (this.qTipText) {
			var findLabel = function(field) {
				var wrapDiv = null;
				var label = null
				// find form-item and label
				wrapDiv = field.getEl().up('div.x-form-item');
				if (wrapDiv) {
					label = wrapDiv.child('label');
				}
				if (label) {
					return label;
				}
			};

			var label = findLabel(this);
			if (label) {
				var helpImage = label.createChild({
		                id: this.id + '_qtip',
						tag:'img',
		                src:'img/info_16.png',
		                width:16,
		                height:16
		            });
				Ext.QuickTips.register({
						target : helpImage,
						title : this.fieldLabel,
						text : this.qTipText,
						enabled : true
					});
			}
		}
		if (this.rightText) {
			var wrapDiv = null;
			var e = this.getEl();
			wrapDiv = e.up('div.x-form-field-wrap');
			if (wrapDiv)
				wrapDiv.createChild({tag: 'span', style:'margin-left: 40px;padding:0;',html: this.rightText});
			else
				e.insertSibling({tag: 'span', style:'margin-left: 10px;padding:0;', html: this.rightText}, 'after');
		}
	})
});

MyLib.DBComboBox = Ext.extend(Ext.form.ComboBox, {
	constructor : function(config) {
		Ext.apply(this, config);
		var st = new Ext.data.Store({
					proxy : new Ext.data.HttpProxy({
								url : config.restless + '/qrylookup?lookupid='
										+ config.lookupid
							}),
					reader : new Ext.data.JsonReader({
								totalProperty : 'itemcnt',
								root : 'items'
							}, [{
										name : 'id'
									}, {
										name : 'display'
									}]),
					listeners : {load: function(){
												if (this.defaultValue)
													this.setValue(this.defaultValue);
												},
								 scope: this}
				});

		MyLib.DBComboBox.superclass.constructor.call(this, {
					store : st,
					displayField : 'display',
					valueField : 'id',
					typeAhead : true,
					mode : 'local',
					triggerAction : 'all',
					emptyText : 'Bitte wählen...',
					selectOnFocus : true,
					forceSelection : true,
					fieldLabel : config.fieldLabel,
					hiddenName : config.name,
					width: 300,
					name : config.name + '_displayvalue'
				});
		if (Ext.isArray(config.dependendLBs)) {
			this.on('select', function() {
						var i;
						for (i = 0; i < this.dependendLBs.length; i++) {
							var cmp = Ext.getCmp(this.dependendLBs[i]);
							cmp.reset();
							cmp.store.proxy = new Ext.data.HttpProxy({
										url : new Ext.data.HttpProxy({
													url : config.restless
															+ '/qrylookup?lookupid='
															+ cmp.lookupid
															+ '&'
															+ this.hiddenName
															+ '='
															+ this.getValue()
												})
									});
							cmp.store.load();
						};
					}, this);
		};
		this.store.load();
	}
});
Ext.reg('x_dblookupcombo', MyLib.DBComboBox);

MyLib.LangComboBox = Ext.extend(Ext.form.ComboBox, {
	constructor : function(pTarget) {
		MyLib.LangComboBox.superclass.constructor.call(this, {
					store : new Ext.data.SimpleStore({
			            fields: ['countryCode', 'countryName'],
			            data: [
			                ['1', 'deutsch'],
			                ['2', 'englisch'],
			                ['3', 'französisch']
// 			                ['4', 'spanisch']
			            ]
			        }),
					displayField : 'countryName',
					valueField : 'countryCode',
					typeAhead : true,
					mode : 'local',
					triggerAction : 'all',
					emptyText : 'Bitte wählen...',
					selectOnFocus : true,
					forceSelection : true
				});
		this.on('select',
				function() {
					var param = Ext.urlDecode(window.location.search.substring(1));
					param.lang_id = this.getValue();
					window.location = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + Ext.urlEncode(param);
				},
				this);
		this.tpl = '<tpl for="."><div class="x-combo-list-item x-icon-combo-item x-flag-{' + this.valueField + '}">{' + this.displayField + '}</div></tpl>';

		this.on('render',
				function(){
			    	var wrap = this.el.up('div.x-form-field-wrap');
			        this.wrap.applyStyles({position:'relative'});
			        this.el.addClass('x-icon-combo-input');
			        this.flag = Ext.DomHelper.append(wrap, {
			             tag: 'div', style:'position:absolute'
			          });
			    },
			    this);
		var lang_id = getLangID();
		if (Ext.isString(pTarget) && pTarget != ""){
			this.render(pTarget);
			this.setValue(lang_id);
		}
	},
    setIconCls: function() {
		this.flag.className = 'x-icon-combo-icon x-flag-' + this.getValue();
    },
    setValue: function(value) {
    	MyLib.LangComboBox.superclass.setValue.call(this, value);
        this.setIconCls();
    }
});
Ext.reg('x_langcombobox', MyLib.LangComboBox);

MyLib.DateField = Ext.extend(Ext.form.DateField, {
			constructor : function(config) {
				config.altFormats = "j\.n\.y|j\.n\.Y|dmy|dmY";
				Ext.apply(this, config);
				MyLib.DateField.superclass.constructor.call(this, config);
			}
		});
Ext.reg('x_datefield', MyLib.DateField)

MyLib.Checkbox = Ext.extend(Ext.form.Checkbox, {
			getValue : function() {
				return (MyLib.Checkbox.superclass.getValue.call(this)
						? "J"
						: "N");
			}
		});
Ext.reg('x_checkbox', MyLib.Checkbox);

MyLib.RadioGroup = Ext.extend(Ext.form.RadioGroup, {
			getValue : function() {
				var o = MyLib.RadioGroup.superclass.getValue.call(this)
				return (o ? o.inputValue : -1);
			}
		});
Ext.reg('x_radiogroup', MyLib.RadioGroup);

MyLib.TextField = Ext.extend(Ext.form.TextField, {
			constructor : function(config) {
				config.maxLength = config.fieldLength;
				config.autoCreate = {
					tag : 'input',
					type : 'text',
					size : Math.min(Math.floor(config.fieldLength * 1.5), 100),
					autocomplete : 'on',
					maxlength : config.fieldLength
				};
				Ext.apply(this, config);
				MyLib.TextField.superclass.constructor.call(this, config);
			}
		});
Ext.reg('x_textfield', MyLib.TextField)


MyLib.BaseForm = Ext.extend(Ext.FormPanel, {
	constructor : function(pTarget, pNLS, pLang, pFormName, pCfg) {
		this.target = pTarget;
		this.NLSStrings = pNLS;
		this.Lang = pLang;
		this.FormName = pFormName;
		this.cfg = pCfg;
		// defaults: Error-Feld und buttons für Senden/Zurücksetzen
		this.cfg.items.unshift({
			id : "idErrorTextSet",
			title : 'Fehler',
			style : 'font-weight:bold;color:#FF0000',
			autoHeight : true,
			autoWidth : true,
			xtype : 'fieldset',
			hidden : true,
			items : [ {
				id : "idErrorText",
				name : "errorText",
				autoHeight : true,
				autoWidth : true,
				style : 'font-weight:bold;color:#FF0000',
				value : "",
				fieldLabel : "Fehler",
				hideLabel : true,
				htmlEncode : false,
				hidden : true,
				noPost : true,
				xtype : 'displayfield'
			} ]
		});
		if(!Ext.isDefined(this.cfg.buttons))
			this.cfg.buttons = [];
		/*this.cfg.buttons.unshift({
			id : 'bnReset',
			text : pNLS.tr('ALLGEMEIN', 'Zurücksetzen'),
			handler : function() {
				if (Ext.isFunction(this.handleReset))
					this.handleReset();
				else
					this.getForm().reset();
			},
			scope : this
		});*/
		this.cfg.buttons.unshift( {
			id : 'bnSubmit',
			text : pNLS.tr('ALLGEMEIN', 'Absenden'),
			handler : this.doSubmit,
			scope : this
		});
		this.cfg.buttons.push({xtype: 'tbfill'});
		this.cfg.buttons.push({
			text : pNLS.tr('ALLGEMEIN', 'Pflichtfelder sind mit * gekennzeichnet'),
			xtype: 'label'
		});
		var i, j;
		this.translate(this.cfg);
		for (i = 0; i < this.cfg.items.length; i++) {
			this.cfg.items[i].restless = this.cfg.restless;
			this.translate(this.cfg.items[i]);
			if (Ext.isArray(this.cfg.items[i].items)){
				for (j = 0; j < this.cfg.items[i].items.length; j++) {
					this.cfg.items[i].items[j].restless = this.cfg.restless;
					this.translate(this.cfg.items[i].items[j]);
				}
			}
		};
		MyLib.BaseForm.superclass.constructor.call(this, this.cfg);
		if (Ext.isString(this.target) && this.target != ""){
			this.render(this.target);
		}
	},
	translate: function(pObj){
		// das geht nicht so einfach objektorientierter, weil wir hier mit den cfg-objekten arbeiten.
		var tr = function(pForm, pVal, pDefault){
			var f = pForm.toUpperCase();
			if (Ext.isDefined(pVal) && Ext.isDefined(this.NLSStrings[this.Lang]) &&
				Ext.isDefined(this.NLSStrings[this.Lang][f]) && Ext.isDefined(this.NLSStrings[this.Lang][f][pVal]) &&
				this.NLSStrings[this.Lang][f][pVal] != ''){
				return  this.NLSStrings[this.Lang][f][pVal];
			}
			else
				return pDefault;
		};
		pObj.qTipText = tr.call(this, "Hilfe", this.FormName + "-" + pObj.fieldLabel, "");
		if (Ext.isDefined(pObj.fieldLabel))
			pObj.fieldLabel = tr.call(this, this.FormName, pObj.fieldLabel, pObj.fieldLabel);
		if (Ext.isDefined(pObj.title))
			pObj.title = tr.call(this, this.FormName, pObj.title, pObj.title);
		if (Ext.isDefined(pObj.rightText))
			pObj.rightText = tr.call(this, this.FormName, pObj.rightText, pObj.rightText);
		if (Ext.isDefined(pObj.xtype) && pObj.xtype == 'displayfield')
			pObj.value = tr.call(this, this.FormName, pObj.value, pObj.value);
		if (Ext.isDefined(pObj.xtype) && pObj.xtype == 'x_radiogroup'){
			for(var i=0; i<pObj.items.length; i++){
				var f = pObj.items[i];
				if (Ext.isDefined(f.boxLabel))
					f.boxLabel = tr.call(this, this.FormName, f.boxLabel, f.boxLabel);
			}
		}
	},
	getFieldValues: function(){
        var o = {};
        this.getForm().items.each(function(f){
        	if (f.noPost !== true){
        		var v = f.getValue();
        		if (Ext.isDate(v))
        			o[f.getName()] = v.format('Y-m-d');
        		else
        			o[f.getName()] = v;
        	}
        });
        return o;
	},
	doSubmit : function() {
		if (this.getForm().isValid()) {
			var p = this.getFieldValues();
			Ext.apply(p, this.extraparams);

			MyLib.doJsonRequest(this, {
						url : this.restless + '/' + this.submitTarget,
						method : 'POST',
						params : p,
						handlesuccess : function(pcfgdata) {
							if (Ext.isFunction(this.afterSubmit))
								this.afterSubmit(pcfgdata);
							else{
								var errField = Ext.getCmp('idErrorText');
								var errFieldSet = Ext.getCmp('idErrorTextSet');
								if (pcfgdata.errors.length == 0) {
									errFieldSet.setVisible(false);
									errField.setVisible(false);
									Ext.MessageBox.alert(this.NLSStrings.tr('Allgemein', 'Anfrage angenommen'),
														 this.NLSStrings.tr(this.FormName, this.cfg.successMessage),
														 function(){this.redirectForm(this.cfg.successRedirect);},
														 this);
								} else{
									errField.setValue(pcfgdata.errors.join("<br>"));
									errFieldSet.setVisible(true);
									errField.setVisible(true);
									Ext.MessageBox.alert(this.NLSStrings.tr('Allgemein', 'Feld-Überprüfung'),
											             this.NLSStrings.tr('Allgemein', 'Bitte korrigieren Sie die angegebenen Fehler'));
								}
							}
						}
					});
		} else {
			Ext.MessageBox.alert("Feld-Überprüfung",
							     "Die Überprüfung ihrer Eingaben war nicht erfolgreich. Bitte korrigieren Sie die markierten Fehler");
		}
	},
	redirectForm: function(pFormName){
		if (Ext.isString(pFormName)){
			var p = document.location.pathname.replace(/(.*)\/([^\/]+.html)/, "$1");
			document.location.assign(p + '/' + pFormName);
		}
	}
});


