App.Checkout = function() {
	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();
	};

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

	var cm = new Ext.grid.ColumnModel([
		{ header: "Kat.-Nr.", dataIndex: 'CatalogueId', width: 50 }
		, { header: "Bezeichnung", dataIndex: 'Name', width: 247 }
		, { header: "Anzahl", dataIndex: 'Quantity', width: 50, align: 'center' }
		, { header: "Preis/VE", dataIndex: 'Netto', width: 65, align: 'right', renderer: 'deMoney' }
		, { header: "Netto", dataIndex: 'Sum', width: 65, align: 'right', renderer: 'deMoney' }
		, { header: "USt", dataIndex: 'Vat', width: 47, align: 'center', renderer: 'percent' }
		, { header: "Brutto", dataIndex: 'Brutto', width: 65, align: 'right', renderer: 'deMoney' }
	]);
	
	return {
		panel1: null
		, panel2: null
		, form1: null
		, store: null
		, Shipping: null
		
		, step1: function() {
			var l = App.getLayout(), c = l.getRegion('center');
			App.nextStep = this.step2.createDelegate(this);
			var x = App.User.getIsAuthenticated();
			if (x) {
				App.Profile.edit();
			} else {
				App.User.showLoginDialog({
					fn: App.Profile.edit,
					scope: App.Profile
				});
			}
		}

		, step2: function() {
			var l = App.getLayout(), c = l.getRegion('center');
			if (! this.gridPanel) {
				l.beginUpdate();
					this.gridPanel = c.add(new Ext.ContentPanel('checkout-grid-panel'
						, { autoCreate: true, preservePanel: true }
						, App.templates.getFormTemplate().apply({ formTitle: 'Zusammenfassung Ihrer Bestellung'
							, formHeadId: 'checkout-grid-form-head'
							, formBodyId: 'checkout-grid-form-body'
							, formFootId: 'checkout-grid-form-foot'
						})
					));
				l.endUpdate();
				this.form1 = new Ext.form.Form({ url: 'shop.php', baseParams: { realm: 'Basket' } });
				this.form1.waitMsgTarget = true;
				this.form1.on('actioncomplete', this.step3, this);
				this.store = new Ext.data.Store({
					proxy: new Ext.data.HttpProxy(new Ext.data.Connection({url: 'shop.php', method: 'post', timeout: 3000, extraParams: { realm: 'basket' } }))
					, reader: new Ext.data.JsonReader({ root: 'records', id: 'Id', record: 'Record' }, rec)
				});
				this.store.on('load', this.onStoreLoad, this);
				this.form1.add(new Ext.form.Layout({ id: 'checkout-grid', style: 'border: 1px solid #ACA899' }));
				this.form1.addButton('<b>Fortfahren</b>').on('click', this.step3, this);
				this.form1.addButton('Zurück').on('click', this.step1, this);
				this.form1.render('checkout-grid-form-body');
				this.grid = new Ext.grid.Grid('checkout-grid', {
					cm: cm
					, ds: this.store
					, autoResize: false
					, enableColumnMove: false
					, enableColumnHide: false
					, enableColumnResize: false
					, trackMouseOver: false
				});
				this.grid.render();
			}
			c.showPanel(this.gridPanel)
			this.store.load();
		}
		
		, onStoreLoad: function(store, records, options) {
			var ft = this.grid.getView().getFooterPanel(true);
			var data = store.reader.jsonData;
			this.Shipping = data.shipping;
			if (! (data.shipping && data.summary && store.getCount())) {				
				ft.update('');
				return;
			}
			var tpl = getRowTemplate();
			ft.update('<div class="x-layout-panel-south basket-summary">'
				+ tpl.apply(data.shipping)
				+ tpl.apply(data.summary)
				+ '</div>'
			);
			this.grid.autoSize();
		}
		
		, step3: function() {
			var l = App.getLayout(), c = l.getRegion('center');
			if (! this.panel2) {
				l.beginUpdate();
					this.panel2 = c.add(new Ext.ContentPanel('checkout-panel2', { autoCreate: true, preservePanel: true }, App.templates.getFormHtml()));
				l.endUpdate();
				Ext.get('form-heading').update('Zusätzliche Informationen');
				var form = new Ext.form.Form({ url: 'shop.php', baseParams: { realm: 'Basket', action: 'checkout', Method: 0 } });
				form.waitMsgTarget = true;
				form.fieldset({ hideLabels: true, legend: 'Versandanschrift (falls abweichend)' },
					new Ext.form.TextArea({ name: 'ShippingAddress', allowBlank: true, grow: true, width: 588, value: App.User.getData().ShippingAddress || '' })
				);
				form.fieldset({ hideLabels: true, legend: 'Anmerkungen' },
					new Ext.form.TextArea({ name: 'Annotation', width: 588, allowBlank: true, grow: true })
				);
				form.fieldset({ hideLabels: true, legend: 'Liefer- und Versandkosten' }
					, new Ext.form.Layout({ id: 'checkout-info' })
				);
				form.fieldset({ hideLabels: true, legend: 'Auswahl der Zahlweise' });
					this.cbzInv = new Ext.form.Radio({ name: 'ppMethod', checked: true, boxLabel: '<span ext:qtip="<b>Sie erhalten eine Rechnung per eMail, Warenversand erfolgt nach Zahlungseingang.</b>">Zahlung per Rechnung</span>' });
                    this.cbzLoc = new Ext.form.Radio({ name: 'ppMethod', boxLabel: '<span ext:qtip="<b>Sie holen die bestellte Ware in unserem Ladenlokal in Zwickau ab.</b>">Abholung im Ladenlokal</span>' });
                    this.cbzPpl = new Ext.form.Radio({ name: 'ppMethod', boxLabel: '<span ext:qtip="<b>Zahlung per PayPal, Versand erfolgt nach Bestätigung ihrer Zahlung durch PayPal.</b>">Zahlung via PayPal</span>' });
					form.add(this.cbzInv, this.cbzLoc, this.cbzPpl);
				form.end();
                form.fieldset({ hideLabels: true, legend: 'AGB und Lieferbedingungen' });
                    this.cbAgb = new Ext.form.Checkbox({ name: 'AGB', checked: false, boxLabel: '<span class="important" ext:qtip="<b>Sie müssen unseren Geschäfts- und Lieferbedingungen zustimmen, sonst ist keine Bestellung möglich.</b>">Ja, ich habe die <a href="javascript:App.Viewer.AGB();" ext:qtip="Klicken, um die Allgemeinen Geschäfts- und Lieferbedingungen in einem separaten Fenster anzeigen">AGB</a> zur Kenntnis genommen und bin mit ihnen einverstanden.</span>' });
                    form.add(this.cbAgb);
                form.end();
				form.addButton({
					text: '<b>Absenden</b>'
					, handler: function() {
						form.submit({ waitMsg: 'Daten werden übertragen ...' });
					}
				});
				form.addButton('Zurück').on('click', this.step2, this);
				form.render('form-body');
				form.on('beforeaction', this.onBeforeAction, this);
				form.on('actioncomplete', this.onActionComplete, this);
			}
			Ext.get('checkout-info').update('<div class="x-form-item"><div class="x-form-element" style="padding-left: 0;">'+this.Shipping.infoText+'</div></div><div class="x-form-clear-left"></div>');
			if (c.hasPanel(this.panel2))
				c.showPanel(this.panel2)
		}
		
		, onBeforeAction: function(form, action) {
			// let load action pass
			if (action.type != 'submit') return;
			// let checked state pass
			if (this.cbAgb.getValue()) {
                if (this.cbzLoc.getValue()) form.baseParams.Method = 1;
                if (this.cbzPpl.getValue()) form.baseParams.Method = 2;

                return true;
            } else {
                Ext.MessageBox.alert('Hinweis', 'Wenn Sie unseren AGB nicht zustimmen,<br />können wir Ihre Bestellung nicht entgegennehmen.');
                return false;
            }
		}
		
		, onConfirm: function() {
			form.submit({ waitMsg: 'Daten werden übertragen ...' });
		}
		
		, onActionComplete: function(form, action) {
			if (action.type != 'submit') return;
            var data = Ext.decode(action.response.responseText || '[]');
               if (data.Method == 2) {
                ppUrl = 'classes/paypal.php?action=process';
                ppUrl = ppUrl + '&basketId='+data.basketId;
                ppUrl = ppUrl + '&Amount='+data.totalBrutto;
                // ppWin = window.open(ppUrl, '_blank','');
                // window.document.URL = ppUrl;
                location.replace(ppUrl);
            }

			App.Basket.dropAllArticles();
			App.info.msg('Nachricht', 'Vielen Dank für Ihre Bestellung. Sie erhalten in Kürze eine Bestellbestätigung per E-Mail.', 5);
			App.home();
		}
	}
}();


