Ext.BLANK_IMAGE_URL = 'img/s.gif';
Ext.ns('Medcon');
Medcon.version = '1.0';

var debug = false;
var user_id = '';
var role = '';

var countries_store;
var languages_store;
var roles_store;
var fields_store;
var cycles_store;

Ext.onReady(function() {
	Ext.QuickTips.init();
	
	// Firebug aktiv?
	if (typeof console != 'undefined') {
		debug = true;
	}
	
	if (debug) {
		console.log('Ext.onReady');
	}	
	
	showMain();	
	
});


function init_stores() {
	countries_store = new Ext.data.JsonStore({
		url: '/countries/',
		fields: ['code', 'title', 'prefix'],
		id: 'code',
		root: 'data',
		autoLoad: false
	});
	countries_store.load();
	
	languages_store = new Ext.data.JsonStore({
		url: '/languages/',
		fields: ['id', 'title'],
		id: 'id',
		root: 'data',
		autoLoad: false
	});
	languages_store.load();

	roles_store = new Ext.data.JsonStore({
		url: '/roles/',
		fields: ['id', 'title'],
		id: 'id',
		root: 'data',
		autoLoad: false
	});
	roles_store.load();
	
	fields_store = new Ext.data.JsonStore({
		url: '/fields/',
		fields: ['id', 'display_name'],
		id: 'id',
		root: 'data',
		autoLoad: true
	});
	fields_store.load();
	
	cycles_store = new Ext.data.JsonStore({
		url: '/cycles/',
		fields: ['id', 'title'],
		id: 'id',
		root: 'data',
		autoLoad: true
	});	
}


function display_boolean(val, x, store) {
	return val ? 'ja' : 'nein';
}


function showLoginDialog() {
	if (debug) {
		console.log('showLoginDialog()');
	}
	
	var login_form = new Ext.FormPanel({
		id: 'login_form',
		layout: 'form',
		xtype: 'form',
		url: '/users/login',
		items: [
		{
			xtype: 'textfield', 
			fieldLabel: 'E-Mail-Adresse',
			name: 'username',
			anchor: '100%',
			allowBlank: false
		},
		{
			xtype: 'textfield', 
			fieldLabel: 'Passwort',
			name: 'password',
			anchor: '100%',			
			inputType: 'password',
			allowBlank: false
		}
		],
		buttons: [
		{
			text: 'Anmelden',
			id: 'login_form_btn_submit',
			handler: function() {
				var passwd_field = login_form.getForm().findField('password');
				var passwd = passwd_field.getValue(); 
				passwd = hex_md5(passwd);
				passwd_field.setValue(passwd);
				
				login_form.getForm().submit({
					success: function(f, a) {
						Ext.getCmp('statusbar').setStatus({text: 'Angemeldet als: ' + 
							a.result.fname + ' ' + a.result.lname + 
							', Rolle: ' + a.result.role_title});
						w.close();
						
						// häufig genutzte stores laden
						init_stores();
						
						// user_id und Rolle merken
						role = a.result.role;
        				user_id = a.result.user_id;
        				if (debug) {
        					console.log('user_id', user_id);
        					console.log('role', role);
        				}
        				
        				// Funktionen entsprechend der Rolle einblenden
        				if (role == admin_role) {
        					Ext.getCmp('viewport_admin_menu').enable();	
        					Ext.getCmp('viewport_admin_menu_users').enable();
        				}
						if (role == editor_role) {
        					Ext.getCmp('viewport_admin_menu').enable();
        				}
						
						// Authentifizierung alle 60s überprüfen
						var check_auth_task = {
							run: function() {
								var conn = new Ext.data.Connection();
								conn.request({
    								url: '/users/status',
    								method: 'POST',    	
    								success: function(res) {
										var resdata = Ext.util.JSON.decode(res.responseText);
										if (debug) {
											console.log('authenticated:', resdata.authenticated);
										}
        								// Bei Erfolg user_id und rolle merken
										if (!resdata.authenticated) {
        									logout();
        								}
									},
     								failure: function() {
        								logout();
     								}
								});
							}, // run end
							interval: 60000
						}; // task end
						Ext.TaskMgr.start(check_auth_task);
						
						// nach Login 'Meine Veranstaltungen' anzeigen
						showEvents();
					},
					failure: function(f, a) {
						passwd_field.setValue('');
						if (a.result) {
							Ext.Msg.alert('Fehler', a.result.errormsg); 							
						} else {
							Ext.Msg.alert('Fehler', 'Bitte füllen Sie alle rot markierten Felder aus.');
						}	
					}					
				});				
			} // handler end
		},
		{
			text: 'Zur&uuml;cksetzen',
			id: 'login_form_btn_reset',
			handler: function() {
				login_form.getForm().reset();			
			}
		},
		{
			text: 'Passwort vergessen',
			id: 'login_form_btn_resetpw',
			handler: function() {
				Ext.Msg.show({
   					title: 'Passwort vergessen',
   					msg: 'Bitte geben Sie Ihre <b>E-Mail-Adresse</b> ein. Nach dem Absenden erhalten Sie eine E-Mail mit einem Link zum Zurücksetzen Ihres Passworts.',
   					buttons: Ext.Msg.OKCANCEL,
   					width: 350,
   					prompt: true,
   					fn: function(btn, data) {
						if ((btn == 'ok') && data) {							
							// Transaktion auslösen
							if (debug) {
								console.log('Calling /users/reset_password with username=', data);
							}
							var conn = new Ext.data.Connection();
							conn.request({
    							url: '/users/reset_password',
    							method: 'POST',
    							params: {
									username: data
								},
    							success: function(res) {
									var resdata = Ext.util.JSON.decode(res.responseText);
        							if (!resdata.success) {
        								Ext.Msg.alert('Fehler', 'Transaktion konnte nicht gestartet werden.');
        							}
								},
     							failure: function() {
        							Ext.Msg.alert('Fehler', 'Transaktion konnte nicht gestartet werden.');
     							}
							}); // conn.request end						
						} // end btn == 'ok'
					}
				});			
			}
		}
		] // buttons end
				
	});
	
	var w = new Ext.Window({ 
		width: 350,
		autoHeight: true,
		title: 'Login',
		defaults: {bodyStyle: 'padding:10px'},
		closable: false,
		modal: true,
		border: false,
		items: [
		 	login_form       		
		]
	});
	
	w.show();
	
}


function showMain() {
	if (debug) {
		console.log('showMain()');
	}
	
	var viewport = new Ext.Viewport({
		layout: 'border',
  		id: 'viewport',
  		items: [{
			region: 'north',
    			xtype: 'panel',
       			height: 100,
	  			layout: 'anchor',
     			border: false,
       			items: [
       			{
       				xtype: 'box',
     				el: 'header',
     				border: false,
     				anchor: 'none -25'	 			
 				}, 
 				{
					xtype: 'toolbar',
   					items: [
   				  		{
   							xtype: 'tbspacer'
   						},
   						{
							xtype: 'tbbutton',
   							text: 'Meine Veranstaltungen',
   							handler: showEvents
						},
   						{
							xtype: 'tbbutton',
   							text: 'Veranstaltung melden',
   							handler: showEventDetails
						},
						{
							xtype: 'tbseparator'
						},
   						{
							xtype: 'tbbutton',
   							text: 'Administration',
   							id: 'viewport_admin_menu',
   							disabled: true,
   							menu: {
   								items: [   						
   									{
   										text: 'Benutzerverwaltung',
   										id : 'viewport_admin_menu_users',
   										disabled: true,
   										handler: showUsers
   									},
   									{
   										text: 'Veranstaltungsorte',
   										handler: showLocations
   									},
									{
   										text: 'Veranstalter',
   										handler: showContacts
   									}   									
   								]
   							}
						},
						{
							xtype: 'tbfill'
						},
						{
							xtype: 'tbbutton',
     						text: 'Abmelden',
     						handler: function(btn) {
	     						logout();
     						}
						}
					] // toolbar items end
			    } // toolbar end
			] // north items end
		}, 
		{
			region: 'center',
    		xtype: 'panel',
       		id: 'mainpanel',
       		bbar: new Ext.StatusBar({
 	 			id: 'statusbar',
 				defaultText: 'Bitte melden Sie sich an',
 				defaultIconCls: 'default-icon',
				iconCls: 'ready-icon'
 			})
		}
		] // viewport items end
	});		
	
	showLoginDialog();	
}


