Ext.BLANK_IMAGE_URL = 'extjs/resources/images/default/s.gif';// reference local blank image
Ext.namespace('myExt', 'myExt.app');
var returnURL='http://www.emissionzero.ie/index.php?p=calculator';

myExt.app = function() {
	return {
		init: function() {
			Ext.QuickTips.init(); var q = Ext.QuickTips.getQuickTip(); q.showDelay = 20; q.trackMouse = true; q.hideDelay=0;  //q.interceptTitles=true;

			var actions = new Ext.ux.grid.RowActions({ header:'', actions:[{ iconCls:'icon_del', tooltip:'Remove', hideIndex:'!type' } ]});
			actions.on({ action:function(grid, record, action, row, col) { if (action=='icon_del') removeItem(record.data.id) }});
			
			var store = new Ext.data.Store({ id:'store', url: 'requests/cart.php', remoteSort: true, autoLoad:true,
				reader: new Ext.data.XmlReader({ record:'item', id:'id', totalRecords:'total' }, ['id', 'type','description','co2', 'cost' ]) 
			});
			store.on('load', function(){ 
				if (this.getCount()<=1){ 
					grid.hide(); paymentForm.hide(); 
					Ext.get('cartEmpty').setDisplayed(true);
					Ext.get('cartNotEmpty').setDisplayed(false);
				} 
				else { 
					grid.show(); paymentForm.show(); 
					Ext.get('cartEmpty').setDisplayed(false);
					Ext.get('cartNotEmpty').setDisplayed(true);
				} 
			});
//			store.load({});
			
			var colmodel = new Ext.grid.ColumnModel([ 
				actions,
				{ header: "Type", dataIndex: 'type', menuDisabled:true, resizable:false  },
				{ header: "Description", dataIndex: 'description', menuDisabled:true, resizable:false },
				{ header: "CO<sub>2</sub>", dataIndex: 'co2', menuDisabled:true, resizable:false, align:'right', width: 80 }, 
				{ header: "Cost", dataIndex: 'cost', menuDisabled:true, resizable:false, align:'right', width: 80, renderer: function(v){ return numberFormat(v,2); }}
			]); 
			
			var grid = new Ext.grid.GridPanel({ renderTo:'cartList', id:'cartList', store: store, title:'Your Cart', 
				stripeRows: true, loadMask:true, border:true, autoShow:true, autoHeight:true, maxHeight: 300, width:615, autoExpandColumn: 'fund',
				cm:colmodel, viewConfig: { scrollOffset:-2, forceFit:true, emptyText:'No data to display' }, plugins:[actions]
			});
			
			
			Ext.form.Field.prototype.msgTarget = 'side';
			var paymentForm = new Ext.myForm({ renderTo:'paymentForm', id:'paymentForm', title:'Payment Details',  width: 615, labelWidth:140, bodyStyle:'padding: 5px 0 0 5px;', 
			url:'requests/payment.php', waitMsgTarget:true, 
			layout: 'column', columns:2,
			items:[
				{ xtype:'fieldset', width:275, autoHeight:true, labelWidth:65, bodyStyle:'padding: 5px 0 10px 10px;', style:'margin-right:10px;',
//				title:'Personal Details', border:true, 
				border:false,
				defaults:{ allowBlank:false, width:150  }, 
				items:[
						{ fieldLabel: 'Full name', xtype:'textfield', name:'fullname' },
						{ fieldLabel: 'Email', xtype:'textfield', name:'email', vtype:'email' },
						{ fieldLabel: 'Mobile', xtype:'textfield', name:'mobile', allowBlank:true },
						{ labelSeparator:'', boxLabel:'Sign up for enewsletter', xtype:'checkbox', name:'newsletter', checked:true, ctCls: 'enewsletter' }
				]},
				{ xtype:'fieldset', width:345, autoHeight:true, labelWidth:140, bodyStyle:'padding: 5px 0 10px 10px',
//				title:'Credit card details', border:true, 
				border:false,
				defaults:{ allowBlank:false, width:150  }, 
				items:[
					{ fieldLabel: 'Card Type', xtype:'myCombo', hiddenName: 'cardtype', name:'card_type', id:'card_type', displayField: 'name', valueField: 'code', 
						store: new Ext.data.SimpleStore({ fields:['name','code'], data:[ ['Visa','visa'], ['Mastercard','mc'], ['American Express','amex'], ['Laser','laser'] ] }),
						listeners:{ select:function(){ showCVC; if (Ext.getCmp('cardnumber').getValue().length>0) Ext.getCmp('cardnumber').validate(); } }
					},
					{ fieldLabel: 'Cardholder name', name:'cardname', xtype:'textfield' },
					{ fieldLabel: 'Credit card number', name:'cardnumber', id:'cardnumber', xtype:'textfield', vtype:'card', minLength:12, maxLength:19 }, 
					new Ext.ux.MonthField({  
						fieldLabel:'Card expiry date', name:'expdate', format:'my', vtype:'cardDate', invalidText:'The card expiry date must be a valid future date in the format: MMYY' 
					}),
					{ fieldLabel: 'Card verification number', xtype:'numberfield', name:'cvc', id:'cvc', minLength:3, maxLength:4, width: 40 },
					{ xtype:'hidden', name:'co2', id:'co2' }, { xtype:'hidden', name:'amount', id:'amount' },
					{ xtype:'box', id:'loadingDiv', width:34, height:34, style:'margin:10px auto; ', hidden:true, autoEl:{ tag:'div', html:'<img src="img/icons/loading.gif">' } }
				]}
			],
			buttons:[
				{ text:'Pay now', handler: payment },
				{ text:'Cancel', handler: function(){ location.href=returnURL; } }
			]});			
			showCVC(0);
			
			
		}// end init
	};// end return
}(); // end app
Ext.onReady(myExt.app.init, myExt.app);


