
var Contribute = function() {
	return {
		init: function() {
			//Set the global form properties
			Ext.QuickTips.init();
			Ext.form.Field.prototype.msgTarget = 'side';

			//Initialise the combo search
			this.initCombo();
			
			//Initialise the contribution form
			this.initForm();
		},
		
		initCombo: function() {
			//Set up the query
			this.store = new Ext.data.Store({
				url: SolidCMS.site.root + 'components/wishbox/data/contribute.php',
				params: {task: 'search'},
				reader: new Ext.data.JsonReader({
					 root: 'accounts',
					 totalProperty: 'total',
					 id: 'id'
				}, [
					'id',
					'description',
					'name_first', 'name_last', 'name_first2', 'name_last2',
					'occasion', 'location',
					{name: 'date', type: 'date', dateFormat: 'Y-m-d'}
				]),
				listeners: {
					'load': {
						scope: this,
						fn: this.onSearchLoaded
					}
				}
			});
	  
			// Custom rendering Template
			//this.template = Ext.XTemplate.from('searchtemplate');
			this.template = new Ext.XTemplate(
				'<tpl for=".">',
				'<div class="search-item">',
					'<table border="0" cellspacing="0" width="100%">',
					'<tr>',
						'<th>Name</th>',
						"<th>Partner's name</th>",
					'</tr>',
					'<tr>',
						'<td>{name_first} {name_last}',
						'<td>{name_first2} {name_last2}</td>',
					'</tr>',
					'<tr>',
						'<th>Event Date</th>',
						'<th>Event &amp; Location</th>',
					'</tr>',
					'<tr>',
						'<td>{date:date("M j, Y")}</td>',
						'<td>{occasion}<br />',
							'{location}</td>',
					'</tr>',
					'</table>',
				'</div>',
			'</tpl>');
			this.template.compile();
			
			this.combo = new Ext.form.ComboBox({
				 id: 'contribute_account_id',
				 store: this.store,
				 baseParams: {task: 'search'},
				 
				 displayField: 'description',
				 valueField: 'id',
				 tpl: this.template,

				 typeAhead: false,
				 forceSelection: true,
				 emptyText: '< Type here >',
				 loadingText: 'Searching...',
				 width: 475,
				 pageSize:10,
				 hideTrigger:true,
				 
				 minChars: 3,

				 applyTo: 'search',
				 itemSelector: 'div.search-item',
				 
				 listeners: {
					'select': {
						scope: this,
						fn: this.onAccountSelect
					}
				 }
			});
			
			//Re-position (IE 6/7 hack)
			if (Ext.isIE) {
				var el = Ext.get('search');				
				var pos = this.combo.getPosition();
				if (pos[1] == 0) {
					el.setY(356);
					//this.combo.setPosition(0, 323);
					//this.combo.syncSize();
				}
			}

		},
		
		//Initialise the 'accept a contribution' form
		initForm: function() {

			this.form = new Ext.form.FormPanel({
				id: 'formEdit',
				renderTo: 'contribute_form',
				layout: 'form',
				width: 500,
				
				//form
				disabled: true,
				labelAlign: 'right',
				waitMsgText: 'Processing Contribution - Please Wait...',
				waitMsgTarget: true,
				labelWidth: 200,
				baseCls: 'contribute',
				
				//layout
				deferredRender: false,
				bodyStyle: 'padding: 7px;',
				
				//panel 
				url: SolidCMS.site.root + 'components/wishbox/data/contribute.php',
				method: 'post',
				fileUpload: false,
				waitMsgTarget: true,
				
			
				items: [{
					xtype: 'numberfield',
					allowBlank: false,
					fieldLabel: 'Contribution Amount ($AU)',
					id: 'contribute_amount',
					name: 'contribute_amount',
					width: 75
				},{
					xtype: 'checkbox',
					id: 'contribute_anonymous',
					fieldLabel: '',
					labelSeparator: '',
					boxLabel: 'Do not disclose my contribution amount',
					name: 'contribute_anonymous'
				},{
					xtype: 'fieldset',
					title: 'Name of person/s making contribution',
					border: true,
					autoHeight: true,
					labelWidth: 120,
					
					items: [{
						xtype: 'textfield',
						fieldLabel: 'Name 1',
						name: 'contribute_name_first',
						width: 175,
						maxLength: 50
					},{
						xtype: 'textfield',
						fieldLabel: 'Name 2',
						name: 'contribute_name_last',
						width: 175,
						maxLength: 50
					},{
						xtype: 'textfield',
						allowBlank: false,
						fieldLabel: 'Email',
						id: 'contribute_email',
						name: 'contribute_email',
						width: 250,
						maxLength: 50,
						vtype: 'email'
					},{
						xtype: 'textarea',
						allowBlank: true,
						fieldLabel: 'Special Message',
						name: 'contribute_comments',
						width: 250
					}]
				},{
					xtype: 'checkbox',
					id: 'tandc',
					labelSeparator: '',
					fieldLabel: 'I agree to the <a href="/page/view/terms-and-conditions-14" target="_blank"><u>Terms and Conditions</u></a>',
					name: 'agree_tandc',
					allowBlank: false
				}]

				/*
				},{
					xtype: 'fieldset',
					title: 'Credit Card Details',
					border: true,
					autoHeight: true,
					labelWidth: 120,
					
					items: [{
						xtype: 'textfield',
						allowBlank: false,
						fieldLabel: 'Name on card',
						id: 'contribute_ccard_name',
						name: 'contribute_ccard_name',
						value: '',
						width: 250
					},{
						
						layout: 'column',
						border: false,
						baseCls: 'contribute',
						defaults: {border: false, baseCls: 'contribute'},

						items: [{
							width: 295,
							layout: 'form',
							items: [{
								xtype: 'textfield',
								allowBlank: false,
								fieldLabel: 'Card Number',
								id: 'contribute_ccard_number',
								name: 'contribute_ccard_number',
								value: '',
								width: 150,
								maskRe: /[0-9\s]/
							}]
						},{
							width: 110,
							labelWidth: 40,
							layout: 'form',
							items: [{
								xtype: 'textfield',
								allowBlank: false,
								fieldLabel: 'CVV',
								id: 'contribute_ccard_cvv',
								name: 'contribute_ccard_cvv',
								value: '',
								width: 35,
								maskRe: /[0-9]/
							}]
						}]
					},{
						layout: 'column',
						border: false,
						baseCls: 'contribute',
						defaults: {border: false, baseCls: 'contribute'},

						items: [{
							width: 227,
							layout: 'form',
							items: [{
								xtype: 'combo',											
								id: 'contribute_ccard_month_display',
								name: 'contribute_ccard_month_display',
								hiddenName: 'contribute_ccard_month',
								fieldLabel: 'Expiry Date',
								
								mode: 'local',
								store: this.getCcardMonths(),
								
								triggerAction: 'all',
								allowBlank: false,
								selectOnFocus: false,
								editable: false,
								width: 80
							}]
						},{
							width: 175,
							layout: 'form',
							items: [{
								xtype: 'combo',											
								id: 'contribute_ccard_year',
								name: 'contribute_ccard_year',
								hideLabel: true,
								
								mode: 'local',
								store: this.getCcardYears(),
								displayField: 'text',
								
								triggerAction: 'all',
								allowBlank: false,
								selectOnFocus: false,
								editable: false,
								width: 75
							}]
						}]
					},{
						xtype: 'checkbox',
						id: 'contribute_anonymous',
						fieldLabel: '',
						labelSeparator: '',
						boxLabel: 'Do not disclose my contribution amount',
						name: 'contribute_anonymous'
					},{
						xtype: 'checkbox',
						id: 'tandc',
						fieldLabel: '',
						labelSeparator: '',
						boxLabel: 'I agree to the <a href="/page/view/terms-and-conditions-14" target="_blank"><u>Terms and Conditions</u></a>',
						name: 'agree_tandc',
						allowBlank: false
					}]
				}]
				*/
				
			});
			

			this.form.render();

			//Mask the form
			//Ext.get('contribute').mask('Search for a Wishbox account in the text field above.');

		},

		getCcardMonths: function() {
			return [[1,'January'],[2,'February'],[3,'March'],[4,'April'],[5,'May'],[6,'June'],[7,'July'],[8,'August'],[9,'September'],[10,'October'],[11,'November'],[12,'December']];
		},
		getCcardYears: function() {
			var years = [];
			var now = new Date();
			var current = now.getFullYear();
			for (var i=current; i<(current+20); i++) {
				years.push(i);
			}
			return years;
		},
		
		onSearchLoaded: function(store, records, options) {
			var instructions = Ext.get('instructions');
			if (store.getTotalCount() > 0) {
				instructions.update('');
			} else {
				instructions.update('<label style="color: #ffaaaa;">No matching accounts were found...</font>');
			}
		},
		
		onAccountSelect: function(combo, record, index) {
			//Display the account details
			this.template.overwrite('contribute_details', record.data);
			//Enable the form
			Ext.get('contribute').show();
			Contribute.form.enable();
			//Move the focus to the contribution box
			Contribute.form.getForm().findField('contribute_amount').focus.defer(1000, Contribute);
			
		return true;
		},
		
		//Send the contribution
		contribute: function() {
			
			var tandc = Ext.getCmp('tandc');
			if (tandc.checked == false) {
				Ext.MessageBox.alert('Terms and Conditions', 'You must agree to the terms and conditions before we can accept your contribution.');
			} else {
				//Mask the form
				Ext.get('contribute').mask('Processing contribution - please wait...', 'x-mask-loading');
				
				var params = {task: 'contribute'};
				
				//Fetch the selected account
				var frm = this.form.getForm();
				var cmb = Ext.getCmp('contribute_account_id');
				params.account_id = cmb.getValue();
				
				if (params.account_id <= 0) {
					this.form.getForm().findField('contribute_account_id').focus();
					Ext.MessageBox.alert('No Wishbox Accunt Selected','Please select an account first.');
				} else {
					//Submit the form
					this.form.getForm().submit({
						params: params,
						success: this.onContributed,
						failure: this.onContributed,
						scope: this,
						clientValidation: true,
						waitMsgTarget: true
					});
				}
			}
		},
		onContributed: function(form, action) {
			
			//Make sure the form submitted correctly
			if (SolidCMS.Utilities.data.formResponse(action) == false) {
				//Unmask the form
				Ext.get('contribute').unmask();
			} else {
				//Display the receipt page
				window.location = SolidCMS.site.root  + 'wishbox/contribute/paypal/' + action.result.id;
			}
		}
		
	};
}();

//Start when document ready
Ext.onReady(
	function() {
		//Set the blank image
		Ext.BLANK_IMAGE_URL = SolidCMS.site.root + 'admin/images/spacer.gif';
		//Load the component
		Contribute.init();
	}, Contribute, true
);