function showEventDetails(event_id) {	
	if (debug) {
		console.log('showEventDetails(event_id)', event_id);
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('eventview')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}
	
	var contacts_store = new Ext.data.JsonStore({
		url: '/contacts/',
		fields: [
		         'id', 
		         {
		        	 name: 'display_name', 
		        	 mapping: 'company + obj.company2 + ", " + obj.city + ", " + obj.country'
		         }
		],
		id: 'id',
		root: 'data',
		autoLoad: false
	});

	var locations_store = new Ext.data.JsonStore({
		url: '/locations/',
		fields: [
		         'id', 
		         {
		        	 name: 'display_name', 
		        	 mapping: 'title + ", " + obj.city + ", " + obj.country'
		         }
		],
		id: 'id',
		root: 'data',
		autoLoad: false
	});
	
	var lectures_store = new Ext.data.JsonStore({
		url: '/lectures/',
		fields: [
		         'id',
		         'title',
		         {
		        	 name: 'highlight',
		        	 type: 'boolean'
		         },
		         'cme_points'
		],
		id: 'id',
		root: 'data',
		autoLoad: false
	});
	
	var comments_store = new Ext.data.JsonStore({
		url: '/comments/',
		fields: [
		         'id',
		         'created',
		         {
		        	 name: 'anonymous',
		        	 type: 'boolean'
		         },
		         'description'
		],
		id: 'id',
		root: 'data',
		autoLoad: false
	});	
	
	// Tab 1: Event Daten
	var event_form = new Ext.FormPanel({
		title: 'Veranstaltung',
		id: 'eventview_tab1',
		layout: 'form',
		xtype: 'form',
		bodyStyle: 'padding:10px',
		autoHeight: true,
		items: [
			{
				xtype: 'datefield',
				name: 'date_begin',
				id: 'eventview_tab1_date_begin',
				fieldLabel: 'Beginn',
				allowBlank: false
			},
			{
				xtype: 'datefield',
				name: 'date_end',
				id: 'eventview_tab1_date_end',
				fieldLabel: 'Ende'
			},		
			{
				xtype: 'textfield',
				name: 'title',
				fieldLabel: 'Titel',
				anchor: '100%',
				allowBlank: false
			},	
			{
				layout: 'table',
				layoutConfig: {
					columnCount: 4
				},
				border: false,
				style: 'margin-bottom: 4px',				
				items: [
				{
					xtype: 'label',
					text: 'Ort',
					cellCls: 'x-form-item',
					width: 105
				},
				{
					xtype: 'combo', 								
					name: 'location',
					hiddenName: 'location',
					id: 'eventview_tab1_location',
					fieldLabel: 'Ort',
					store: locations_store,
					displayField: 'display_name',
					valueField: 'id',
					mode: 'remote',
					typeAhead: true,
					triggerAction: 'all',
					minChars: 3,
					emptyText: 'Bitte auswählen',
					forceSelection: true,
					allowBlank: false,
					width: 370
				},
				new Ext.form.MiscField({
					fieldLabel: 'MiscField',
    				id: 'spacer2',
    				width: 5,
    				value: ' '
				}),
				{
		        	xtype: 'button',
	            	text: 'Hinzufügen',
	            	width: 90,
	            	handler: function() {
						showCreateLocation();
					}	            	   				
	            }
		        ]

			},	// location end		
			{
				xtype: 'textarea',
				name: 'description',
				fieldLabel: 'Kurze Beschreibung der Veranstaltung',
				height: 100,
				anchor: '99%',
				emptyText: 'Details zu Vorträgen erfassen Sie bitte unter dem Register "Vorträge"'
			},
			{
				xtype: 'textfield',
				name: 'administration',
				fieldLabel: 'Organisation',
				anchor: '100%',
				emptyText: 'Fügen Sie hier den Ansprechpartner ein'
			},												
			{
				layout: 'table',
				layoutConfig: {
					columnCount: 4
				},
				border: false,
				style: 'margin-bottom: 4px',		
				items: [
				{
					xtype: 'label',
					text: 'Veranstalter:',
					cellCls: 'x-form-item',
					width: 105
				},
				{
					xtype: 'combo', 								
					name: 'contact',
					hiddenName: 'contact',
					id: 'eventview_tab1_contact',
					fieldLabel: 'Veranstalter',
					store: contacts_store,
					displayField: 'display_name',
					valueField: 'id',
					mode: 'remote',
					typeAhead: true,
					triggerAction: 'all',
					minChars: 3,
					emptyText: 'Wählen Sie hier den Veranstalter aus',
					forceSelection: true,
					allowBlank: false,
					width: 370
				},
				new Ext.form.MiscField({
					fieldLabel: 'MiscField',
    				id: 'spacer1',
    				width: 5,
    				value: ' '
				}),
				{
		   			xtype: 'button',
	  				name: 'SubItem1',	  				
	       	   		text: 'Hinzufügen',
	            	width: 90,
	            	handler: function() {
						showCreateContact();						
					}
	            }
		        ]
			}, // contact end		
			{
				xtype: 'combo',
				name: 'cycle',
				hiddenName: 'cycle',
				fieldLabel: 'Turnus',								
				store: cycles_store,
				displayField: 'title',
				valueField: 'id',
				mode: 'local',
				emptyText: 'Bitte auswählen',
				forceSelection: true,
				allowBlank: false,
				anchor: '100%',
				listeners:  {
					//'focus': function(combo) {
						//combo.clearValue();
					//}
				}
			},								
			{
				xtype: 'checkbox',
				name: 'exhibition',
				fieldLabel: 'Ausstellung',
				inputValue: '1'
			},		
			{
				xtype: 'numberfield',
				name: 'expected_visitors',
				fieldLabel: 'Erwartete Besucherzahl',
				anchor: '100%'
			},
			{
				xtype: 'hidden',
				name: 'id',
				id: 'eventview_tab1_id',
				value: 0
			}
		], // items end
		
		listeners: {
				'activate': function() {
					if (debug) {
						console.log('activated events_form');
					}
					// sichtbarkeit der butons anpassen
					Ext.getCmp('eventview_bt_save').show();
					Ext.getCmp('eventview_bt_add').hide();
					Ext.getCmp('eventview_bt_edit').hide();
					Ext.getCmp('eventview_bt_delete').hide();
				}
		} // listener end		
    });
	// Ende Tab 1
	
	// Tab 2: Vorträge
	var lectures_grid = new Ext.grid.GridPanel({
		title: 'Vorträge',
		id: 'eventview_tab2',
		disabled: true,
		xtype: 'grid',
		store: lectures_store,
		bodyStyle: 'padding:0px',	
		height: 367,
		columns: [
		        {
					header: "ID", 
					dataIndex: 'id', 
					sortable: true, 
					hidden: true 
		        },
		        {
					header: "Titel", 
					dataIndex: 'title', 
					sortable: true, 
					width: 400
				},
				{ 
					header: "Highlight", 
					dataIndex: 'highlight', 
					sortable: true,
					renderer: display_boolean,
					width: 50 
				},
				{
					header: "CME Punkte", 
					dataIndex: 'cme_points', 
					sortable: true, 
					width: 75 
				} 	  						
			], // columns end
			//autoExpandColumn: 1,
			listeners: {
				'activate': function() {
					if (debug) {
						console.log('activated lectures_grid');
					}
					// sichtbarkeit der butons anpassen
					Ext.getCmp('eventview_bt_save').hide();
					Ext.getCmp('eventview_bt_add').show();
					Ext.getCmp('eventview_bt_edit').show();
					Ext.getCmp('eventview_bt_delete').show();
					
					// lectures laden
					lectures_grid.store.reload({
						params: {
							event_id: Ext.getCmp('eventview_tab1_id').getValue()
						}
					});
				}
			} // listener end
	});	
	
	// per Doppelclick Detail Dialog öffnen
	lectures_grid.on('rowdblclick', function(grid, index, e) {
		if (debug) {
			console.log('lectures_grid rowdblclick', grid.store.getAt(index).id);			
		}
		showLectureDetails(event_id, grid.store.getAt(index).id);
	});	
	// Ende Tab 2
	
	// Administrative Funktionen
	var comments_grid;
	var status_form;
	if ((role == editor_role) || (role == admin_role)) {
		if (debug) {
			console.log('creating comments_grid, status_form');
		}
		
		// Tab 3: Kommentare
		var comments_grid = new Ext.grid.GridPanel({
			title: 'Kommentare',
			id: 'eventview_tab3',
			disabled: true,
			xtype: 'grid',
			store: comments_store,
			bodyStyle: 'padding:0px',	
			height: 367,
			columns: [
		    	    {
						header: "ID", 
						dataIndex: 'id', 
						sortable: true, 
						hidden: true 
		        	},
		        	{
						header: "Datum", 
						dataIndex: 'created', 
						sortable: true, 
						width: 100
					},
					{ 
						header: "Anonym", 
						dataIndex: 'anonymous', 
						sortable: true,
						renderer: display_boolean,
						width: 50
					},
					{
						header: "Kommentar", 
						dataIndex: 'description', 
						sortable: true, 
						width: 400 
					} 	  						
				], // columns end
				//autoExpandColumn: 1,
				listeners: {
					'activate': function() {
						if (debug) {
							console.log('activated comments_grid');
						}
						// sichtbarkeit der butons anpassen
						Ext.getCmp('eventview_bt_save').hide();
						Ext.getCmp('eventview_bt_add').hide();
						Ext.getCmp('eventview_bt_edit').show();
						Ext.getCmp('eventview_bt_delete').show();
					
						// comments laden
						comments_grid.store.reload({
							params: {
								event_id: Ext.getCmp('eventview_tab1_id').getValue()
							}
						});
					}
				} // listener end
		});	
	
		// per Doppelclick Detail Dialog öffnen
		comments_grid.on('rowdblclick', function(grid, index, e) {
			if (debug) {
				console.log('comments_grid rowdblclick', grid.store.getAt(index).id);
			}
			showCommentDetails(event_id, grid.store.getAt(index).id);
		});	
		// Tab 3 Ende
		
		// Tab 4: Status
		status_form = new Ext.FormPanel({
		title: 'Status',
		id: 'eventview_tab4',
		layout: 'form',
		xtype: 'form',
		bodyStyle: 'padding:10px',
		disabled: true,
		autoHeight: true,
		items: [
			{
				xtype: 'checkbox',
				id: 'eventview_tab4_hidden',
				name: 'hidden',
				fieldLabel: 'Versteckt',
				inputValue: '1'
			},
			{
				xtype: 'checkbox',
				id: 'eventview_tab4_approved',
				name: 'approved',
				fieldLabel: 'Geprüft',
				inputValue: '1'
			}
		],
		listeners: {
			'activate': function() {
				if (debug) {
					console.log('activated status_form');
				}
					
				// sichtbarkeit der butons anpassen
				Ext.getCmp('eventview_bt_save').show();
				Ext.getCmp('eventview_bt_add').hide();
				Ext.getCmp('eventview_bt_edit').hide();
				Ext.getCmp('eventview_bt_delete').hide();
				
				// Werte laden
				var conn = new Ext.data.Connection();
				conn.request({
    				url: '/events/view',
    				method: 'GET',
    				params: {
						id: event_id
					},
    				success: function(res) {
						var resdata = Ext.util.JSON.decode(res.responseText);						
						
        				if (!resdata.success) {
        					Ext.Msg.alert('Fehler', 'Es ist ein unbekannter Fehler aufgetreten');
        				} else {
							// 'hidden' setzen
        					if (resdata.data.hidden == 1) {
        						Ext.getCmp('eventview_tab4_hidden').setValue(true);
        					}
				
							// 'approved' setzen
							if (resdata.data.admin_approved == 1) {
        						Ext.getCmp('eventview_tab4_approved').setValue(true);
        						// Checkbox sperren, da nicht vorgesehen ist, den Status wieder zu ändern
        						Ext.getCmp('eventview_tab4_approved').disable();
        					}        					

						} // else
					},
     				failure: function() {
        				Ext.Msg.alert('Fehler', 'Es ist ein unbekannter Fehler aufgetreten');
     				}
				}); // conn.request end				
				
			} // function end
		} // listener end		
    	}); // status_form end		
		// Tab 4 Ende
	}
		
	// wenn eine event_id übergeben wurde, Daten laden
	if (typeof(event_id) == 'string') {
			
		// id Feld setzen
		Ext.getCmp('eventview_tab1_id').setValue(event_id);
		
		// 2. Tab aktivieren
		lectures_grid.enable();
		
		// Admin Tabs aktivieren
		if ((role == editor_role) || (role == admin_role)) {
			comments_grid.enable();
			status_form.enable();
		}
		
		// contact und location stores filtern, damit displayField angezeigt wird
		var location = Ext.getCmp('eventview_tab1_location');
		var contact = Ext.getCmp('eventview_tab1_contact');
		
		event_form.getForm().on("actioncomplete", function() {
			location.store.on("load", function() {
				location.setValue(location.getValue());				
			});
			location.store.load({
				params: {
					id: location.getValue()
				}
			});
			
			contact.store.on("load", function() {
				contact.setValue(contact.getValue());				
			});
			contact.store.load({
				params: {
					id: contact.getValue()
				}
			});			
		});
		
		// Event Daten laden. 
		event_form.getForm().load({
			url: '/events/view',
			params: {
				id: event_id
			}
		});
		
	} // ende event daten laden
	
	var w = new Ext.Window({
		width: 600,
		title: 'Veranstaltung bearbeiten',
		id: 'eventview',
		//autoHeight: true,
		modal: true,
		height: 460,
		items: [
		{
			xtype: 'tabpanel',
			id: 'eventview_tabpanel',
			activeTab: 0,
			border: false,	
			items: [
			        event_form,					
			        lectures_grid
			]
		}
		], // items end
		buttons: [
		{
			text: 'Speichern',
			id: 'eventview_bt_save',
			handler: function() {				
				saveEvent();
			}
		},
		{
			text: 'Neu',
			id: 'eventview_bt_add',
			hidden: true,
			handler: function() {
				// workaround, weil event_id bei neuen Veranstaltungen nicht
				// korrekt gesetzt wird
				event_id = Ext.getCmp('eventview_tab1_id').getValue();
				
				showLectureDetails(event_id);				
			}
		},
		{
			text: 'Bearbeiten',
			id: 'eventview_bt_edit',
			hidden: true,
			handler: function() {
				var tp = Ext.getCmp('eventview_tabpanel');
				var tabindex = tp.items.indexOf(tp.getActiveTab());
				if (tabindex == 1) {
					// aktives tab: lectures 
					var sm = lectures_grid.getSelectionModel();
					if (sm.hasSelection()) {
						var sel = sm.getSelected();
						showLectureDetails(event_id, sel.data.id);
					} else {
						Ext.Msg.alert('Fehler', 'Bitte wählen Sie eine Zeile aus!');
					}
					
				} else if (tabindex == 2) {
					// aktives tab: comments
					var sm = comments_grid.getSelectionModel();
					if (sm.hasSelection()) {
						var sel = sm.getSelected();
						showCommentDetails(event_id, sel.data.id);
					} else {
						Ext.Msg.alert('Fehler', 'Bitte wählen Sie eine Zeile aus!');
					}					
				}
			} // handler end
		},
		{
			text: 'Löschen',
			id: 'eventview_bt_delete',
			hidden: true,
			handler: function() {
				var tp = Ext.getCmp('eventview_tabpanel');
				var tabindex = tp.items.indexOf(tp.getActiveTab());
				if (tabindex == 1) {
					// aktives tab: lectures 
					var sm = lectures_grid.getSelectionModel();
					if (sm.hasSelection()) {
						var sel = sm.getSelected();
						deleteLecture(sel.data.id);
					} else {
						Ext.Msg.alert('Fehler', 'Bitte wählen Sie eine Zeile aus!');
					}
				
				} else if (tabindex == 2) {
					// aktives tab: comments
					var sm = comments_grid.getSelectionModel();
					if (sm.hasSelection()) {
						var sel = sm.getSelected();
						deleteComment(sel.data.id);
					} else {
						Ext.Msg.alert('Fehler', 'Bitte wählen Sie eine Zeile aus!');
					}					
				}				
			} // handler end
		},		
		{
			text: 'Abbrechen',
			id: 'eventview_bt_cancel',
			handler: function() {
				w.close();
			}
		}		          
		] // buttons end

	});
	
	// Administrative Funktionen aktivieren
	if ((role == editor_role) || (role == admin_role)) {
		if (debug) {
			console.log('adding comments_grid, status_form to tabpanel');
		}
		
		w.on('beforeshow', function() {
			Ext.getCmp('eventview_tabpanel').add(comments_grid);
			Ext.getCmp('eventview_tabpanel').add(status_form);			
		});
	}
	
	w.show();

}


