App.ProductView = function() {
	var pId, tree, panel, grid, initialized;
	var layout, west, center;
	var zoomTemplate = new Ext.Template(
		'<div class="img-zoom"><img src="/content/images/{Filename}" title="{Filename}" /></div>'
	);
	zoomTemplate.compile();
	
	return {
		init: function(){
			this.productsPanel = this.createProductsPanel();
		},
		
		ds: null,
		
		productsPanel: null,

		loadList: function(categoriesId) {
			var l = App.getLayout(), c = l.getRegion('center');
			c.showPanel(this.productsPanel);
			this.categoriesId = categoriesId
			if (! categoriesId) {
				var w = layout.getRegion('west');
				if (w.collapsed) w.expand();
				if (Ext.get('prod-notice').isVisible() == false) Ext.get('prod-notice').slideIn();
				Ext.get('prod-list').hide();
				return;
			}

			this.hasSingleArticles = false;
			this.singleNodeAdded = false;
			if (this.tree) {
				this.tree.purgeListeners();
				delete this.tree;
			}
			Ext.get('prod-notice').pause(0.25).slideOut('t', { useDisplay: true });
			Ext.get('prod-list').show().update('');
			this.loader = this.loader || new Ext.tree.TreeLoader({
				dataUrl: 'shop.php'
				, method: 'post'
				, baseParams: { realm: 'product', action: 'getProductsList' }
				, createNode : function(attr){
					if(this.applyLoader !== false){
						attr.loader = this;
					}
					if(typeof attr.uiProvider == 'string'){
					   attr.uiProvider = this.uiProviders[attr.uiProvider] || eval(attr.uiProvider);
					}
					return new Ext.tree.TreeNode(attr);
				}
			});
			Ext.apply(this.loader.baseParams, { categoriesId: categoriesId });
			this.tree = new Ext.tree.TreePanel('prod-list', {
				loader: this.loader
				, rootVisible: false
				, containerScroll: false
				, lines: false
			});
			this.tree.on('load', function(node) {
				this.lookupSingleArticles();
			}, this);
			this.tree.on('click', function(node, event) {
				if (node.attributes.id) {
					this.loadDetails(node.attributes.id);
				}
			}, this);
			var root = new Ext.tree.AsyncTreeNode({
				text: 'root'
				, draggable: false
				, singleClickExpand: true
				, id: categoriesId
				, icon: ''
			});
			this.tree.setRootNode(root);
			this.tree.render();
			root.expand();
		}

		, lookupSingleArticles: function() {
			if (! this.lconn) {
				this.lconn = new Ext.data.Connection();
				this.lconn.on('requestcomplete', this.addSingleNode, this);
			}
			this.lconn.request({method: 'POST', url: 'shop.php', params: { realm: 'category', action: 'lookupSingleArticles', id: this.categoriesId } });
		}

		, addSingleNode: function(store, param) {
			var r = Ext.decode(param.responseText);
			var root = this.tree.getRootNode();
			if (r.success && r.totalRecords) {
				var node = new Ext.tree.TreeNode({ id: 'single', text: 'Einzelne Artikel', qtip: (r.totalRecords + ' Artikel'), leaf: true, cls: 'single-node' });
				root.insertBefore(node, root.firstChild);
				this.singleNodeAdded = true;
			}
			var w = layout.getRegion('west');
			if (root.childNodes.length > 1) {
				if (w.collapsed) w.expand();
			} else {
				if (! w.collapsed) w.collapse();
			}
			// return;
			// select first entry
			if (root.childNodes.length) {
				root.firstChild.select();
				this.loadDetails(root.firstChild.id);
			}
		}

		, loadDetails: function(productsId) {
			pId = productsId;
			if (this.conn) {
				if (this.conn.isLoading())
					return false;
			} else {
				this.conn = new Ext.data.Connection();
				this.conn.on('requestcomplete', this.buildGrid, this);
			}
			if (productsId = parseInt(productsId))
				this.conn.request({method: 'POST', url: 'shop.php', params: { realm: 'Product', action: 'details', id: productsId } });
			else
				this.loadSingleArticles();
		}

		, loadSingleArticles: function() {
			if (! this.categoriesId) return;

			if (this.grid) {
				this.grid.destroy(false);
			}

			var fields = [
				{name: 'Id', tpe:'int' }
				, { name: 'CatalogueId', type: 'string' }
				, { name: 'KeyId', type: 'string' }
				, { name: 'Name', type: 'string' }
				, { name: 'Manufacturer', type: 'string' }
				, { name: 'Netto1', type: 'float' }
				, { name: 'IsSoldOut', type: 'boolean' }
		  	];
			var rec = Ext.data.Record.create(fields);
			var cols = [
				/* { header: "ID", dataIndex: 'Id', width: 60, fixed: true, hidden: true } */
				{ header: "Kat.-Nr.", dataIndex: 'CatalogueId', width: 60, fixed: true }
				, { header: "Name", dataIndex: 'Name', width: 250 }
				, { header: "Hersteller", dataIndex: 'Manufacturer', align: 'left', width: 100 }
				, { header: "pro St./VE", dataIndex: 'Netto1', align: 'right', renderer: 'deMoney', width: 70, fixed: true }
			];
			if (this.cm) { this.cm.purgeListeners(); delete this.cm; }
			this.cm = new Ext.grid.ColumnModel(cols);


			if (this.store) { this.store.purgeListeners(); delete this.store; }
			this.store = new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({ method: 'POST', url: 'shop.php' })
				, reader: new Ext.data.JsonReader({ root: 'data.Articles', totalProperty: 'totalRecords', id: 'Id' }, rec)
				, baseParams: { realm: 'Category', action: 'getSingleArticles', id: this.categoriesId }
			});
			this.sm = this.sm || new Ext.grid.RowSelectionModel({singleSelect: true});

			if (this.grid) { this.grid.destroy(false); }
			this.grid = new Ext.grid.Grid('prod-grid', {
				cm: this.cm
				, ds: this.store
				, selModel: this.sm
				, enableColLock: false
				, autoHeight: true
				, trackMouseOver: false
			});
			this.grid.on('rowclick', function() { var sm = this.getSelectionModel(); App.ArticleView.show(sm.getSelected().get('Id')); });
			this.grid.render();
			this.grid.getView().getRowClass = function(record, index) {
				return record.get('IsSoldOut') ? 'art-sold-out' : '';
			}

			// resize the grid, if required
			this.store.on('load', function() {
				Ext.get('prod-detail').update('<h3>Einzelne Artikel in dieser Warengruppe</h3>');
				var h = Ext.get(this.center.el.dom.parentNode).getHeight();
				var ch = Ext.get('prod-detail').getHeight();
				var gh = this.grid.container.getHeight();
				if (gh > h - ch - 24) {
					this.grid.autoHeight = false;
					this.grid.container.setHeight(h - ch - 24);
					this.grid.autoSize();
				}
			}, this);

			this.resizeGrid();
			this.store.load();
			layout.purgeListeners();
			layout.on('layout', function() {
				this.resizeGrid.defer(100, this);
			}, this);
		}

		, buildGrid: function(obj, param) {
			// retrieve data
			var r = Ext.decode(param.responseText), data = r.data;

			// update detail view
			var tpl = '';
			if (data.Images && data.Images.length) {
				tpl = new Ext.Template(
					'<div class="thumb-wrap" style="float:right;" id="{Filename}">' +
					'<div class="thumb"><img src="getImage.php?filename={Filename}" id="th_{Filename}" style="width:120px; height:120px;"></div></div>'
				).apply(data.Images[0]);
			}
			tpl = new Ext.Template(tpl + '<h3>{Name}</h3><p>{Description}</p><br style="clear:both;" />').apply(data);
			Ext.get('prod-detail').update(tpl);
			if (data.Images && data.Images.length) {
				Ext.QuickTips.register({
					target: Ext.get('th_' + data.Images[0].Filename)
					, autoHide: false
					, width: parseInt(data.Images[0].Width) + 20
					, title: 'Bild-Zoom'
					, text: zoomTemplate.apply(data.Images[0])
				});
			}


			// collect record fields and column model
			var fields = [{name: 'Id', type: 'int' }
				, { name: 'CatalogueId', type: 'string' }
				, { name: 'KeyId', type: 'string' }
				, { name: 'Name', type: 'string' }
				, { name: 'Netto1', type: 'float' }
				, { name: 'Netto2', type: 'float' }
				, { name: 'Netto3', type: 'float' }
				, { name: 'IsSoldOut', type: 'boolean' }
		  	];
			var cols = [
				/* { header: "ID", dataIndex: 'Id', width: 60, fixed: true, hidden: true } */
				{ header: "Kat.-Nr.", dataIndex: 'CatalogueId', width: 60, fixed: true }
				, { header: "Name", dataIndex: 'Name', width: 250 }
			];

			for(var i = 0, len = data.Features.length; i < len; i++){
				o = data.Features[i];
				fields.push({ name: 'feat-' + o.FeaturesId, type: 'string' });
				cols.push({ header: o.FeatureName, dataIndex: 'feat-' + o.FeaturesId });
			}
			cols.push({ header: "pro St./VE", dataIndex: 'Netto1', align: 'right', renderer: 'deMoney', width: 70, fixed: true });
			if (data.Quantity2 && data.Quantity2 != '0')
				cols.push({ header: "ab " + data.Quantity2 + " St./VE", dataIndex: 'Netto2', align: 'right', renderer: 'deMoney', width: 70, fixed: true });
			if (data.Quantity3 && data.Quantity3 != '0')
				cols.push({ header: "ab " + data.Quantity3 + " St./VE", dataIndex: 'Netto3', align: 'right', renderer: 'deMoney', width: 70, fixed: true });
			// kill old column model
			if (this.cm) { this.cm.purgeListeners(); delete this.cm; }
			this.cm = new Ext.grid.ColumnModel(cols);
			var rec = Ext.data.Record.create(fields);

			// kill old store
			if (this.store) { this.store.purgeListeners(); delete this.store; }
			this.store = new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({ method: 'POST', url: 'shop.php' })
				, reader: new Ext.data.JsonReader({ root: 'data.Articles', totalProperty: 'totalRecords', id: 'Id' }, rec)
				, baseParams: { realm: 'Product', action: 'getArticles', id: data.Id }
			});
			// resize the grid, if required
			this.store.on('load', this.resizeGrid, this);

			if (this.grid) {
				this.grid.destroy(false);
			}
			Ext.get('prod-grid').update('');
			this.grid = new Ext.grid.Grid('prod-grid', {
				cm: this.cm
				, ds: this.store
				, selModel: this.sm
				, enableColLock: false
				, autoHeight: true
				, trackMouseOver: false
				, maxRowsToMeasure: 5
			});
			this.grid.on('rowclick', function() {
				var rec = this.grid.getSelectionModel().getSelected();
				App.ArticleView.show(rec.get('Id'));
			}, this);
			this.grid.render();
			this.grid.getView().getRowClass = function(record, index) {
				return record.get('IsSoldOut') ? 'art-sold-out' : '';
			}

			this.store.load();
			layout.purgeListeners();
			layout.on('layout', function() {
				this.resizeGrid.defer(100, this);
			}, this);
		}

		, resizeGrid: function() {
			var h = Ext.get(this.center.el.dom.parentNode).getHeight();
			var ch = Ext.get('prod-detail').getHeight();
			var gh = this.grid.container.getHeight();
			if (gh > h - ch - 30) {
				this.grid.autoHeight = false;
				this.grid.container.setHeight(h - ch - 30);
			}
			this.grid.autoSize();
			this.grid.getView().fitColumns(true);
		}

		, createProductsPanel: function() {
			if (this.productsPanel) return this.productsPanel;
			var l = App.getLayout(), c = l.getRegion('center');
			l.beginUpdate();
				this.productsPanel = l.add('center', new Ext.ContentPanel('productsPanel', { autoCreate: true }, '<div id="innerWest"></div><div id="innerCenter"></div>'));
				layout = new Ext.BorderLayout(this.productsPanel.getEl(), {
					west: {
						title: 'Produkte'
						, split: true
						, initialSize: 300
						, autoScroll: true
						, titlebar: true
						, collapsible: true
						, minSize: 150
						, maxSize: 400
					}
					, center: {
						title: 'Produktdetails'
						, autoScroll: false
						, titlebar: true
					}
				});
				layout.add('west', this.west = new Ext.ContentPanel('innerWest', { title: 'Produkte in dieser Warengruppe', fitToFrame:true, closable:false, autoScroll: true }, '<div class="p05"><div id="prod-notice" class="x-box-mc"><p>&laquo; Bitte wählen Sie eine untergeordnete Warengruppe.</p><p>Klick auf den Ordnernamen oder das Pluszeichen öffnet den Zweig.</p></div><p><div id="prod-list"></div></p></div>'));
				layout.add('center', this.center = new Ext.ContentPanel('innerCenter', { title: 'Produktansicht', fitToFrame:true, closable:false, autoScroll: true }, '<div class="p05"><div id="prod-detail" class="x-box-mc" style="background: none"></div><p style="clear:both"></p><div id="prod-grid"></div></div>'));
			l.endUpdate();
			App.getLayout().on('layout', layout.layout, layout);
			return this.productsPanel;
		}
	}
}();
Ext.onReady(App.ProductView.init, App.ProductView);

