/*
 * @author: Christian Lahrz-Beckmann
 * @co-author: Thomas Fr�bel
 * 
 * xml-grid.js modifiziert um ein Grid zur Ticketdarstellung zu erstellen 
 */


var UID = '';
if (!SIZE) {
	var SIZE = 23;
}
if (!PKEY) {
	var PKEY = 'SPIEL';
}
if (!PID) {
	var PID = '4';
}

var EMAIL = '';

/*
 * Taskfilter: progress, old, open
 * typefilter: bug, feature, task, improvement
 */

if (!TASKFILTER) {
	var TASKFILTER = 'progress';
}

if (!TYPEFILTER) {
	var TYPEFILTER = '0';
}

/*
 * checkmich: boolean das keine rekursion beim dr�cken des showpreview-buttons entsteht
 * previewpressed: booleanwert des showpreview-buttons
 */ 

var checkmich = true;
var previewpressed = false;
var CACHE = 1;

function captureEvents(observable) {
    Ext.util.Observable.capture(
        observable,
        function(eventName) {
            console.info(eventName);
        },
        this
    );		
}

/**
 * Auf- und Zuklappen der Zeilen, um mehr Inhalt darzustellen 
 * @param {Boolean} expand
 * @param {Object} panel
 * @param {Object} store
 * @param {Object} expander
 */
function ExpandAll (expand,panel,store, expander)
{
	for (var x=0; x<store.getCount(); x++)
    {
        if (expand)
            expander.expandRow(x);
        else
            expander.collapseRow(x);
   }

    panel.getView().focusRow(0);
    panel.getView().ensureVisible(0, 0, false);
} 