function showLectureDetails(event_id, lecture_id) {
	if (debug) {
		console.log('showLectureDetails(event_id, lecture_id)', event_id, lecture_id);
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('lectures_win')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}			
	
	var referees_store = new Ext.data.JsonStore({
		url: '/users/',
		baseParams: {
			referee: 1
		},
		fields: [
		         'id',
		         {
		        	 name: 'display_name', 
		        	 mapping: 'title + " " + obj.fname + " " + obj.lname + ", " + obj.city + ", " + obj.country'
		         }
		         ],
		id: 'id',
		root: 'data',
		autoLoad: false
	});	
	
	function add_referee(referee_id) {
		
		if (!referee_id) {
			return 1;
		}

		// display_name von Referenten holen
		var conn = new Ext.data.Connection();
		conn.request({
    		url: '/users/view',
    		method: 'GET',
    		params: {
				id: referee_id
			},
    		success: function(res) {
				var resdata = Ext.util.JSON.decode(res.responseText);
				//console.log('success:', resdata.success);
        		if (!resdata.success) {
        			Ext.Msg.alert('Fehler', 'Es ist ein unbekannter Fehler aufgetreten');
        		} else {
					// Datensatz hinzufügen
        			var display_name = resdata.data.title +
        				' ' +
        				resdata.data.fname +
        				' ' +
        				resdata.data.lname +
        				', ' +
        				resdata.data.city +
        				', ' +
        				resdata.data.country;
        				
					var ds_model = Ext.data.Record.create([
						'id',
						'display_name'
					]);
					var referee_grid = Ext.getCmp('lecture_form_referee_grid');
					referee_grid.getStore().insert(
						referee_grid.getStore().getCount(),
						new ds_model({
							id: referee_id,
							display_name: display_name
						})
					);
				} // else
			},
     		failure: function() {
        		Ext.Msg.alert('Fehler', 'Es ist ein unbekannter Fehler aufgetreten');
     		}
		}); // conn.request end
	}

	var lecture_form = new Ext.FormPanel({		
		bodyStyle: 'padding:10px',
		id: 'lecture_form',
		items: [		        
		{
			xtype: 'textfield',
			name: 'title',
			fieldLabel: 'Titel',
			anchor: '100%',
			allowBlank: false
		},
		{
			xtype: 'textarea',
			name: 'description',
			fieldLabel: 'Beschreibung',
			height: 100,
			anchor: '99%'
		},
		{
			xtype: 'checkbox',
			name: 'highlight',
			fieldLabel: 'Highlight'			
		},
		{
			xtype: 'numberfield',
			name: 'cme_points',
			fieldLabel: 'CME Punkte',
			anchor: '100%'
		},		
		{
			xtype: 'combo', 								
			name: 'language',
			id: 'lecture_form_language',
			hiddenName: 'language',
			fieldLabel: 'Sprache',
			store: languages_store,
			displayField: 'title',
			valueField: 'id',
			mode: 'local',
			typeAhead: true,
			triggerAction: 'all',
			minChars: 3,
			emptyText: 'Bitte auswählen',
			forceSelection: true,
			allowBlank: false,
			anchor: '100%'
		},
		{
			xtype: 'checkbox',
			name: 'translation',
			id: 'lecture_form_translation',
			fieldLabel: 'Übersetzung'
		},
  		new Ext.ux.form.LovCombo({
  			name: 'translation_language',
 			id: 'lecture_form_translation_language',
 			hiddenName: 'translation_language',
 			fieldLabel: 'Übersetzte Sprachen',
  			anchor: '100%',
 			hideOnSelect: false,
 			store: languages_store,
 			triggerAction: 'all',
 			valueField: 'id',
 			displayField: 'title',
 			mode: 'local',
 			separator: ';',
 			allowBlank: false,
			disabled: true
 		}),		
  		new Ext.ux.form.LovCombo({
  			name: 'field',
 			id: 'lecture_form_field',
 			hiddenName: 'field',
 			fieldLabel: 'Fachgebiete',
  			anchor: '100%',
 			hideOnSelect: false,
 			store: fields_store,
 			triggerAction: 'all',
 			valueField: 'id',
 			displayField: 'display_name',
 			mode: 'local',
 			separator: ';',
 			allowBlank: false
 		}),
 		// referenten combo start
		{
			layout: 'table',
			layoutConfig: {
				columnCount: 4
			},
			border: false,
			style: 'margin-bottom: 4px',		
			items: [
				{
					xtype: 'label',
					text: 'Referenten:',
					cellCls: 'x-form-item',
					width: 105
				},
				{
					xtype: 'combo', 								
					name: 'referee_search',
					//hiddenName: 'contact',
					id: 'lecture_form_referee_search',
					store: referees_store,
					displayField: 'display_name',
					valueField: 'id',
					mode: 'remote',
					typeAhead: true,
					triggerAction: 'all',
					minChars: 3,
					emptyText: 'Bitte auswählen und dann mit [+] übernehmen',
					forceSelection: true,
					width: 425
				},
				new Ext.form.MiscField({
					fieldLabel: 'MiscField',
    				id: 'spacer1',
    				width: 5,
    				value: ' '
				}),
				{
					xtype: 'button',
	  				name: 'SubItem1',	  				
	       			text: '+',
	           		width: 25,
	           		handler: function() {
						var referee_grid = Ext.getCmp('lecture_form_referee_grid');
						var referee_search = Ext.getCmp('lecture_form_referee_search');
						var referee_id = referee_search.getValue();
						
						if (referee_id) {
							add_referee(referee_id);														
						} // if referee_id
					}
	          	}
		    ]
		}, // referenten combo ende
		
		// referenten grid start
		{
			layout: 'table',
			layoutConfig: {
				columnCount: 4
			},
			border: false,
			style: 'margin-bottom: 4px',		
			items: [
				new Ext.form.MiscField({
					fieldLabel: 'MiscField',
    				id: 'spacer1',
    				width: 105,
    				value: ' '
				}),			        
				{
					xtype: 'grid',
					id: 'lecture_form_referee_grid',
					columns: [
		        		{
							header: "ID",
							dataIndex: 'id',
							hidden: true 
		        		},
		        		{
		        			header: 'Name',
		        			dataIndex: 'display_name',
		        			width: 400
		        		}
		    		], // columns end
		    		store: new Ext.data.SimpleStore({
						fields:[
						        'id',
								'display_name'
						],
						data: []
					}),
					//autoExpandColumn: 1,
		    		height: 150,
		    		width: 425,
		    		// header verstecken
					listeners: {
                		render: function(grid) {
                    		grid.getView().el.select('.x-grid3-header').setStyle('display', 'none');
                		}
            		}
				},
				new Ext.form.MiscField({
					fieldLabel: 'MiscField',
    				id: 'spacer2',
    				width: 5,
    				value: ' '
				}),
				{
					xtype: 'button',
	  				name: 'SubItem1',	  				
	       			text: '-',
	           		width: 25,
	           		handler: function() {
						var referee_grid = Ext.getCmp('lecture_form_referee_grid');
						var sm = referee_grid.getSelectionModel();
						var sel = sm.getSelected();
						if (sm.hasSelection()) {
							referee_grid.getStore().remove(sel);
						} else {
							Ext.Msg.alert('Fehler', 'Bitte wählen Sie eine Zeile aus!');
						}
					}
	          	}				
				
			] // items end
		},  		
		// referenten grid ende
		{
			xtype: 'hidden',
			name: 'id',
			id: 'lecture_form_id',
			value: lecture_id
		},
		{
			xtype: 'hidden',
			name: 'referee',
			id: 'lecture_form_referee'
		},		
		{
			xtype: 'hidden',
			name: 'event_id',
			id: 'lecture_form_event_id',
			value: event_id
		}
		], // items end
		
		listeners: {
			'beforeaction': function(f, a) {
				// hidden field 'referee' mit allen id's im referee_grid füllen
				//console.log('beforeaction', a.type);
				if (a.type == 'submit') {
					var referee = Ext.getCmp('lecture_form_referee');
					var referee_grid = Ext.getCmp('lecture_form_referee_grid');
					var ids = '';
					referee_grid.getStore().each(
						function(r) {
							if (ids.length) {
								ids = ids + ',';
							}
							ids = ids + r.data.id;
						}
					);
					
					referee.setValue(ids);
								
					// max. 5 Fachgebiete auswählbar
					var field = Ext.getCmp('lecture_form_field').getValue();					
					var field_value = field.split(";");
					if (field_value.length > 5) {
						Ext.Msg.alert('Fehler', 'Es können maximal 5 Fachgebiete ausgewählt werden!');
						return false;
					}
					
					// max. 5 übersetzte Sprachen auswählbar
					var translation_language = Ext.getCmp('lecture_form_translation_language').getValue();					
					var translation_language_value = translation_language.split(";");
					if (translation_language_value.length > 5) {
						Ext.Msg.alert('Fehler', 'Es können maximal 5 übersetzte Sprachen ausgewählt werden!');
						return false;
					}					
				
				}
			}
		}, 
		
		buttons: [
		{
			text: 'Speichern',
			handler: function() {
				var url = '/lectures/add';
				if (lecture_id) {
					url = '/lectures/edit';
				}

				lecture_form.getForm().submit({
					url: url,					
					success: function(f, a) {						
						// nur bei 'add': lecture_id übernehmen
						if (!lecture_id) {
							lecture_id = a.result.id;
							Ext.getCmp('lecture_form_id').setValue(lecture_id);
						}
												
						// Fenster schliessen
						w.close();
						
						// ...und lectures_grid neu laden
						var lectures_grid = Ext.getCmp('eventview_tab2');
						lectures_grid.store.reload({
							params: {
								event_id: Ext.getCmp('eventview_tab1_id').getValue()
							}
						});
						
					},
					failure: function(f, a) {
						if (a.result) {
							Ext.Msg.alert('Fehler', a.result.errormsg); 							
						} else {
							Ext.Msg.alert('Fehler', 'Es ist ein Fehler aufgetreten. Bitte füllen Sie alle rot markierten Felder aus.');
						}	
					}					
				});
				
			}
		},
		{
			text: 'Abbrechen',	
			handler: function() {
				w.close();
			}
		}		          
		] // buttons end		
	
	});
	
	// Checkbox 'translation' überwachen und 'translation_language' ggf.
	// (de)aktivieren
	var translation = Ext.getCmp('lecture_form_translation');
	translation.on('check', function() {
		if (debug) {
			console.log('lecture_form_translation changed: ', translation.getValue());
		}
	
		if (translation.getValue()) {	
			Ext.getCmp('lecture_form_translation_language').enable();
		} else {
			Ext.getCmp('lecture_form_translation_language').disable();
		}
	});	
	
	// wenn eine lecture_id übergeben wurde, Daten laden
	if (typeof(lecture_id) == 'string') {
		if (debug) {
			console.log('got lecture_id ', lecture_id);
		}
		
		// id Feld setzen
		Ext.getCmp('lecture_form_id').setValue(lecture_id);
		
		// Sprache setzen, wenn Store geladen ist, damit displayField angezeigt wird
		//languages_store.on("load", function() {
		//	var language = Ext.getCmp('lecture_form_language');
		//	language.setValue(language.getValue());		
		//});
				
		// Referenten in Tabelle übernehmen
		lecture_form.getForm().on("actioncomplete", function() {
			var referee = Ext.getCmp('lecture_form_referee');
			var ids = referee.getValue().split(',');
			for (var i = 0; i < ids.length; ++i) {
				add_referee(ids[i]);
			}
		});
		
		// Lecture Daten laden 
		lecture_form.getForm().load({
			url: '/lectures/view',
			params: {
				id: lecture_id
			},
			failure: function() {
        		Ext.Msg.alert('Fehler', 'Datensatz konnte nicht geladen werden.');
     		}
		});
		
	} // ende lecture daten laden
	else {
		if (debug) {
			console.log('no lecture_id, clearing lecture_form_field');
		}
		// evtl. gesetzte Checkboxen zurücksetzen
		Ext.getCmp('lecture_form_field').clearValue();
		Ext.getCmp('lecture_form_translation_language').clearValue();
	}
	
	var w = new Ext.Window({
		id: 'lectures_win',
		width: 600,
		title: 'Vortrag bearbeiten',
		border: false,
		autoHeight: true,
		items: [
		        lecture_form
		       ]
	});
	
	w.show();	
}


