App.Search = function() {
	var m, n, str, initialized, lastFunction;
	var fields = [
   		{ name: 'Id', type: 'int' }
   		, { name: 'CatalogueId', type: 'string' }
   		, { name: 'Name', type: 'string' }
   		, { name: 'Manufacturer', type: 'string' }
   		, { name: 'Netto1', type: 'string' }
   		, { name: 'IsSoldOut', type: 'boolean' }
		, { name: 'LastOrderDate', type: 'string' }
		, { name: 'Frequency', type: 'int' }
  	];
	var cols = [
		// { header: "ID", dataIndex: 'Id', width: 60, fixed: true }
		{ header: "Kat.-Nr.", dataIndex: 'CatalogueId', width: 60, fixed: true }
		, { header: "Name", dataIndex: 'Name', width: 345, tooltip: 'Klicken zum Sortieren' }
		, { header: "Hersteller", dataIndex: 'Manufacturer', width: 100 }
		, { header: "pro St./VE", dataIndex: 'Netto1', align: 'right', width: 70, fixed: true, renderer: 'deMoney', sortable: false }
		, { header: "wie oft bestellt", dataIndex: 'Frequency', width: 90, fixed: true, align: 'center', renderer: function(v) { return v + ' x';}, hidden: true }
		, { header: "zuletzt bestellt", dataIndex: 'LastOrderDate', width: 90, fixed: true, align: 'center', hidden: true }
	];

	return {
		init: function(callback) {
		},
		
		getPanel: function(){
			if (! this.panel){
				this.cm = new Ext.grid.ColumnModel(cols);
				this.cm.defaultSortable = true;
				this.sm = new Ext.grid.RowSelectionModel({ singleSelect: true });
				this.store = this._createStore();

				var l = App.getLayout(), c = l.getRegion('center');
				l.beginUpdate();
					Ext.DomHelper.append(c.bodyEl, 
						'<div id="search-panel">' +
						' <div style="padding:10px;">' +
						'  <h3 id="search-info">Suchergebnisse</h3>' +
						'  <div id="search-grid" style="border:1px solid silver;"></div>' +
						' </div>' +
						'</div>');
					this.grid = this._createGrid();
					this.panel = l.add('center', new Ext.ContentPanel('search-panel', { title: 'Suchergebnisse', autoCreate: true, preservePanel: true, fitToFrame: true, autoScroll: true }));
				l.endUpdate();
			}
			return this.panel;
		}

		, search: function() {
			var p = this.getPanel();
			var l = App.getLayout(), c = l.getRegion('center'), cm = this.grid.getColumnModel();
			cm.setHidden(4, true);
			cm.setHidden(5, true);
			l.showPanel(p);
			var data = { search: App.Toolbar.query.dom.value, fields: [] };
			var m = App.Toolbar.searchMenu;
			if (data.search.length < 3) {
				App.info.msg('Hinweis', 'Suchbegriff zu kurz oder leer');
				return;
			}
			if (m.items.get('Name').checked)
				data.fields.push('Name');
			if (m.items.get('ShowCoreArticlesOnly').checked)
				data.fields.push('ShowCoreArticlesOnly');
			if (m.items.get('Manufacturer').checked)
				data.fields.push('Manufacturer');
			if (m.items.get('Fulltext').checked)
				data.fields.push('Fulltext');
			if (m.items.get('Key').checked)
				data.fields.push('Key');

			this.store.setDefaultSort('Manufacturer', 'ASC');
			Ext.apply(this.store.baseParams, { action: 'search', data: Ext.util.JSON.encode(data) });
			this.store.load({ params: { start: 0 }});
			lastFunction = 'search';
		}

		, listDiscounts: function() {
			var p = this.getPanel();
			var l = App.getLayout(), c = l.getRegion('center'), cm = this.grid.getColumnModel();
			cm.setHidden(4, true);
			cm.setHidden(5, true);
			l.showPanel(p);
			this.store.setDefaultSort('Manufacturer', 'ASC');
			Ext.apply(this.store.baseParams, { action: 'getDiscountArticles', data: null });
			this.store.load({ params: { start: 0 }});
			lastFunction = 'listDiscounts';
		}

		, listFavourites: function() {
			var p = this.getPanel();
			var l = App.getLayout(), c = l.getRegion('center'), cm = this.grid.getColumnModel();
			cm.setHidden(4, false);
			cm.setHidden(5, false);
			l.showPanel(p);
			Ext.apply(this.store.baseParams, { action: 'getFavouriteArticles', data: null });
			this.store.setDefaultSort('Frequency', 'DESC');
			this.store.load({ params: { start: 0 }});
			lastFunction = 'listFavourites';
		}

		, listCoreArticles: function() {
			var p = this.getPanel();
			var l = App.getLayout(), c = l.getRegion('center'), cm = this.grid.getColumnModel();
			cm.setHidden(4, true);
			cm.setHidden(5, true);
			l.showPanel(p);
			Ext.apply(this.store.baseParams, { action: 'getCoreArticles', data: null });
			this.store.setDefaultSort('CatalogueId', 'ASC');
			this.store.load({ params: { start: 0 }});
			lastFunction = 'listCoreArticles';
		}

		, reset: function() {
			App.Toolbar.query.dom.value = '';
		}

		, reconfigure: function() {
			this.store.baseParams.limit = App.conf.itemsPerPage;
			switch (lastFunction) {
				case 'search': this.search(); break;
				case 'listDiscounts': this.listDiscounts(); break;
				case 'listFavourites': this.listFavourites(); break;
			}
		}

		, onStoreLoad: function(store, records) {
			this.resizeGrid();
			Ext.get('search-info').update('<h3>' + (this.store.getTotalCount() || 'Keine') + ' Suchergebnisse</h3>');
			if (! this.store.getTotalCount()) App.Toolbar.flashHelp();
		}

		, resizeGrid: function() {
			// calculate the number of rows to display
			var ogh = this.grid.container.getHeight();
			var ph = this.getPanel().el.getHeight();	
			var ch = Ext.get('search-info').getHeight();					 
			var gh = ph - ch - 82;
			var maxRows = Math.floor(gh / 20);
			var rows = Math.min(this.store.getCount(), maxRows);

			// reload the store, if number of maxRows has changed
			if (this.store.baseParams.limit != maxRows){
				this.store.removeAll();
				this.store.baseParams.limit = maxRows;
				this.pager.pageSize = maxRows;
				App.conf.itemsPerPage = maxRows;
				this.store.reload();
				return;
			}

			// resize the grid, if required
			this.grid.autoHeight = false;
			this.grid.container.setHeight(rows * 20 + 51);
			this.grid.autoSize();
			this.grid.getView().fitColumns(true);
		}

		, _createStore: function() {
			var rec = Ext.data.Record.create(fields);
			var store = new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({ method: 'POST', url: 'shop.php' })
				, reader: new Ext.data.JsonReader({ root: 'articles', totalProperty: 'totalRecords', id: 'Id' }, rec)
				, baseParams: { realm: 'article', action: 'search', limit: App.conf.itemsPerPage, data: '' }
				, remoteSort: true
			});
			store.on('load', this.onStoreLoad, this);
			store.setDefaultSort('Manufacturer', 'asc');
			return store;
		}

		// private
		, _createGrid: function() {
			var grid = new Ext.grid.Grid('search-grid', {
				ds: this.store
				, cm: this.cm
				, selModel: this.sm
				, enableColLock: false
				, autoHeight: true
				, trackMouseOver: false
				, maxRowsToMeasure: 5
				, loadMask: { msg: 'Suche läuft...', removeMask: true }
			});
			grid.on('rowclick', function() {
				var rec = this.grid.getSelectionModel().getSelected();
				App.ArticleView.show(rec.get('Id'));
			}, this);
			grid.render();
			grid.getView().getRowClass = function(record, index) {
				return record.get('IsSoldOut') ? 'art-sold-out' : '';
			};

			App.getLayout().on('layout', this.resizeGrid, this);

			var gridHead = grid.getView().getHeaderPanel(true);
			this.pager = new Ext.PagingToolbar(gridHead, this.store, {
				displayInfo: true,
				displayMsg: "Artikel {0} &ndash; {1} von {2}",
				emptyMsg: 'Keine Daten zum Anzeigen'
			});

			return grid;
		}
	};
}();

