App.Basket = function() {
	/**
	 * The closure class invisible to outside
	 */
	// private:
	var dialog = null,
		printDialog = null,
		f = null,
		grid = null,
		b = {},
		isIntialized = false;

	var rec = Ext.data.Record.create([
   		{name: 'ArticlesId', type: 'int'}
   		, {name: 'CatalogueId', type: 'string'}
   		, {name: 'KeyId', type: 'string'}
   		, {name: 'Name', type: 'string'}
		, {name: 'Quantity', type: 'float'}
   		, {name: 'Netto', type: 'float'}
   		, {name: 'Sum', type: 'float'}
   		, {name: 'Vat', type: 'float'}
   		, {name: 'Brutto', type: 'float'}
  	]);

	var conn = new Ext.data.Connection({url: 'shop.php', method: 'post', timeout: 3000, extraParams: { realm: 'basket' } });
	var store = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy(conn),
		reader: new Ext.data.JsonReader({
			root: 'records',
			id: 'ArticlesId',
			record: 'Record',
			totalProperty: 'totalRecords'
		}, rec)
	});

	function getRowTemplate() {
		return new Ext.Template(
'<div class="x-grid-body" style="height: 20px;">' +
'	<table cellspacing="0" cellpadding="0" border="0">' +
'		<tbody>' +
'			<tr class="x-grid-row {Cls}">' +
'				<td tabindex="0" class="x-grid-col x-grid-td-0 x-grid-cell-0-0">' +
'					<div class="x-grid-col-0 x-grid-cell-inner">' +
'						<div unselectable="on" class="x-grid-cell-text">{Pos}</div>' +
'					</div>' +
'				</td>' +
'				<td tabindex="0" class="x-grid-col x-grid-td-1 x-grid-cell-0-1">' +
'					<div class="x-grid-col-1 x-grid-cell-inner">' +
'						<div unselectable="on" class="x-grid-cell-text">{Name}</div>' +
'					</div>' +
'				</td>' +
'				<td tabindex="0" class="x-grid-col x-grid-td-2 x-grid-cell-0-2">' +
'					<div class="x-grid-col-2 x-grid-cell-inner">' +
'						<div unselectable="on" class="x-grid-cell-text">{Count}' +
'						</div>' +
'					</div>' +
'				</td>' +
'				<td tabindex="0" class="x-grid-col x-grid-td-3 x-grid-cell-0-3">' +
'					<div class="x-grid-col-3 x-grid-cell-inner">' +
'						<div unselectable="on" class="x-grid-cell-text">{Netto:deMoneyEmpty}</div>' +
'					</div>' +
'				</td>' +
'				<td tabindex="0" class="x-grid-col x-grid-td-4 x-grid-cell-0-4">' +
'					<div class="x-grid-col-4 x-grid-cell-inner">' +
'						<div unselectable="on" class="x-grid-cell-text">{Sum:deMoney}</div>' +
'					</div>' +
'				</td>' +
'				<td tabindex="0" class="x-grid-col x-grid-td-5 x-grid-cell-0-5">' +
'					<div class="x-grid-col-5 x-grid-cell-inner">' +
'						<div unselectable="on" class="x-grid-cell-text">{Vat:percent}</div>' +
'					</div>' +
'				</td>' +
'				<td tabindex="0" class="x-grid-col x-grid-td-6 x-grid-cell-0-6">' +
'					<div class="x-grid-col-6 x-grid-cell-inner">' +
'						<div unselectable="on" class="x-grid-cell-text">{Brutto:deMoneyEmpty}</div>' +
'					</div>' +
'				</td>' +
'			</tr>' +
'		</tbody>' +
'	</table>' +
'</div>').compile();
	};

	function getDialog() {
		if (! dialog) {
			// build the dialog
			var colModel = new Ext.grid.ColumnModel([
				{ header: "Kat.-Nr.", dataIndex: 'CatalogueId', width: 50, resizable: false, sortable: false }
				, { header: "Name", dataIndex: 'Name', width: 217, resizable: false, sortable: false }
				, { header: "Anzahl", dataIndex: 'Quantity', width: 50, align: 'center', resizable: false, sortable: false, 
					editor: new Ext.grid.GridEditor(new Ext.form.NumberField({ selectOnFocus: true, allowDecimals: false, allowNegative: false, maxLength: 3 })) }
				, { header: "Preis/VE", dataIndex: 'Netto', width: 65, align: 'right', renderer: 'deMoney', resizable: false, sortable: false }
				, { header: "Netto", dataIndex: 'Sum', width: 65, align: 'right', renderer: 'deMoney', resizable: false, sortable: false }
				, { header: "USt.", dataIndex: 'Vat', width: 47, align: 'right', renderer: 'percent', resizable: false, sortable: false }
				, { header: "Brutto", dataIndex: 'Brutto', width: 65, align: 'right', renderer: 'deMoney', resizable: false, sortable: false }
			]);
		
			var selModel = new Ext.grid.RowSelectionModel({singleSelect: true});

			var d = new Ext.LayoutDialog(Ext.id(), {
				autoCreate: true
				, title: 'Warenkorb'
				, width: 600
				, height: 250
				, minHeight: 220
				, maxHeight: 600
				, modal:false
				, resizable:true
				, resizeHandles: 's' 
				, draggable:true
				, shadow:true
				, collapsible: false
				, center: { autoTabs: false, autoScroll: false }
			});
			Ext.DomHelper.append(d.body, { html: '<div id="basket-items"></div><div id="basket-info" class="x-grid-bottombar" style="display: block !important;"></div>' });
			b.del = d.addButton({ id: 'del', text:'Löschen', tooltip:'Ausgewählte Position löschen', disabled: true }, dropArticle, App.Basket);
			b.delall = d.addButton({ id: 'delall', text:'Alle löschen', tooltip:'Alle Artikel aus dem Warenkorb entfernen' }, function(){
				dropAllArticles();
				dialog.hide();
			});
			b.submit = d.addButton({ id: 'submit', text:'Aktualisieren'}, onSubmit);
			b.print = d.addButton({ id: 'print', text:'Druckansicht'}, showPrintDialog);
			b.checkout = d.addButton({ id: 'checkout', text:'Zum Bestellvorgang'}, function(){
				dialog.hide();
				App.Checkout.step1();
			});
			selModel.on('rowselect', b.del.enable, b.del);
			
			// build the grid
			grid = new Ext.grid.EditorGrid('basket-items', {
				ds: store,
				cm: colModel,
				selModel: selModel,
				autoResize: false,
				enableColumnMove: false,
				enableColumnHide: false,
				enableColumnResize: false
			});
			grid.render();
			grid.on('afteredit', b.submit.enable, b.submit);
			var l = d.getLayout();
			l.beginUpdate();
				l.add('center', new Ext.GridPanel(grid));
			l.endUpdate();
			isInitialized = true;
			dialog = d;
		}
		return dialog;
	}
	
	function onStoreLoad(store, records, options) {
		updateSummary(store);
		this.fireEvent('loaded', store.getCount() > 0);
		if (! dialog) return;
		grid.getSelectionModel().clearSelections();
		b.submit.disable();
		b.del.disable();
		if (1 > store.getCount()){
			b.delall.disable();
			b.checkout.disable();
		}
		else{
			b.delall.enable();
			b.checkout.enable();
		}
		var f = grid.getView().getFooterPanel(true);
		var data = store.reader.jsonData;
		if (data.info && data.info.articlesRemoved){
			Ext.MessageBox.alert('Hinweis', 'Es wurden ' + data.info.articlesRemoved + ' Artikel aus dem Warenkorb entfernt,<br/>weil keine Bestellberechtigung besteht.');
		}
		if (! (data.shipping && data.summary && store.getCount())) {
			f.update('');
			return;
		}
		var t = getRowTemplate();
		f.update('<div class="x-layout-panel-south basket-summary">'
			+ t.apply(data.shipping)
			+ t.apply(data.summary)
			+ '<p style="margin:5px;">Auswahl einer Zeile aktiviert den Löschen-Knopf. Felder der Spalte "Anzahl" können per Doppelklick bearbeitet werden. <b>Nach Abschluss der Bearbeitung "Aktualisieren" klicken, um die Änderungen zu speichern.</b></p>'
			+ '</div>'
		);
		grid.autoSize();
	}

	function show(){
		if (! store.getCount()) return;
		getDialog().show();
		store.load();
	}
	
	function hide(){
		getDialog().hide();
	}

	function onSubmit(e) {
		var mr = grid.getDataSource().getModifiedRecords();
		var conn = new Ext.data.Connection();
		var data = new Array;
		for (var index in mr) {
			data.push(mr[index].data);
		}
		store.load({ params: { action: 'update', data: Ext.util.JSON.encode(data) } });
	}
	
	function addArticle(ArticlesId, Quantity) {
		store.load({params: { action: 'add', articlesId: ArticlesId, quantity: Quantity } });
	}
	
	function dropArticle() {
		var sel = grid.getSelectionModel();
		if (! sel.hasSelection()) {
			App.info.msg('Hinweis', 'Kein Artikel gewählt');
			return;
		}
		var row = sel.getSelected();
		store.load({ params: { action: 'drop', ArticlesId: row.id } });
	}

	function dropAllArticles() {
		store.load({params: { action: 'empty' } });
		hide();
	}

	function updateSummary() {
		Ext.get('basket-count').update(store.getCount() || '&mdash;');
		Ext.get('basket-panel').stopFx().highlight().highlight();
	}
	
	function updatePrices() {
		store.load({params: { action: 'updatePrices' } });
	}
	
	function getPrintDialog() {
		if (! printDialog){
			printDialog = new Ext.BasicDialog(Ext.id(), {
				autoCreate: true,
				title: 'Druckansicht',
				width: 700,
				height: 400,
				resizable:false,
				modal:true,
				shadow:true,
				collapsible: false
			});
			printDialog.body.update('<iframe id="basket-print" frameborder="0" border="0" style="width:676px; height:322px; border:1px solid silver; background:white;"></iframe>');
			printDialog.addButton({ text:'Drucken', handler: printIfr, scope: this });
		}
		return printDialog;
	}

	function showPrintDialog(){
		var d = getPrintDialog(), doc = Ext.fly('basket-print').dom.contentWindow.document;
		var tpl = new Ext.Template(
			'<tr>' +
			'<td class="c">{CatalogueId}</td>' +
			'<td class="c">{KeyId}</td>' +
			'<td class="l">{Name:ellipsis(50)}</td>' +
			'<td class="c">{Quantity}</td>' +
			'<td class="r">{Netto:deMoney}</td>' +
			'<td class="r">{Sum:deMoney}</td>' +
			'<td class="r">{Vat:percent}</td>' +
			'<td class="r">{Brutto:deMoney}</td>' +
			'</tr>'
		).compile();
		d.show();
		doc.open();
		doc.write('<html><head><style>body,th,td{font:11px Tahoma,Arial,sans-serif}th,td{border:1px solid dimgray;padding:2px 8px;}th{font-weight:bold;}.l{text-align:left;}.r{text-align:right;}.c{text-align:center;}table{width:640px;border:0px none;border-collapse:collapse}</style></head><body>');
		doc.write('<table cellspacing="0" rules="all">');
		doc.write('<thead><tr>' +
			'<th class="c">Kat.-Nr.</th>' +
			'<th class="c">Schl.-Nr.</th>' +
			'<th class="l">Name</th>' +
			'<th class="c">Anzahl</th>' +
			'<th class="r">Preis/VE</th>' +
			'<th class="r">Netto</th>' +
			'<th class="r">USt.</th>' +
			'<th class="r">Brutto</th>' +
			'</thead><tbody>'
		);
		store.each(function(record){
			doc.write(tpl.apply(record.data));
		})
		doc.write('</tbody></table></body></html>');
		doc.close();
	}

	/*
	Return the Iframes window object
	*/
	function getIfrWindow(){
		var dom = Ext.fly('basket-print').dom;
		return dom
			? dom.contentWindow || window.frames[dom.name]
			: null;
	}
	
	/*
	Print the contents of the Iframes (if we own the document)
	*/
	function printIfr(){
		try{
			var win = getIfrWindow();
			if(Ext.isIE){
				win.focus();
			}
			win.print();
		} catch(ex){
			console.log('print exception: ' + (ex.description || ex.message || ex));
		}
	}
	
	
	/**
	 * The public interface
	 */
	return Ext.apply(new Ext.util.Observable, {
		events: {
			'loaded': true
		},
		
		init: function(){
			Ext.fly('basket-panel').on('click', this.show, this);
			App.User.on('logout', dropAllArticles, this);
			App.User.on('login', updatePrices, this);
			store.on('load', onStoreLoad, this);
			this.on('loaded', App.Toolbar.onBasketLoaded, this);
			store.load();
		},
		
		show: show,
		
		updatePrices: updatePrices,
		
		addArticle: addArticle,
		
		dropAllArticles: dropAllArticles
	})
}();

Ext.onReady(App.Basket.init, App.Basket);