function deleteLecture(lecture_id) {
	if (debug) {
		console.log('deleteLecture(lecture_id)', lecture_id);
	}
	
	Ext.Msg.confirm(
		'Vortrag löschen', 
		'Möchten Sie diesen Vortrag wirklich löschen?',
		function(btn, text) {
			//console.log('btn', btn);
			if (btn == 'yes') {
				// löschen
				var conn = new Ext.data.Connection();
				conn.request({
    				url: '/lectures/delete',
    				method: 'POST',
    				params: {
						id: lecture_id
					},
    				success: function(res) {
						var resdata = Ext.util.JSON.decode(res.responseText);
						//console.log('success:', resdata.success);
        				if (!resdata.success) {
        					Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gelöscht werden.');
        				} else {
        					// lectures_grid neu laden
							//console.log('success, reload lectures_grid');
							Ext.getCmp('eventview_tab2').store.removeAll();
							Ext.getCmp('eventview_tab2').store.reload({
							params: {
								event_id: Ext.getCmp('eventview_tab1_id').getValue()
							}
						});
        				}
					},
     				failure: function() {
        				Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gelöscht werden.');
     				}
				}); // conn.request end
			} // if btn end
		} // function end
	); // Msg.confirm end
}


function deleteComment(comment_id) {
	if (debug) {
		console.log('deleteComment(comment_id)', comment_id);
	}
	
	Ext.Msg.confirm(
		'Kommentar löschen', 
		'Möchten Sie diesen Kommentar wirklich löschen?',
		function(btn, text) {
			//console.log('btn', btn);
			if (btn == 'yes') {
				// löschen
				var conn = new Ext.data.Connection();
				conn.request({
    				url: '/comments/delete',
    				method: 'POST',
    				params: {
						id: comment_id
					},
    				success: function(res) {
						var resdata = Ext.util.JSON.decode(res.responseText);
						//console.log('success:', resdata.success);
        				if (!resdata.success) {
        					Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gelöscht werden.');
        				} else {
        					// lectures_grid neu laden
							//console.log('success, reload lectures_grid');
							Ext.getCmp('eventview_tab3').store.removeAll();
							Ext.getCmp('eventview_tab3').store.reload({
							params: {
								event_id: Ext.getCmp('eventview_tab1_id').getValue()
							}
						});
        				}
					},
     				failure: function() {
        				Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gelöscht werden.');
     				}
				}); // conn.request end
			} // if btn end
		} // function end
	); // Msg.confirm end
}


function showCommentDetails(event_id, comment_id) {
	if (debug) {
		console.log('showCommentDetails(event_id, comment_id)', event_id, comment_id);
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('comments_win')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}		

	var comment_form = new Ext.FormPanel({		
		bodyStyle: 'padding:10px',
		id: 'comment_form',
		items: [ 
		{
			xtype: 'textarea',
			name: 'description',
			fieldLabel: 'Kommentar',
			height: 250,
			anchor: '99%'
		},
		{
			xtype: 'checkbox',
			name: 'anonymous',
			fieldLabel: 'Anonym'			
		},
		{
			xtype: 'hidden',
			name: 'id',
			id: 'comment_form_id',
			value: comment_id
		},
		{
			xtype: 'hidden',
			name: 'event_id',
			id: 'comment_form_event_id',
			value: event_id
		}
		], // items end
		
		buttons: [
		{
			text: 'Speichern',
			handler: function() {
				var url = '/comments/add';
				if (comment_id) {
					url = '/comments/edit';
				}
				comment_form.getForm().submit({
					url: url,					
					success: function(f, a) {						
						// nur bei 'add': comment_id übernehmen
						if (!comment_id) {
							comment_id = a.result.id;
							Ext.getCmp('comment_form_id').setValue(comment_id);
						}
												
						// Fenster schliessen
						w.close();
						
						// ...und lectures_grid neu laden
						var comments_grid = Ext.getCmp('eventview_tab3');
						comments_grid.store.reload({
							params: {
								event_id: Ext.getCmp('eventview_tab1_id').getValue()
							}
						});
						
					},
					failure: function(f, a) {
						if (a.result) {
							Ext.Msg.alert('Fehler', a.result.errormsg); 							
						} else {
							Ext.Msg.alert('Fehler', 'Es ist ein Fehler aufgetreten. Bitte füllen Sie alle rot markierten Felder aus.');
						}	
					}					
				});
				
			}
		},
		{
			text: 'Abbrechen',	
			handler: function() {
				w.close();
			}
		}		          
		] // buttons end		
	
	});
	
	// wenn eine comment_id übergeben wurde, Daten laden
	if (typeof(comment_id) == 'string') {
		
		// id Feld setzen
		Ext.getCmp('comment_form_id').setValue(comment_id);
					
		// Daten laden. 
		comment_form.getForm().load({
			url: '/comments/view',
			params: {
				id: comment_id
			}
		});
		
	} // ende lecture daten laden	
	
	var w = new Ext.Window({
		id: 'comments_win',
		width: 600,
		title: 'Kommentar bearbeiten',
		border: false,
		autoHeight: true,
		items: [
		        comment_form
		       ]
	});
	
	w.show();	
}