function payment(){
	var store=Ext.getCmp('cartList').getStore();
	var total=store.getAt(store.getCount()-1).data;
	
	var totalCost=total.cost.replace(/(<([^>]+)>)/ig,'');
	var co2=total.co2.replace(/(<([^>]+)>)/ig,'');
	try {	totalCost=totalCost.replace(/€/g,''); totalCost=totalCost.replace(/,/g,''); } catch(e){}
	try {	co2=co2.replace(/ tonnes/g,''); } catch(e){}
	totalCost=parseFloat(totalCost);
	co2=parseFloat(co2);
	
	Ext.getCmp('amount').setValue(totalCost);
	Ext.getCmp('co2').setValue(co2);
	var form=Ext.getCmp('paymentForm').getForm();
	if (form.isValid()){
		Ext.get('paymentForm').mask('Connecting to the bank system...'); 
		form.submit({ 
			failure: function(f,act){ 
				Ext.get('paymentForm').unmask(); 
				try {
					if (act.result.errors[0].id=='general') Ext.Msg.show({title:'System Error', msg:act.result.errors[0].msg, buttons: Ext.Msg.OK, icon: Ext.MessageBox.ERROR, width: 600 });
				} catch(e){ // most likely timeout 
					Ext.Msg.show({title:'System Error', msg:'Sorry, there is a problem with the payment engine at the moment. Please try again later. <br />No funds have been withdrawn from your account', buttons: Ext.Msg.OK, icon: Ext.MessageBox.ERROR, width: 600 });
				}
			}, 
			success: function(f,act){ Ext.get('paymentForm').mask('Generating your certificate...'); location.href='http://www.emissionzero.ie/index.php?p=cart-done' }
		});	
	}
}


function showCVC(show){
	var card=Ext.getCmp('card_type'), cvc=Ext.getCmp('cvc');
	if (card.getValue()=='laser' || !show){ cvc.disable(); cvc.hide(); cvc.getEl().up('.x-form-item').setDisplayed(false); }
	else { cvc.enable(); cvc.show(); cvc.getEl().up('.x-form-item').setDisplayed(true); }
}

function removeItem(id){ Ext.Ajax.request({ url: 'requests/cart.php', params:{ id:id, action:'delItem' },	success: function(resp){ Ext.getCmp('cartList').getStore().reload();	} }); }