Ext.onReady(function(){

	/* 
	 * Prototype l�dt ein iframe
	 */
	var panel_prototype = '';
	if (PID == '7') {
		panel_prototype = new Ext.Panel({
			frame: false,
			width: '100%',
			tbar: tabs,
			items: [{
				html: '<h1><a href="http://haefft.webxells.com">Zur Pr&auml;sentationsseite - bitte Logindaten beachten.</a></h1><!--<iframe src="http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html" width="574" height="800" frameborder="0"></iframe>-->'
			}]
		}).hide();
	} else {
		panel_prototype = new Ext.Panel({
			frame: false,
			width: '100%',
			tbar: tabs,
			items: [{
				html: '<h1><a href="http://aekb.webxells.com/desktop/desktop.html">Zur Pr&auml;sentationsseite - bitte Logindaten beachten.</a></h1><!--<iframe src="http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html" width="574" height="800" frameborder="0"></iframe>-->'
			}]
		}).hide();
	}

	/* 
	 * Wiki l�dt ein iframe
	 */
	//html : '<iframe src="http://www.webxells.com" width="574" height="800" frameborder="0"></iframe>'
	var panel_wiki = new Ext.Panel({
		frame : false,
		width : '100%',
		tbar: tabs,
		items : [{
			html : '<iframe src="http://www.webxells.com/AEKB_Wiki/index.php" width="574" height="800" frameborder="0"></iframe>'
		}]
	}).hide();

	var jql_path = '';
	if (window.location.hostname != 'localhost') {
		//LIVE
		jql_path = 'customers/jql/';
	}
	
	//var jsonFelder = [{xtype:'textfield',name:'name','fieldLabel':'Name des Feldes'}];

	/**
	 * Dokumententab, Formular
	 */
	var documentsType = '';
	documentsType = new Ext.form.ComboBox({
		name : 'docclass',
		width :135,
		forceSelection : true,
		typeAhead : true,
		editable :false,
	    transform :'docclass',
		triggerAction : 'all',
		listeners: {
			select: documentsTypeSelected
		}
    });
	var documentsForm = new Ext.FormPanel({
		labelWidth: 75,
		url:'',
        frame:true,
		fileUpload: true,
        title: 'Upload your documents',
        bodyStyle:'padding:5px 5px 0',
        width: 450,
        defaults: {width: 345},
        defaultType: 'textfield',

        items: [ documentsType,
			new Ext.ux.form.FileUploadField({
				emptyText: 'Select a document',
				name : 'dokument'
		    }), {
				xtype : 'hidden',
				name  : 'pkey',
				value : PKEY
			}, {
				xtype : 'hidden',
				name  : 'pid',
				value : PID
			}
        ],

        buttons: [{
            text: 'Save',
            handler: function(){
                if(documentsForm.getForm().isValid()){
	                documentsForm.getForm().submit({
	                    url: jql_path+'documents_upload.php',
	                    waitMsg: 'Uploading your documents...',
	                    success: function(d, o){
							if (o.result.success == true || o.result.success == "true") {
								Ext.Msg.alert('Document upload', 'Your documents have been successfully uploaded.');
								documentsForm.getForm().reset();
								loadDocumentGrids();
							} else {
								//Fehler ist aufgetreten 
								Ext.Msg.alert('Error', 'Something went wrong with your upload.');
							}
	                    },
						failure: function(d, o){
							Ext.Msg.alert('Error transmission', 'Something went wrong.');
						}
	                });
                }
            }
        },{
            text: 'Reset',
            handler: function(){
                documentsForm.getForm().reset();
            }
        }]
	});

	/**
	 * Dokumententab, Panel
	 */
	
	var documentsPanel = new Ext.Panel({
		width : '100%',
		frame : true,
		layout: 'form',
		items : [documentsForm,{
					html : '<br />'
				}
			]
	}).hide();

	/**
	 * Dokumententab, Grids aus JSON beziehen um sie dann dynamisch zu erzeugen
	 */
	var old_document_tables = new Array();
	function loadDocumentGrids(){
		Ext.Ajax.request({
			url: jql_path + 'getdocgrids.php?pid=' + PID + '&uid=' + UID,
			success: function(response){
				//Tabelle ins DOM einh�ngen und dann dynamisch mittel Table-Grid umwandeln lassen 
				if (response.responseText != '') {
					//Ext.select('body').insertHtml('body','<div id="grid_tabellen">'+response.responseText+'</div>');
					
					//Problem mit jQuery behoben, ein Problem ist bei Ext mit insertHtml passiert beim IE 
					jQuery('div#grid_tabellen').empty();
					jQuery('body').prepend('<div id="grid_tabellen">' + response.responseText + '</div>');
					//Titel der Grids verstecken 
					jQuery('#grid_tabellen p').hide();
					
					//Tabellen-IDs durchgehen und eintragen um ein Grid daraus dynamisch zu erzeugen 
					var i = 0;
					var l = old_document_tables.length;
					for (var j = 0; j < l; j++) {
						documentsPanel.remove(Ext.getCmp(old_document_tables[j]));
					}

					Ext.select('div#grid_tabellen table').each(function(){
						var grid_titel = jQuery('#grid_tabellen p:eq(' + i + ')').text();
						i++;
						var dkids = Ext.id(this);
						//Quelle: ext/examples/grid/from-markup.js 
						var gridTable = new Ext.ux.grid.TableGrid(dkids, {
							title: grid_titel,
							stripeRows: true, // stripe alternate rows
							width: '100%',
							viewConfig: {
								forceFit: false
							},
							collapsible: true,
							autoExpandMin: '100'
						}).hide();

						old_document_tables.push(gridTable.id)
						documentsPanel.add(gridTable);
						documentsPanel.doLayout();
						
						if (tabs.getActiveTab().id == 'documents_tab') {
							documentsPanel.items.each(function(item){
								item.show();
							})
						}
					//gridTable.render();
					})
				}
			},
			failure: function(){
			
			}
		})
	}
	loadDocumentGrids();

	/**
	 * Dokumentenfelder auswerten und dynamisch erzeugen 
	 * Textfelder, Zeitfelder und Downloadfelder 
	 * JSON wird per getdocfields_json.php geholt und ausgewertet 
	 * Beispiel: {"1":[{"fieldLabel":"name","name":"feld1","xtype":"textfield"},{"fieldLabel":"main focus","name":"feld1","xtype":"textfield"},{"fieldLabel":"status","name":"feld1","xtype":"textfield"},{"fieldLabel":"hourly rate","name":"feld1","xtype":"textfield"}]}
	 */
	var jsonDocFields = new Ext.data.JsonStore({
		fields: ['name','xtype','fieldLabel'],
		url: jql_path+'getdocfields_json.php',
		listeners: {
		    load: jsonDocFieldsLoaded
		}
	});
	
	function jsonDocFieldsLoaded(jsonDocFields) {
		//console.log(jsonDocFields.reader.jsonData[1]);
	}

	jsonDocFields.load();
	
	function documentsTypeSelected(documentsType) {
		var dokid = documentsType.getValue();
		//L�sche alle nachfolgenden Felder, nach dem Uploadfeld, es sind insgesamt 4 Felder
		//das Drop-Down, Textfeld zur Pfadangabe f�r die Datei, FileUpload Feld selbst 
		//Deswegen wird i > 3 gepr�ft, bei 0 beginnend 
		if(documentsForm.items != undefined){
			var i = 0;
			documentsForm.items.each(function(item){
				if (i > 3) {
					documentsForm.remove(item, true);
				}
				i++;
			});
		} 
		var daten = jsonDocFields.reader.jsonData[dokid];
		if (daten != undefined) {
			documentsForm.add(daten);
		}
		documentsForm.doLayout();
		documentsPanel.doLayout();
	}

	/**
	 * New Tasks Combobox
	 */
	var newTaskType = new Ext.form.ComboBox({
		fieldLabel : 'Type',
		name : 'typ',
		width :135,
		forceSelection : true,
		typeAhead : true,
		editable :false,
	    transform :'typ',
		triggerAction : 'all'
    });

	/*var zeit = new Date();
	var time_id = String(zeit.getHours()).concat(zeit.getSeconds()); //Zeitstring eintragen 
	var time_id = time_id.concat(zeit.getMilliseconds());
	zeit = '';*/

	/**
	 * Formular New task
	 * @param {Object} action
	 */
	var newTaskForm = new Ext.FormPanel({
		labelWidth: 75,
		fileUpload: true,
        frame:true,
        title: 'Create a new ticket',
        bodyStyle:'padding:5px 5px 0',
        width: 450,
        defaults: {
			width: 345
			//allowBlank: false
		},
        defaultType: 'textfield',

        items: [ newTaskType,
			{
                fieldLabel: 'Title',
                name: 'summary',
				allowBlank: false
            },{
                xtype : 'textarea',
				fieldLabel: 'Description',
                name: 'description',
				allowBlank: false,
				height:200
            }, new Ext.ux.form.FileUploadField({
				emptyText: 'Select a document',
				name : 'datei'
		    }), {
				xtype : 'hidden',
				name  : 'new_task',
				value : '1'
			},{
				xtype : 'hidden',
				name  : 'pkey',
				value : PKEY

			},{
				xtype : 'hidden',
				name  : 'pid',
				value : PID
			},{
				xtype : 'hidden',
				name  : 'email',
				value : EMAIL
			},{
				xtype : 'hidden',
				name  : 'uid',
				value : UID
			}
        ],

        buttons: [{
            text: 'Save',
            handler: function(){
				if(newTaskForm.getForm().isValid()){
	                newTaskForm.getForm().submit({
						clientValidation: true,
	                    waitMsg: 'Uploading your data...',
					    url: jql_path+'newtask_upload.php',
						success: function(n, o){
	                        if (o.result.success == true || o.result.success == "true") {
								Ext.Msg.alert('New task', 'You created a new ticket.');
								newTaskForm.getForm().reset();
								CACHE=0;
								//Cache auf 0 setzen um die �nderung anzuzeigen 
							} else {
								//Fehler ist aufgetreten 
								Ext.Msg.alert('Error', 'Something went wrong.');
							}
	                    },
						failure: function(n, o){
							Ext.Msg.alert('Error transmission', 'Something went wrong.');
						}
					})
                }
            }
        },{
            text: 'Reset',
            handler: function(){
                newTaskForm.getForm().reset();
            }
        }]
	}).hide();

	//Auswertung der Men�-Filter 
	var handleAction = function(action){
	    //Aktion auswerten und jeweils nach Typ filtern 
	};

	function hideGrid() {
		//grid.el.fadeOut({ endOpacity: 0, duration: .5});
		if (groundPanel && toolbar.bbar && newTaskForm) {
			grid.hide();
			newTaskForm.hide();
			documentsPanel.hide();
			groundPanel.doLayout();
			toolbar.bbar.hide();
			panel_prototype.hide();
			panel_wiki.hide();
		}
	}
	function showGrid() {
		if (groundPanel && grid && toolbar.bbar) {
			grid.show();
			newTaskForm.hide();
			documentsPanel.hide();
			toolbar.bbar.show();
			panel_prototype.hide();
			panel_wiki.hide();
		}
	}
	
	function reloadGrid() {
		// beim Switchen eines Tabs wird der Showpreview Button, sofern pressed, wieder auf unpressed gesetzt
		if (previewpressed) {
			Ext.getCmp('ShowPreviewBottom').toggle();
			//bbar.items.items[14].toggle();
		}
		store.baseParams = {start:0, limit:SIZE, uid:UID, pkey:PKEY, taskfilter:TASKFILTER, typefilter:TYPEFILTER, cache:CACHE};
		store.load({params:{start:0, limit:SIZE, uid:UID, pkey:PKEY, taskfilter:TASKFILTER, typefilter:TYPEFILTER, cache:CACHE}});
		if (CACHE==0) {
			CACHE=1;
		}
	}

	//Auswertung der Tabs 
	var tabAction = function(action){
	    //Aktion auswerten und jeweils nach Typ filtern 

		//In progress
		if (action == 'In progress') {
			showGrid();
			TYPEFILTER='0';
			TASKFILTER='progress';
			uncheckbuttons();
			reloadGrid();
		}
		//Open tasks
		if (action == 'Open tasks') {
			showGrid();
			TYPEFILTER='0';
			TASKFILTER='open';
			uncheckbuttons();
			reloadGrid();		
			}
		//Old tasks
		if (action == 'Old tasks') {
			showGrid();
			TYPEFILTER='0';
			TASKFILTER='old';
			uncheckbuttons();
			reloadGrid();		}
		
		//New task
		if (action == 'New task') {
			hideGrid();
			if (groundPanel) {
				newTaskForm.show();
			}
		}
		
		//Documents
		if (action == 'Documents') {
			hideGrid();
			if (groundPanel) {
				documentsPanel.show();
				documentsPanel.items.each(function(item){
					item.show();
				})
			}
		}
		
		//Wiki
		if (action == 'Wiki') {
			hideGrid();
			if (groundPanel) {
				panel_wiki.show();
			}
		}
		
		//Prototype
		if (action == 'Prototype') {
			hideGrid();
			if (groundPanel) {
				panel_prototype.show();
			}
		}
		
	};

    //Tabs werden oberhalb des Panels angebracht
	var tabs = new Ext.TabPanel({
        //renderTo: 'tabs',
        activeTab: 0,
        frame:true,
        plain:true,
		defaults:{autoHeight: true},
        items:[
            {title: 'In progress', listeners: { activate : tabAction.createCallback('In progress') }},
            {title: 'Open tasks', listeners: { activate : tabAction.createCallback('Open tasks') }},
            {title: 'Old tasks', listeners: { activate : tabAction.createCallback('Old tasks') }},
            {title: 'New task', listeners: { activate : tabAction.createCallback('New task') }},
            {id:'documents_tab', title: 'Documents', listeners: { activate : tabAction.createCallback('Documents') }},
            {title: 'Wiki', listeners: { activate : tabAction.createCallback('Wiki') }},
            {title: 'Prototype', listeners: { activate : tabAction.createCallback('Prototype') }}
        ]
    });
	
	var checkbutton = false;
	
	function checkbuttonchecked(button, pressed, type)
	{
		if (pressed) {
			checkbutton = true;
			for (i=0;i<4;i++)
			{
				if (i!=button)
				{
					if (btoolbar.items.items[i].pressed)
					{
						btoolbar.items.items[i].toggle();
					}
				}
			}
			checkbutton = false;
			TYPEFILTER = type;
		}
		else
		{
			TYPEFILTER = '0';
		}
		reloadGrid();
	}
	
    function uncheckbuttons(){
        checkbutton = true;
        for (i = 0; i < 4; i++) {
            if (btoolbar.items.items[i].pressed) {
                btoolbar.items.items[i].toggle();
            }
        }
        checkbutton = false;
        TYPEFILTER = "0";
    }
	
	//TYPEFILTER = 'bug';
	//reloadGrid();
	
	var btoolbar = new Ext.Toolbar({
    items: [{

			xtype: 'tbbutton',
            text: 'Bug',
			pressed: false,
			enableToggle: true,
            iconCls: 'icon_bug',
			toggleHandler: function(btn,pressed){
			if (!checkbutton) {
				checkbuttonchecked(0, pressed, "bug")
			}
			
			} 
			
        },{
			xtype: 'tbbutton',
            text: 'Feature',
			pressed: false,
			enableToggle: true,
            iconCls: 'icon_feature',
			toggleHandler: function(btn,pressed){
			if (!checkbutton) {
				checkbuttonchecked(1, pressed, "feature")
			}
			} 
        },{
			xtype: 'tbbutton',
            text: 'Task',
			pressed: false,
			enableToggle: true,
            iconCls: 'icon_task',
			toggleHandler: function(btn,pressed){
			if (!checkbutton) {
				checkbuttonchecked(2, pressed, "task")
			}
			} 

        },{
			xtype: 'tbbutton',
            text: 'Improvement',
			pressed: false,
			enableToggle: true,
            iconCls: 'icon_improvement',
			toggleHandler: function(btn,pressed){
			if (!checkbutton) {
				checkbuttonchecked(3, pressed, "improvement")
			}
			} 

    }]
  });
	
	//Panel welches die Tabs und die Men�buttons f�r das Grid aufnimmt und im Grid als Toolbar erscheint 
	var toolbar = new Ext.Panel({
		frame : false,
		width : '100%',
		tbar: tabs,
		items : [{
			html : ''
		}],
		bbar: btoolbar
	})

/**
 * Datenbereich
 */
	MyExpander = Ext.extend(Ext.ux.grid.RowExpander, {
	    getBodyContent : function(record, index){
	        var data = {
	            comments: record.data.comments,
				attachments: record.data.attachments,
	            description: record.get('description'),
	            summary: record.get('summary')
	        };
	        if(!this.enableCaching){
	            return this.tpl.apply(data);
	        }
	        var content = this.bodyContent[record.id];
	        if(!content){
	            content = this.tpl.apply(data);
	            this.bodyContent[record.id] = content;
	        }
	        return content;
	    }
	});
	 
	var xmlreader = new Ext.data.XmlReader({
	    totalProperty: 'issue@total',
	    record: 'item',
	    fields: ['description', 'summary', 'updated', 
			{ 	name: 'type',
				mapping: 'type@id'
			},
			'assignee', 'status', 'resolution', 'key', 
			{
	        name: 'comments',
	        convert: function(raw, item){
	            var comments = Ext.DomQuery.select('comments/comment', item);
				var description = Ext.DomQuery.select('description', item);
                data = [];
	            Ext.each(comments, function(comment){
	                data.push({
	                    comment_id: comment.getAttribute('id'),
	                    comment_author: comment.getAttribute('author'),
	                    comment_created: new Date(comment.getAttribute('created')),
	                    comment_text: comment.textContent || comment.text
	                });
	            });

	            return data;
	        }
	    },{
			name: 'attachments',
	        convert: function(raw, item){
	            var attachments = Ext.DomQuery.select('attachments/attachment', item);
                data = [];
	            Ext.each(attachments, function(attachment){
	                data.push({
	                    attachment_id: attachment.getAttribute('id'),
	                    attachment_author: attachment.getAttribute('author'),
	                    attachment_created: new Date(attachment.getAttribute('created')),
	                    attachment_name: attachment.getAttribute('name')
	                });
	            });
	            return data;
	        }
			
		}]
	});

	var addComment = new Ext.Button({
		width:100,
		height:25,
		text:'Add comment',
		iconCls:'icon_add_comment'
	});

//var action = new Ext.ux.grid.RowAction({iconCls:'icon_bug',qtip:'Fehler'});
//action.on('action', function(grid, record) {...});  

    var store = new Ext.data.Store({
        reader: xmlreader,

		proxy: new Ext.data.HttpProxy({
            url: jql_path+'jira_jql_getxml.php'
        }),
		listeners: {
			load : function() {
				/**
				 * Falls der Show Button geklickt ist, soll auch nach einer Aktualisierung das Grid die Tickets offen anzeigen 
				 */
				//var kommentare = this.reader.xmlData.querySelectorAll('comments > comment');
				//console.log(kommentare);
				//console.log(this.data);

				if (Ext.getCmp('ShowPreviewTop').pressed) {
					ExpandAll(true, grid, store, expander);
				}
			}
		}
		
    });
	store.baseParams = {start:0, limit:SIZE, uid:UID, pkey:PKEY, taskfilter:TASKFILTER, typefilter:TYPEFILTER, cache:1};

	var expander = new MyExpander({
	    tpl: new Ext.XTemplate(
			'<p>Description: {description}</p><br /><p>{summary}</p><br />',
			'Attachments: <p><tpl for="attachments"><b>{[xindex]}. {attachment_author} - {attachment_created:date("d-m-Y")}</b><br /><p><a href="'+jql_path+'proxy_download.php?aid={attachment_id}&aname={attachment_name}&pid='+PID+'&uid='+UID+'">{attachment_name}</a></p></tpl></p>',
			'Comments: <p><tpl for="comments"><b>{[xindex]}. {comment_author} - {comment_created:date("d-m-Y")}</b><br /><p>{comment_text}</p></tpl></p>'
		)
	});
	
		/**
		 * Aktualisierung der Paginierung �berschreiben, damit der Cache deaktiviert wird zur Aktualisierung 
		 */
		//Siehe: http://www.extjs.com/forum/showthread.php?71532-3.x-Ext.ux.data.PagingStore-v0.4/page10&highlight=pagingtoolbar+refresh
		Ext.override(Ext.PagingToolbar, {
			doRefresh: function(){
				delete this.store.lastParams;
				store.baseParams = {start:0, limit:SIZE, uid:UID, pkey:PKEY, taskfilter:TASKFILTER, typefilter:TYPEFILTER, cache:0};
		        this.doLoad(this.cursor);
		    }
		});
			
		var tbar = new Ext.PagingToolbar({
			pageSize: SIZE,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying tickets {0} - {1} of {2}',
            emptyMsg: "No tickets to display",
            items: ['-', {
				pressed: false,
				enableToggle: true,
				id: 'ShowPreviewTop',
				text: 'Show Preview',
				cls: 'x-btn-text-icon details',
				toggleHandler: function(btn, pressed){
					previewpressed = pressed;
					if (checkmich) {
						checkmich = false;
						Ext.getCmp('ShowPreviewBottom').toggle();
						//bbar.items.items[14].toggle();
						ExpandAll(pressed, grid, store, expander);
					}
					else {
						checkmich = true;
					}
				}
			}, '-',
			{
	xtype: 'tbbutton',
	text: 'Cancel Ticket',
	handler: function() {
		var gridrecord = grid.getSelectionModel().getSelected();
	//	console.log(gridrecord.data.key);
	  
	Ext.MessageBox.confirm('Confirm', 'Are you sure you want to cancel that ticket ('+gridrecord.data.key+') ?', function(btn){
    if (btn == 'yes'){
        store.baseParams = {start:0, limit:SIZE, uid:UID, pkey:PKEY, taskfilter:TASKFILTER, typefilter:TYPEFILTER, cache:0, key: gridrecord.data.key};
		store.load({params:{start:0, limit:SIZE, uid:UID, pkey:PKEY, taskfilter:TASKFILTER, typefilter:TYPEFILTER, cache:0, key: gridrecord.data.key}});
       	store.baseParams = {start:0, limit:SIZE, uid:UID, pkey:PKEY, taskfilter:TASKFILTER, typefilter:TYPEFILTER, cache:0};

    }
});

	
	}

    }
			]
        });
		
		var bbar =  new Ext.PagingToolbar({
            pageSize: SIZE,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying tickets {0} - {1} of {2}',
            emptyMsg: "No tickets to display",
            items:['-', 
			{
                pressed: false,
                enableToggle:true,
				id: 'ShowPreviewBottom',
                text: 'Show Preview',
                cls: 'x-btn-text-icon details',
                toggleHandler: function(btn, pressed,check){
					if (checkmich) {
						checkmich=false;
						Ext.getCmp('ShowPreviewTop').toggle();
						//tbar.items.items[14].toggle();
						ExpandAll(pressed,grid,store, expander);			
					}
					else
					{
						checkmich=true;
					}
				}
            }]
        });
   
    // create the grid
    var grid = new Ext.grid.GridPanel({
    	store: store,
		title:'Tickets',
        plugins:[expander],
        columns: [
            expander, 
            {header: "Type", width:30, dataIndex: 'type', sortable: true, renderer: function(value, metaData, record, rowIndex, colIndex, store) {
				if (value == '1') {
					//Bug
					value = '<img src="/customers/imgs/bug.gif" alt="Bug" />';
				}
				if (value == '2') {
					//Neue Funktion
					value = '<img src="/customers/imgs/feature.gif" alt="Feature" />';
				}
				if (value == '3') {
					//Aufgabe
					value = '<img src="/customers/imgs/task.gif" alt="Task" />';
				}
				if (value == '4') {
					//Verbesserung
					value = '<img src="/customers/imgs/improvement.gif" alt="Improvement" />';
				}
				if (value == '5') {
					//Unteraufgabe
					value = '<img src="/customers/sub.gif" alt="Subtask" />';
				}

				//console.log(record.get('comment'));
				return value;
			}},
            {header: "Key", width:120, dataIndex: 'key', sortable: true},
            {header: "Summary", width:379, dataIndex: 'summary', sortable: true},
            {header: "Assignee", width:100, dataIndex: 'assignee', sortable: true},
            {header: "Last activity", width:100, dataIndex: 'updated', sortable: true}
        ],
        //renderTo:'example-grid',
		//renderTo:'inprogress',
        //width:540,
        height:620,
        animCollapse:true,
		frame: true,
		loadMask: true,
		autoExpandColumn: 'summary',
		stripeRows: true,
        // customize view config

        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        },

		tbar: tbar,
		bbar: bbar,
		onEnable: function() { 
			//console.log("jaa");
		}
        
    });


	//Hauptpanel welches alle weiteren Element aufnimmt 
	var groundPanel = new Ext.Panel({
		width : '100%',
		frame : true,
		layout: 'fit',
		//title : 'Customer Portal',
		renderTo : 'example-grid',
		tbar  : toolbar,
		items  : [grid, newTaskForm, documentsPanel, panel_wiki, panel_prototype]
	}).show();

	/*var portalWindow = new Ext.Window({
		width : 500,
		height: '100%',
		minHeight: 760,
		layout: 'column',
		maximizable : true,
		closable : false,
		x : 0,
		y : 0,
		renderTo : 'example-grid',
		items  : groundPanel
	}).show();*/


});