function saveEvent() {
	var events_form = Ext.getCmp('eventview_tab1').getForm();
	var lectures_grid = Ext.getCmp('eventview_tab2');
	var tp = Ext.getCmp('eventview_tabpanel');
	var tabindex = tp.items.indexOf(tp.getActiveTab());
	
	if (debug) {
		console.log('saveEvent()');
		console.log('tabindex', tabindex);
	}
	
	if (tabindex === 0) {		
		// Event speichern
		var event_id = Ext.getCmp('eventview_tab1_id').getValue();
		if (debug) {
			console.log('event_id:', event_id);
		}
			
		// Datumsfelder nach YYYY-MM-DD formatieren
		var date_begin = Ext.getCmp('eventview_tab1_date_begin');
		var date_end = Ext.getCmp('eventview_tab1_date_end');
		var dr = Ext.util.Format.dateRenderer('Y-m-d');
		date_begin.setRawValue(dr(date_begin.getValue()));
		date_end.setRawValue(dr(date_end.getValue()));

		if (event_id == 0) {
			// neuen Datensatz anlegen
			events_form.submit({
				url: '/events/add',
				success: function(f, a) {
					event_id = a.result.id;
					if (debug) {
						console.log('new event_id:', event_id);
					}
					Ext.getCmp('eventview_tab1_id').setValue(event_id);
					
					// Datumsfelder zurücksetzen wg. Formatierung
					date_begin.setValue(date_begin.getValue());
					date_end.setValue(date_end.getValue());
										
					// zum Tab 'Vorträge' springen
					lectures_grid.enable();
					tp.activate(1);
					
					// Admin Tabs aktivieren
					if ((role == editor_role) || (role == admin_role)) {
						Ext.getCmp('eventview_tab4').enable();
					}
				},
				failure: function(f, a) {
					if (a.result) {
						Ext.Msg.alert('Fehler', a.result.errormsg); 							
					} else {
						Ext.Msg.alert('Fehler', 'Es ist ein Fehler aufgetreten. Bitte füllen Sie alle rot markierten Felder aus.');
					}
				}
				
			});
			
		} else {
			// vorhandenen Datensatz speichern
			events_form.submit({
				url: '/events/edit',
				success: function(f, a) {
					if (debug) {
						console.log('event_id', event_id, 'saved');
					}
					
					// Datumsfelder zurücksetzen wg. Formatierung
					date_begin.setValue(date_begin.getValue());
					date_end.setValue(date_end.getValue());
					
					// zum Tab 'Vorträge' springen
					tp.activate(1);
				},
				failure: function(f, a) {
					if (a.result) {
						Ext.Msg.alert('Fehler', a.result.errormsg); 							
					} else {
						Ext.Msg.alert('Fehler', 'Es ist ein Fehler aufgetreten. Bitte füllen Sie alle rot markierten Felder aus.');
					}					
				}
			});
		}
		
		
	} else if (tabindex == 3) {
		// Status setzen
		var url;
		if (Ext.getCmp('eventview_tab4_hidden').checked) {
			url = '/events/disable';
		} else {
			url = '/events/enable';
		}
		var conn = new Ext.data.Connection();
		conn.request({
    		url: url,
    		method: 'POST',
    		params: {
				id: Ext.getCmp('eventview_tab1_id').getValue()
			},
    		success: function(res) {
				var resdata = Ext.util.JSON.decode(res.responseText);
        		if (!resdata.success) {
        			Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gespeichert werden.');
        		}
			},
     		failure: function() {
        		Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gespeichert werden.');
     		}
		}); // conn.request end
		
		// approved setzen		
		if (Ext.getCmp('eventview_tab4_approved').checked) {
			url = '/events/approve';
			// Checkbox sperren, da nicht vorgesehen ist, den Status wieder zu ändern
			Ext.getCmp('eventview_tab4_approved').disable();
		} else {
			url = '/events/view';
		}
		conn.request({
    		url: url,
    		method: 'POST',
    		params: {
				id: Ext.getCmp('eventview_tab1_id').getValue()
			},
    		success: function(res) {
				var resdata = Ext.util.JSON.decode(res.responseText);
        		if (!resdata.success) {
        			Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gespeichert werden.');
        		}
			},
     		failure: function() {
        		Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gespeichert werden.');
     		}
		}); // conn.request end
		
		// Fenster schliessen
		Ext.getCmp('eventview').close();
		
	}

}


function saveUser() {
	var user_form = Ext.getCmp('userview_tab1').getForm();
	
	if (debug) {
		console.log('saveUser()');
	}

	// Benutzer speichern
	var user_id = Ext.getCmp('userview_tab1_id').getValue();

	if (user_id === 0) {


	} else {
		// vorhandenen Datensatz speichern
		user_form.submit({
			url: '/users/edit',
		success: function(f, a) {
			if (debug) {
				console.log('user_id', user_id, 'saved');
			}
			// rolle setzen
			var conn = new Ext.data.Connection();
			conn.request({
    			url: '/users/change_role',
    			method: 'POST',
    			params: {
					id: user_id,
					role: Ext.getCmp('userview_tab1_role').getValue()
				},
    			success: function(res) {
					var resdata = Ext.util.JSON.decode(res.responseText);
					//console.log('success:', resdata.success);
       				if (!resdata.success) {
       					Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gespeichert werden.');
       				}
				},
    			failure: function() {
       				Ext.Msg.alert('Fehler', 'Datensatz konnte nicht gelöscht werden.');
    			}
			}); // conn.request end
			
			Ext.getCmp('userview').close();
		},
		failure: function(f, a) {
			if (a.result) {
				Ext.Msg.alert('Fehler', a.result.errormsg); 							
			} else {
				Ext.Msg.alert('Fehler', 'Es ist ein Fehler aufgetreten. Bitte füllen Sie alle rot markierten Felder aus.');
			}					
		}
		});
	}

}


function showCreateContact() {
	if (debug) {
		console.log('showCreateContact()');
	}

	showContactDetails();
}


function showContactDetails(contact_id) {
	if (debug) {
		console.log('showContactDetails(contact_id), ' + contact_id);
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('contacts_win')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}	
	
	var contact_form = new Ext.FormPanel({		
		bodyStyle: 'padding:10px',
		id: 'contact_form',
		items: [		        
		{
			xtype: 'textfield',
			name: 'company',
			fieldLabel: 'Firma',
			anchor: '100%',
			allowBlank: false
		},		
		{
			xtype: 'textfield',
			name: 'company2',
			fieldLabel: 'Firma2',
			anchor: '100%'
		},		
		{
			xtype: 'textfield',
			name: 'department',
			fieldLabel: 'Abteilung',
			anchor: '100%'
		},		
		{
			xtype: 'textfield', 
			name: 'address',
			fieldLabel: 'Anschrift',
			anchor: '100%',
			allowBlank: false
		},		
		{
			xtype: 'textfield', 
			name: 'address2',
			fieldLabel: 'Anschrift2',
			anchor: '100%'
		},
		{
			xtype: 'textfield',
			name: 'zip',
			fieldLabel: 'PLZ',
			anchor: '100%',
			allowBlank: false
		},		
		{
			xtype: 'textfield',
			name: 'city',
			fieldLabel: 'Ort',
			anchor: '100%',
			allowBlank: false
		},
		{
			xtype: 'combo', 								
			name: 'country',
			id: 'contact_form_country',
			hiddenName: 'country',
			fieldLabel: 'Land',
			store: countries_store,
			displayField: 'title',
			valueField: 'code',
			mode: 'remote',
			typeAhead: true,
			triggerAction: 'all',
			minChars: 3,
			emptyText: 'Bitte auswählen',
			forceSelection: true,
			allowBlank: false,
			anchor: '100%'
		},
		{
			xtype: 'textfield', 
			name: 'phone',
			id: 'contact_form_phone',
			fieldLabel: 'Telefon',
			anchor: '100%',
			vtype: 'intphone'
		},	
		{
			xtype: 'textfield',
			name: 'fax',
			id: 'contact_form_fax',
			fieldLabel: 'Fax',
			anchor: '100%',
			vtype: 'intphone'
		},	
		{
			xtype: 'textfield', 
			name: 'email',
			fieldLabel: 'Email',
			anchor: '100%',
			vtype: 'email',
			allowBlank: false
		},
		{
			xtype: 'textfield', 
			name: 'website_url',
			fieldLabel: 'Website',
			anchor: '100%',
			vtype: 'url'
		},
		{
			xtype: 'hidden', 
			name: 'id',
			id: 'contactview_id',
			value: 0
		}		
		], // items end
		
		buttons: [
		{
			text: 'Speichern',
			handler: function() {
				var url;
				var contact = Ext.getCmp('contactview_id');
								
				if (contact.getValue() != '0') {
					url = '/contacts/edit';
				} else {
					url = '/contacts/add';
				}
				contact_form.getForm().submit({
					url: url,
					success: function(f, a) {
						if (debug) {
							console.log('new contact_id', a.result.id);
						}

						// falls Event Fenster offen ist
						// neuen Datensatz in combobox auswählen
						if (Ext.getCmp('eventview_tab1')) {
							var contact = Ext.getCmp('eventview_tab1').getForm().findField('contact');
							contact.store.on("load", function() {
								contact.setValue(a.result.id);							
							});

							contact.store.load({
								params: {
								id: a.result.id
							}
							});
						}
						
						w.close();					
					},
					failure: function(f, a) {
						if (a.result) {
							Ext.Msg.alert('Fehler', a.result.errormsg); 							
						} else {
							Ext.Msg.alert('Fehler', 'Es ist ein Fehler aufgetreten. Bitte füllen Sie alle rot markierten Felder aus.');
						}					
					}					
				});
				
			}
		},
		{
			text: 'Abbrechen',	
			handler: function() {
				w.close();
			}
		}		          
		] // buttons end		
	
	});
	
	// Vorwahl bei phone & fax Feldern ergänzen
	var country = Ext.getCmp('contact_form_country');
	var phone = Ext.getCmp('contact_form_phone');
	var fax = Ext.getCmp('contact_form_fax');
	country.on("select", function() {
		var cc = country.getValue();
		if (debug) {
			console.log('country selected: ', cc);
		}		

		var prefix = country.store.getById(cc).get('prefix') + '-';
		if (debug) {
			console.log('country prefix: ', prefix);
		}
		
		if (!phone.getValue()) {
			phone.setValue(prefix);
		}
		if (!fax.getValue()) {
			fax.setValue(prefix);
		}		
	});	
	
	// wenn eine contact_id übergeben wurde, Daten laden
	if (typeof(contact_id) == 'string') {
			
		// id Feld setzen
		Ext.getCmp('contactview_id').setValue(contact_id);		
		
		// Event Daten laden. 
		contact_form.getForm().load({
			url: '/contacts/view',
			params: {
				id: contact_id
			}
		});
		
	} // ende event daten laden	
	
	var w = new Ext.Window({
		id: 'contacts_win',
		width: 400,
		title: 'Veranstalter erstellen',
		border: false,
		autoHeight: true,
		items: [
		        contact_form
		       ]
	});
	
	w.show();
}


function showCreateLocation() {
	if (debug) {
		console.log('showCreateLocation()');
	}

	showLocationDetails();
}


function showLocationDetails(location_id) {
	if (debug) {
		console.log('showLocationDetails()');
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('locations_win')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}	

	var location_form = new Ext.FormPanel({		
		bodyStyle: 'padding:10px',
		id: 'location_form',
		items: [		        
		{
			xtype: 'textfield',
			name: 'title',
			fieldLabel: 'Titel',
			anchor: '100%',
			allowBlank: false
		},
		{
			xtype: 'textfield', 
			name: 'address',
			fieldLabel: 'Anschrift',
			anchor: '100%',
			allowBlank: false
		},
		{
			xtype: 'textfield',
			name: 'address2',
			fieldLabel: 'Anschrift2',
			anchor: '100%'
		},
		{
			xtype: 'textfield',
			name: 'zip',
			fieldLabel: 'PLZ',
			anchor: '100%',
			allowBlank: false
		},		
		{
			xtype: 'textfield',
			name: 'city',
			fieldLabel: 'Ort',
			anchor: '100%',
			allowBlank: false
		},
		{
			xtype: 'combo', 								
			name: 'country',
			hiddenName: 'country',
			fieldLabel: 'Land',
			store: countries_store,
			displayField: 'title',
			valueField: 'code',
			mode: 'remote',
			typeAhead: true,
			triggerAction: 'all',
			minChars: 3,
			emptyText: 'Bitte auswählen',
			forceSelection: true,
			allowBlank: false,
			anchor: '100%'
		},
		{
			xtype: 'hidden',
			name: 'id',
			id: 'location_form_id',
			value: 0
		}
		], // items end
		
		buttons: [
		{
			text: 'Speichern',
			handler: function() {
				var url;
				var location = Ext.getCmp('location_form_id');

				if (location.getValue() != '0') {
					url = '/locations/edit';
				} else {
					url = '/locations/add';
				}			
				location_form.getForm().submit({
					url: url,
					success: function(f, a) {
						if (debug) {
							console.log('new event_id', a.result.id);
						}

						// falls Event Fenster offen ist
						// neuen Datensatz in combobox auswählen
						if (Ext.getCmp('eventview_tab1')) {
							var location = Ext.getCmp('eventview_tab1').getForm().findField('location');
							location.store.on("load", function() {
								location.setValue(a.result.id);							
							});

							location.store.load({
								params: {
								id: a.result.id
							}
							});
						}
						w.close();					
					},
					failure: function(f, a) {
						if (a.result) {
							Ext.Msg.alert('Fehler', a.result.errormsg); 							
						} else {
							Ext.Msg.alert('Fehler', 'Es ist ein Fehler aufgetreten. Bitte füllen Sie alle rot markierten Felder aus.');
						}	
					}					
				});
				
			}
		},
		{
			text: 'Abbrechen',	
			handler: function() {
				w.close();
			}
		}		          
		] // buttons end		
	
	});

	// wenn eine location_id übergeben wurde, Daten laden
	if (typeof(location_id) == 'string') {
			
		// id Feld setzen
		Ext.getCmp('location_form_id').setValue(location_id);		
		
		// Event Daten laden. 
		location_form.getForm().load({
			url: '/locations/view',
			params: {
				id: location_id
			}
		});
		
	} // ende location daten laden	
	
	var w = new Ext.Window({
		id: 'locations_win',
		width: 400,
		title: 'Ort erstellen',
		border: false,
		autoHeight: true,
		items: [
		        location_form
		       ]
	});
	
	w.show();

}


function showEvents() {
	if (debug) {
		console.log('showEvents()');
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('eventsview')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}
	
	var events_store = new Ext.data.JsonStore({
		url: '/events/',
		fields: [
		         'id',
		         {
		        	 name: 'date_begin',
		        	 type: 'date',
		        	 dateFormat: 'Y-m-d'
		         },
		         {
		        	 name: 'date_end',
		        	 type: 'date',
		        	 dateFormat: 'Y-m-d'
		         },
		         'title', 
		         'location',
		         'location_name'
		         ],
		id: 'id',
		root: 'data',
		totalProperty: 'results',
		autoLoad: true
	});
	
	// Schnellsuche berücksichtigen
	events_store.on('beforeload', function() {
		// store leeren, falls bei load() keine Datensätze kommen
		events_store.removeAll();
		// per Default keine hist. Daten anzeigen
		var now = new Date();
		var date_begin = now.format('Y-m-d');
		if (Ext.getCmp('bt_hist_data').checked) {
			date_begin = '';
		}
		// nur Admins und Redakteure dürfen alle Events sehen	
		var created_by = '';
		if ((role == user_role) || (role == referee_role)) {			
			created_by = user_id;
		}
		// 'Nur neue Datensätze anzeigen' berücksichtigen
		var approved = '';
		if (Ext.getCmp('bt_tobeapproved_data').checked) {
			approved = '0';
		}		
		
  		events_store.baseParams = {
    		'limit': 22,
    		'query': Ext.getCmp('query_field').getValue(),
    		'date_begin': date_begin,
    		'created_by': created_by,
    		'approved': approved
  		};
	});
	
	function display_date(val, x, store) {
		var dr = Ext.util.Format.dateRenderer('d.m.Y');
		var out = dr(val);
		var date_end = dr(store.data.date_end); 
		if (date_end != out) {
			out +=  ' - ' + date_end;
		}
		return out;
	}
	
	var events_grid = new Ext.grid.GridPanel({
		frame: false,
		id: 'events_grid',
		height: 550,
		store: events_store,
		columns: [
		{			
			header: 'ID',
			dataIndex: 'id',
			hidden: true
		},		          
		{			
			header: 'Datum',
			dataIndex: 'date_begin',
			renderer: display_date,
			width: 140
		},
		{
			header: 'Titel',
			dataIndex: 'title',
			width: 300
		},
		{
			header: 'Veranstaltungsort',
			dataIndex: 'location_name',
			width: 300
		}		
		], // columns end
		//autoExpandColumn: 2,
		bbar: new Ext.PagingToolbar({
			pageSize: 22,
			store: events_store
		}),
		tbar: [
			{
				text: 'Bearbeiten',
				handler: function() {
					var sm = events_grid.getSelectionModel();
					if (sm.hasSelection()) {
						var sel = sm.getSelected();
						showEventDetails(sel.data.id); 
					} else {
						Ext.Msg.alert('Fehler', 'Bitte wählen Sie eine Zeile aus!');
					}
				}
			},
			{
				xtype: 'tbbutton',
				text: 'Optionen',
				menu: {
					items: [
						{
							text: 'Historische Datensätze anzeigen',
							id: 'bt_hist_data',							
							checked: false,
							checkHandler: function() {
								events_store.load();
							}
						},
						{
							text: 'Nur unbestätigte Datensätze anzeigen',
							id: 'bt_tobeapproved_data',							
							checked: false,
							hidden: true,
							checkHandler: function() {
								events_store.load();
							}
						}						
					]
				}
				
			},			
			{
				xtype: 'tbfill'
			},						
			{
				xtype: 'textfield',
				name: 'query',
				id: 'query_field',
    			emptyText: 'Schnellsuche',
   			  	enableKeyEvents: true,
  				listeners: {
    				"keydown": function(field, event) {
						// Schnellsuche
      					if (event.getKey() == event.ENTER) {     						     							
      						events_store.load();      					
      					}
    				}
  				}

			},
			{	
				xtype: 'tbbutton',
				text: 'Clear',
				handler: function() {
					// Filter entfernen
					Ext.getCmp('query_field').setValue('');
					events_store.load();
				}
			}
	
		] // tbar end			
	
	});
	
	// per Doppelclick Detail Dialog öffnen
	events_grid.on('rowdblclick', function(grid, index, e) {
		if (debug) {
			console.log('rowdblclick', grid.store.getAt(index).id);
		}
		showEventDetails(grid.store.getAt(index).id);
	});
	
	var w = new Ext.Window({
		width: 800,
		title: 'Veranstaltungen',
		id: 'eventsview',		
		autoHeight: true,
		border: false,
		items: [
			events_grid
		]
	});

	w.on('beforeshow', function() {
		// Funktionen entsprechend der Rolle einblenden
		if (role == admin_role) {
			Ext.getCmp('bt_tobeapproved_data').show();
		}
		if (role == editor_role) {
			Ext.getCmp('bt_tobeapproved_data').show();
		}
	});

	w.show();
	
}


function logout() {
	if (debug) {
		console.log('logout()');
	}
	
	var conn = new Ext.data.Connection();
	conn.request({
    	url: '/users/logout',
    	method: 'POST',    	
    	success: function(res) {
			// alle offenen Fenster schliessen
			Ext.WindowMgr.each(function(win) {
  				win.close();
			});
			
			// user_id und role zurücksetzen
			user_id = '';
			role = '';
			
			// Statuszeile aktualisieren
			Ext.getCmp('statusbar').clearStatus({useDefaults:true});
			
			// Alle Tasks stoppen
			Ext.TaskMgr.stopAll();
			
			// Login Dialog anzeigen
			//showLoginDialog();
			document.location = frontend_url;
			
    	},
     	failure: function() {
        	Ext.Msg.alert('Status', 'An unknown error occurred. Please try again later.');
     	}
	});
}


function showUsers() {
	if (debug) {
		console.log('showUsers()');
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('usersview')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}
	
	var users_store = new Ext.data.JsonStore({
		url: '/users/',
		fields: [
		         'id',
		         'fname',
		         'lname',
		         'title',
		         'company',
		         'address',
		         'zip',
		         'city',
		         'country',
		         'email'
		         ],
		id: 'id',
		root: 'data',
		totalProperty: 'results',
		autoLoad: true
	});
	
	// Schnellsuche berücksichtigen
	users_store.on('beforeload', function() {
		// store leeren, falls bei load() keine Datensätze kommen
		users_store.removeAll();
		// 'Nur aktive Benutzer anzeigen' berücksichtigen
		var active = '';
		if (Ext.getCmp('bt_active_users').checked) {
			active = '1';
		}		
		
  		users_store.baseParams = {
    		'limit': 22,
    		'query': Ext.getCmp('query_field').getValue(),
    		'active': active
  		};
	});
	
	var users_grid = new Ext.grid.GridPanel({
		frame: false,
		id: 'users_grid',
		height: 550,
		store: users_store,
		columns: [
		{			
			header: 'ID',
			dataIndex: 'id',
			hidden: true
		},		          
		{			
			header: 'Vorname',
			dataIndex: 'fname'
		},
		{			
			header: 'Nachname',
			dataIndex: 'lname'
		},
		{			
			header: 'Titel',
			dataIndex: 'title',
			width: 75
		},
		{			
			header: 'Firma',
			dataIndex: 'company'
		},
		{			
			header: 'Anschrift',
			dataIndex: 'address'
		},
		{			
			header: 'PLZ',
			dataIndex: 'zip',
			width: 50
		},
		{			
			header: 'Ort',
			dataIndex: 'city'	
		},
		{			
			header: 'Land',
			dataIndex: 'country',
			width: 50
		},
		{			
			header: 'Email',
			dataIndex: 'email'	
		}
		
		], // columns end
		//autoExpandColumn: 2,
		bbar: new Ext.PagingToolbar({
			pageSize: 22,
			store: users_store
		}),
		tbar: [
			{
				text: 'Bearbeiten',
				handler: function() {
					var sm = users_grid.getSelectionModel();
					if (sm.hasSelection()) {
						var sel = sm.getSelected();
						showUserDetails(sel.data.id); 
					} else {
						Ext.Msg.alert('Fehler', 'Bitte wählen Sie eine Zeile aus!');
					}
				}
			},	
			{
				text: 'Löschen',
				disabled: true
			},
			{
				xtype: 'tbbutton',
				text: 'Optionen',
				menu: {
					items: [
						{
							text: 'Nur aktive Benutzer anzeigen',
							id: 'bt_active_users',							
							checked: true,
							checkHandler: function() {
								users_store.load();
							}
						}						
					]
				}
				
			},			
			{
				xtype: 'tbfill'
			},						
			{
				xtype: 'textfield',
				name: 'query',
				id: 'query_field',
    			emptyText: 'Schnellsuche',
   			  	enableKeyEvents: true,
  				listeners: {
    				"keydown": function(field, event) {
						// Schnellsuche
      					if (event.getKey() == event.ENTER) {     						     							
      						users_store.load();      					
      					}
    				}
  				}

			},
			{	
				xtype: 'tbbutton',
				text: 'Clear',
				handler: function() {
					// Filter entfernen
					Ext.getCmp('query_field').setValue('');
					users_store.load();
				}
			}
	
		] // tbar end			
	
	});
	
	// per Doppelclick Detail Dialog öffnen
	users_grid.on('rowdblclick', function(grid, index, e) {
		if (debug) {
			console.log('rowdblclick', grid.store.getAt(index).id);
		}
		showUserDetails(grid.store.getAt(index).id);
	});
	
	var w = new Ext.Window({
		width: 800,
		title: 'Benutzerverwaltung',
		id: 'usersview',		
		autoHeight: true,
		border: false,
		items: [
			users_grid
		]
	});

	w.show();
	
}


function showUserDetails(user_id) {	
	if (debug) {
		console.log('showUserDetails(user_id)', user_id);
	}

	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('userview')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}
	
	// Tab 1: Event Daten
	var user_form = new Ext.FormPanel({
		title: 'Benutzer',
		id: 'userview_tab1',
		layout: 'form',
		xtype: 'form',
		bodyStyle: 'padding:10px',
		autoHeight: true,
		border: false,
		items: [	
			{
				xtype: 'textfield',
				name: 'fname',
				fieldLabel: 'Vorname',
				anchor: '100%'
			},
			{
				xtype: 'textfield',
				name: 'lname',
				fieldLabel: 'Nachname',
				anchor: '100%'
			},
			{
				xtype: 'textfield',
				name: 'title',
				fieldLabel: 'Titel',
				anchor: '100%'
			},
			{
				xtype: 'textfield',
				name: 'company',
				fieldLabel: 'Firma',
				anchor: '100%'
			},
			{
				xtype: 'textfield',
				name: 'company2',
				fieldLabel: 'Firma2',
				anchor: '100%'
			},
			{
				xtype: 'textfield',
				name: 'department',
				fieldLabel: 'Abteilung',
				anchor: '100%'
			},
			{
				xtype: 'textfield',
				name: 'address',
				fieldLabel: 'Anschrift',
				anchor: '100%'
			},
			{
				xtype: 'textfield',
				name: 'address2',
				fieldLabel: 'Anschrift2',
				anchor: '100%'
			},
			{
				xtype: 'combo', 								
				name: 'country',
				id: 'userview_tab1_country',
				hiddenName: 'country',
				fieldLabel: 'Land',
				store: countries_store,
				displayField: 'title',
				valueField: 'code',
				mode: 'remote',
				typeAhead: true,
				triggerAction: 'all',
				minChars: 3,
				emptyText: 'Bitte auswählen',
				forceSelection: true,
				allowBlank: false,
				anchor: '100%'
			},			
			{
				xtype: 'textfield',
				name: 'zip',
				id: 'userview_tab1_zip',
				fieldLabel: 'PLZ',
				anchor: '100%',
				enableKeyEvents: true
			},
			{
				xtype: 'textfield',
				name: 'city',
				id: 'userview_tab1_city',
				fieldLabel: 'Ort',
				anchor: '100%'
			},
			{
				xtype: 'textfield',
				name: 'phone',
				id: 'userview_tab1_phone',
				fieldLabel: 'Telefon',
				anchor: '100%',
				vtype: 'intphone'
			},
			{
				xtype: 'textfield',
				name: 'fax',
				id: 'userview_tab1_fax',
				fieldLabel: 'Fax',
				anchor: '100%',
				vtype: 'intphone'
			},
			{
				xtype: 'textfield',
				name: 'email',
				fieldLabel: 'Email',
				anchor: '100%',
				vtype: 'email'
			},
			{
				xtype: 'textfield',
				name: 'website_url',
				fieldLabel: 'Website',
				anchor: '100%',
				vtype: 'url'
			},
  			new Ext.ux.form.LovCombo({
  				name: 'field',
 				id: 'userview_tab1_field',
 				hiddenName: 'field',
 				fieldLabel: 'Fachgebiete',
  				anchor: '100%',
 				hideOnSelect: false,
 				store: fields_store,
 				triggerAction: 'all',
 				valueField: 'id',
 				displayField: 'display_name',
 				mode: 'local',
 				separator: ';',
 				allowBlank: false
 			}),			
			{
				xtype: 'combo', 								
				name: 'role',
				id: 'userview_tab1_role',
				hiddenName: 'role',
				fieldLabel: 'Rolle',
				store: roles_store,
				displayField: 'title',
				valueField: 'id',
				mode: 'local',
				typeAhead: true,
				triggerAction: 'all',
				minChars: 3,
				emptyText: 'Bitte auswählen',
				forceSelection: true,
				allowBlank: false,
				anchor: '100%'
			},			
			{
				xtype: 'checkbox',
				name: 'active',
				fieldLabel: 'Aktiv',
				inputValue: '1'
			},		
			{
				xtype: 'hidden',
				name: 'id',
				id: 'userview_tab1_id',
				value: 0
			}
		], // items end
		listeners: {
			'beforeaction': function(f, a) {
					// max. 5 Fachgebiete auswählbar
					var field = Ext.getCmp('userview_tab1_field').getValue();					
					var field_value = field.split(";");
					if (field_value.length > 5) {
						Ext.Msg.alert('Fehler', 'Es können maximal 5 Fachgebiete ausgewählt werden!');
						return false;
					}
			}
		}, // listeners end 		
    });
	// Ende Tab 1
	
	// Vorwahl bei phone & fax Feldern ergänzen
	var country = Ext.getCmp('userview_tab1_country');
	var phone = Ext.getCmp('userview_tab1_phone');
	var fax = Ext.getCmp('userview_tab1_fax');
	country.on("select", function() {
		var cc = country.getValue();
		if (debug) {
			console.log('country selected: ', cc);
		}		

		var prefix = country.store.getById(cc).get('prefix') + '-';
		if (debug) {
			console.log('country prefix: ', prefix);
		}
		
		if (!phone.getValue()) {
			phone.setValue(prefix);
		}
		if (!fax.getValue()) {
			fax.setValue(prefix);
		}		
	});
	
	
	function lookup_zipcode(cc, zipcode) {
		if (debug) {
			console.log('lookup_zipcode(', cc, ', ', zipcode, ')');
		}
		
		var city = Ext.getCmp('userview_tab1_city');
		
		var conn = new Ext.data.Connection();
		conn.request({
			url: '/zipcodes',
			method: 'POST',
			params: {
				zipcode: zipcode,
				cc: cc
			},
			success: function(res) {
				var resdata = Ext.util.JSON.decode(res.responseText);
				if (!resdata.success) {
					Ext.Msg.alert('Fehler', 'Fehler bei Abfrage der PLZ Datenbank');
				} else {        					
					if (debug) {
						console.log('results: ', resdata.results);
					}
					// mind. 1 Treffer?
					if (resdata.results > 0) {
						if (resdata.results == 1) {
							// nur 1 Treffer, Ortsnamen direkt übernehmen
							city.setValue(resdata.data[0].city);
						} else {
							// PLZ Auswahldialog anzeigen
							showZIPCodeDialog(country.getValue(), zip.getValue());
						}
					}
				}
			},
			failure: function() {
				Ext.Msg.alert('Fehler', 'Fehler bei Abfrage der PLZ Datenbank');
			}
		}); // conn.request end				
	} // lookup_zipcode
	
	
	// Einschränkung der Auswahl von Orten durch Postleitzahl
	var zip = Ext.getCmp('userview_tab1_zip');
	var city = Ext.getCmp('userview_tab1_city');
	zip.on("keyup", function() {
		if (country.getValue().match(/^DE$/i)) {
			if (zip.getValue().length == 5) {
				if (debug) {
					console.log('DE PLZ: keyup event && length=5. value: ', zip.getValue());
				}
				lookup_zipcode(country.getValue(), zip.getValue());				
			}
		} else if (country.getValue().match(/^AT|CH$/i)) {
			if (zip.getValue().length == 4) {
				if (debug) {
					console.log('AT/CH PLZ: keyup event && length=4. value: ', zip.getValue());
				}
				lookup_zipcode(country.getValue(), zip.getValue());				
			}
		}
	});
		
	// wenn eine user_id übergeben wurde, Daten laden
	if (typeof(user_id) == 'string') {
			
		// id Feld setzen
		Ext.getCmp('userview_tab1_id').setValue(user_id);		
		
		// Event Daten laden. 
		user_form.getForm().load({
			url: '/users/view',
			params: {
				id: user_id
			}
		});
		
	} // ende user daten laden
	

	var w = new Ext.Window({
		width: 600,
		title: 'Benutzer bearbeiten',
		id: 'userview',
		autoHeight: true,
		//height: 460,
		items: [
		        user_form
		], // items end
		buttons: [
		{
			text: 'Speichern',
			id: 'userview_bt_save',
			handler: function() {				
				saveUser();				
			}
		},
		{
			text: 'Abbrechen',
			id: 'userview_bt_cancel',
			handler: function() {
				w.close();
			}
		}		          
		] // buttons end

	});
	
	w.show();

}


function showZIPCodeDialog(cc, zipcode) {
	if (debug) {
		console.log('showZIPCodeDialog() ', cc, ' ', zipcode);
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('zipcodedialog')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}
	
	var zipcodes_store = new Ext.data.JsonStore({
		url: '/zipcodes/',
		baseParams: {
			zipcode: zipcode,
			cc: cc
		},
		fields: [
		         'cc',
		         'zipcode',
		         'city'
		         ],
		id: 'city',
		root: 'data',
		totalProperty: 'results',
		autoLoad: true
	});
	
	var w = new Ext.Window({
		width: 350,
		title: 'Ort auswählen',
		id: 'zipcodedialog',		
		autoHeight: true,
		border: true,
		modal: true,
		layout: 'form',
		xtype: 'form',
		bodyStyle: 'padding:10px',
		items: [
			{
				xtype: 'combo', 								
				name: 'city',
				id: 'zipcodedialog_city',
				hiddenName: 'city',
				fieldLabel: 'Ort',
				store: zipcodes_store,
				displayField: 'city',
				valueField: 'city',
				mode: 'local',
				typeAhead: true,
				triggerAction: 'all',
				minChars: 3,
				emptyText: 'Bitte auswählen',
				forceSelection: true,
				allowBlank: false,
				anchor: '100%'
			}
			
		],
		buttons: [
		{
			text: 'Übernehmen',
			handler: function() {
				var zipcodedialog_city = Ext.getCmp('zipcodedialog_city');
				Ext.getCmp('userview_tab1_city').setValue(zipcodedialog_city.getValue());
				w.close();
			}
		},
		{
			text: 'Abbrechen',
			handler: function() {
				w.close();
			}
		}		          
		] // buttons end		
	});

	w.show();	
	
}


function showLocations() {
	if (debug) {
		console.log('showLocations()');
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('locationsview')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}
	
	var locations_store = new Ext.data.JsonStore({
		url: '/locations/',
		fields: [
		         'id',
		         'title',
		         'address',
		         'zip',
		         'city',
		         'country'
		         ],
		id: 'id',
		root: 'data',
		totalProperty: 'results',
		autoLoad: true
	});
	
	// Schnellsuche berücksichtigen
	locations_store.on('beforeload', function() {
		// store leeren, falls bei load() keine Datensätze kommen
		locations_store.removeAll();
		
  		locations_store.baseParams = {
    		'limit': 22,
    		'query': Ext.getCmp('query_field').getValue()
  		};
	});
	
	var locations_grid = new Ext.grid.GridPanel({
		frame: false,
		id: 'locations_grid',
		height: 550,
		store: locations_store,
		columns: [
		{			
			header: 'ID',
			dataIndex: 'id',
			hidden: true
		},
		{
			header: 'Titel',
			dataIndex: 'title',
			width: 250
		},
		{			
			header: 'Anschrift',
			dataIndex: 'address',
			width: 200
		},
		{			
			header: 'PLZ',
			dataIndex: 'zip',
			width: 50
		},
		{			
			header: 'Ort',
			dataIndex: 'city',
			width: 150
		},
		{			
			header: 'Land',
			dataIndex: 'country',
			width: 50
		}
		
		], // columns end
		//autoExpandColumn: 2,
		bbar: new Ext.PagingToolbar({
			pageSize: 22,
			store: locations_store
		}),
		tbar: [
			{
				text: 'Bearbeiten',
				handler: function() {
					var sm = locations_grid.getSelectionModel();
					if (sm.hasSelection()) {
						var sel = sm.getSelected();
						showLocationDetails(sel.data.id); 
					} else {
						Ext.Msg.alert('Fehler', 'Bitte wählen Sie eine Zeile aus!');
					}
				}
			},	
			{
				text: 'Löschen',
				disabled: true
			},			
			{
				xtype: 'tbfill'
			},						
			{
				xtype: 'textfield',
				name: 'query',
				id: 'query_field',
    			emptyText: 'Schnellsuche',
   			  	enableKeyEvents: true,
  				listeners: {
    				"keydown": function(field, event) {
						// Schnellsuche
      					if (event.getKey() == event.ENTER) {     						     							
      						locations_store.load();      					
      					}
    				}
  				}

			},
			{	
				xtype: 'tbbutton',
				text: 'Clear',
				handler: function() {
					// Filter entfernen
					Ext.getCmp('query_field').setValue('');
					locations_store.load();
				}
			}
	
		] // tbar end			
	
	});
	
	// per Doppelclick Detail Dialog öffnen
	locations_grid.on('rowdblclick', function(grid, index, e) {
		if (debug) {
			console.log('rowdblclick', grid.store.getAt(index).id);
		}
		showLocationDetails(grid.store.getAt(index).id);
	});
	
	var w = new Ext.Window({
		width: 800,
		title: 'Veranstaltungsorte',
		id: 'locationsview',		
		autoHeight: true,
		border: false,
		items: [
			locations_grid
		]
	});

	w.show();

}


function showContacts() {
	if (debug) {
		console.log('showContacts()');
	}
	
	// mehrfaches Öffnen verhindern
	if (Ext.getCmp('contactsview')) {
		if (debug) {
			console.log('window already exists');
		}
		return 1;
	}
	
	var contacts_store = new Ext.data.JsonStore({
		url: '/contacts/',
		fields: [
		         'id',
		         'company',
		         'address',
		         'zip',
		         'city',
		         'country'
		         ],
		id: 'id',
		root: 'data',
		totalProperty: 'results',
		autoLoad: true
	});
	
	// Schnellsuche berücksichtigen
	contacts_store.on('beforeload', function() {
		// store leeren, falls bei load() keine Datensätze kommen
		contacts_store.removeAll();
		
  		contacts_store.baseParams = {
    		'limit': 22,
    		'query': Ext.getCmp('query_field').getValue()
  		};
	});
	
	var contacts_grid = new Ext.grid.GridPanel({
		frame: false,
		id: 'contacts_grid',
		height: 550,
		store: contacts_store,
		columns: [
		{			
			header: 'ID',
			dataIndex: 'id',
			hidden: true
		},
		{
			header: 'Firma',
			dataIndex: 'company',
			width: 250
		},
		{			
			header: 'Anschrift',
			dataIndex: 'address',
			width: 200
		},
		{			
			header: 'PLZ',
			dataIndex: 'zip',
			width: 50
		},
		{			
			header: 'Ort',
			dataIndex: 'city',
			width: 150
		},
		{			
			header: 'Land',
			dataIndex: 'country',
			width: 50
		}
		
		], // columns end
		//autoExpandColumn: 2,
		bbar: new Ext.PagingToolbar({
			pageSize: 22,
			store: contacts_store
		}),
		tbar: [
			{
				text: 'Bearbeiten',
				handler: function() {
					var sm = contacts_grid.getSelectionModel();
					if (sm.hasSelection()) {
						var sel = sm.getSelected();
						showContactDetails(sel.data.id); 
					} else {
						Ext.Msg.alert('Fehler', 'Bitte wählen Sie eine Zeile aus!');
					}
				}
			},	
			{
				text: 'Löschen',
				disabled: true
			},			
			{
				xtype: 'tbfill'
			},						
			{
				xtype: 'textfield',
				name: 'query',
				id: 'query_field',
    			emptyText: 'Schnellsuche',
   			  	enableKeyEvents: true,
  				listeners: {
    				"keydown": function(field, event) {
						// Schnellsuche
      					if (event.getKey() == event.ENTER) {     						     							
      						contacts_store.load();      					
      					}
    				}
  				}

			},
			{	
				xtype: 'tbbutton',
				text: 'Clear',
				handler: function() {
					// Filter entfernen
					Ext.getCmp('query_field').setValue('');
					contacts_store.load();
				}
			}
	
		] // tbar end			
	
	});
	
	// per Doppelclick Detail Dialog öffnen
	contacts_grid.on('rowdblclick', function(grid, index, e) {
		if (debug) {
			console.log('rowdblclick', grid.store.getAt(index).id);
		}
		showContactDetails(grid.store.getAt(index).id);
	});
	
	var w = new Ext.Window({
		width: 800,
		title: 'Veranstalter',
		id: 'contactsview',		
		autoHeight: true,
		border: false,
		items: [
			contacts_grid
		]
	});

	w.show();
	
}

// VType für Rufnummern im internationalen Format (+49-1234-567890)
Ext.form.VTypes["intphone"] = /^\+(\d{1,3}[-])(\d+[-])(\d+)$/;
Ext.form.VTypes["intphoneText"] = 'Ungültige Rufnummer. Erwartetes Format: +49-1234-567890';


// Ext sendet per Default den emptyText bei Submit, das ist jedoch nicht erwünscht
Ext.form.Action.Submit.prototype.run = Ext.form.Action.Submit.prototype.run.createInterceptor(function() {
	this.form.items.each(function(item) {
		if (item.el.getValue() == item.emptyText) {
			item.el.dom.value = '';
		}
	});
});
Ext.form.Action.Submit.prototype.run = Ext.form.Action.Submit.prototype.run.createSequence(function() {
	this.form.items.each(function(item) {
		if (item.el.getValue() === '' && item.emptyText) {
			item.el.dom.value = item.emptyText;
		}
	});
});


// Simulates PHP's date function
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<11?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return"Not Yet Supported";},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(this.getTimezoneOffset()<0?'-':'+')+(this.getTimezoneOffset()/60<10?'0':'')+(this.getTimezoneOffset()/60)+'00';},T:function(){return"Not Yet Supported";},Z:function(){return this.getTimezoneOffset()*60;},c:function(){return"Not Yet Supported";},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};
