Ext.onReady(function(){
	Ext.QuickTips.init(); var q = Ext.QuickTips.getQuickTip(); q.showDelay = 20; q.trackMouse = true; q.hideDelay=0;  //q.interceptTitles=true;
	Ext.form.Field.prototype.msgTarget = 'side';
	
	// preconfigured combo
	Ext.form.myCombo = Ext.extend(Ext.form.ComboBox, { triggerAction: 'all', mode:'local', editable:false, emptyText:'Please select' });
	Ext.reg('myCombo', Ext.form.myCombo);	
	
	// hideTrigger fix for IE
	Ext.form.TriggerField.override({ afterRender : function(){ Ext.form.TriggerField.superclass.afterRender.call(this); var y; if(Ext.isIE && !this.hideTrigger && this.el.getY() != (y = this.trigger.getY())){ this.el.position(); this.el.setY(y); } }});
	
	// Comapnies' store
	var storeCompanies = new Ext.data.Store({ id:'storeCompanies', url: 'requests/companies.php', remoteSort: true, sortInfo : {field: "id", direction: "ASC"}, reader: new Ext.data.XmlReader({ record:'item', id:'id' }, ['id', 'name']) });
	storeCompanies.load();

	new Ext.FormPanel({ id:'signmeupForm', renderTo:'signmeup-box', border:false, bodyStyle:'background:0; margin:20px 30px 10px 30px;',
		defaultType:'textfield', labelWidth: 150, waitMsgTarget:'signmeup-box',
		defaults:{ width: 220, allowBlank:false, style:'margin-bottom:5px;', labelSeparator:'', validationEvent:false }, 
		reader : new Ext.data.XmlReader({ record: 'item' }, [ 'id' ]), monitorValid:true,
		url:'requests/signmeup.php', errorReader: new Ext.form.XmlErrorReader(),
		items:[
			{ fieldLabel:'First Name<sup class="required">*</sup>', name:'firstName' },
			{ fieldLabel:'Surname<sup class="required">*</sup>', name:'lastName' },
			{ fieldLabel:'Email<sup class="required">*</sup>', name:'email', vtype:'email' }, { xtype:'hint',style:'margin:-29px 0 3px;right:41px;' , text:'If you have a company email address, please use it when registering for a company programme.', title:'Info', width: 16, cls:'formHint' },
			/*{ xtype:'combo', fieldLabel: 'Company programme<sup class="required">*</sup>', hiddenName: 'programId', id:'companyCombo', store:storeCompanies, displayField:'name', valueField:'id', editable:false, typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'Pick your company', selectOnFocus:true, lazyRender: true, forceSelection:false, hiddenValue:0, tpl: '<tpl for="."><tpl if="id == 0"><hr /></tpl><div class="x-combo-list-item">{name}</div></tpl>'
, style:'margin-bottom:0;' },*/ 
			
			{ xtype:'checkbox', fieldLabel:'General Public', name:'general_public', id:'general_public', listeners:{'check':checkGeneral} },
			{ xtype:'label', html:'<b>OR</b>' },

			{ fieldLabel:'Company programme<sup class="required">*</sup>', store:storeCompanies, id:'companyCombo', hiddenName: 'programId', valueField: 'id', displayField: 'name', editable:true, hideTrigger:true, xtype:'myCombo',
				emptyText:'Enter your company name', mode:'remote', minChars:1, listWidth:300, 
				tpl: '<tpl for="."><div class="x-combo-list-item"><div style="float:right; #margin-top:-1px; clear:right;"></div>{name}</div></tpl>',
				listeners:{ 
					select: function(){  }, 
					blur: function(){  }, 
					beforequery:function(qe){ if (qe.query.length<1) { qe.combo.collapse(); return false } }
				}
			}, { xtype:'hint',style:'margin:-29px 0 3px;right:41px;' , text:'You need to be part of a company programme to be in with a chance to win Cycle Challenge prizes. You can still log your Cycle Challenge journeys but only registered companies can participate in the competition.', title:'Info', width: 16, cls:'formHint' },

			{ xtype:'checkbox', hideLabel:true, name:'t_c', boxLabel:' I accept the <a href="jl_faq.php#terms_and_conditions" target="_blank">Terms and Conditions</a> of use<sup class="required">*</sup>', width: 300, validator:function(){ return this.getValue();} },
			{ xtype:'label', html:'* Required', cls:'required' },
			{ name: 'action', id: 'actionField', xtype:'hidden', value:'register' }
		]
	});

});

/****************************************************************************************************/
// FUNCTIONS
/****************************************************************************************************/

function signmeupSubmit(){
	var form=Ext.getCmp('signmeupForm').getForm();
	form.submit({
		waitMsg:'Wait please...', 
		url:'requests/signmeup.php',
		failure: function(){  },
		success: function(){ location.href='jl_register_ty.php'; }
	});
}

function checkGeneral() {
	var companyCombo = Ext.getCmp('companyCombo');
	if(Ext.getCmp('general_public').getValue()) {
		companyCombo.allowBlank = true;
		companyCombo.disable();
	} else {
		companyCombo.allowBlank = false;
		companyCombo.enable();
	}
}

function checkCompEmail() {
	var aFormValues = Ext.getCmp('signmeupForm').getForm().getValues();
	var programId 	= aFormValues['programId'];
	var email 		= aFormValues['email'];

	// Form submitted when everything's allright.
	if (Ext.getCmp('general_public').getValue()) { signmeupSubmit(); }
	// A wrong company has been entered
	else if(programId=='') {
		Ext.Msg.alert('', 'Company Programme does not exist. If your company has been registered, it will appear on a list once you start typing its name. You can then select it from this list to proceed.');
	}
	// a company has been chosen
	else {
		Ext.Ajax.request({ url: 'requests/signmeup.php', method: 'post', params: { action:'checkCompEmail', programId:programId, email:email },
			success: function(response) {
				// Form submitted when everything's allright.
				if (response.responseText=='true') { signmeupSubmit(); } 
				
				else if (response.responseText!='false') {
					Ext.Msg.show({ title:'Programme Registration',  msg: 'Are you sure you wish to register for the ' + response.responseText + ' Journey Logger Programme?', buttons: Ext.Msg.YESNO, icon: Ext.MessageBox.WARNING, fn: function(btn){if (btn=='yes') {
						signmeupSubmit();
					} }});
				}
				// wrong email address
				else { Ext.Msg.alert('', 'You must use your company email to register for the company programme.'); }
			},
			failure: function() {}
		});
	}
}

function checkSignmeupForm() {
	var form		= Ext.getCmp('signmeupForm').getForm();
	var aFormValues = Ext.getCmp('signmeupForm').getForm().getValues();
	var email 		= aFormValues['email'];

	// if all the form fields are valid
	if (form.isValid()) {
		// Check if the email has already been used
		Ext.Ajax.request({ url: 'requests/signmeup.php', method: 'post', params: { action:'checkExistingEmail', email:email },
			success: function(response) {
				if (response.responseText=='true') { checkCompEmail(); } 
				// wrong email address
				else { Ext.Msg.alert('', 'This email address has already been used. Please choose another one.'); }
			},
			failure: function() {}
		});
	} else { Ext.Msg.alert('', 'Please fill in all the fields.'); }
}


// A reusable error reader class for XML forms
Ext.form.XmlErrorReader = function(){ Ext.form.XmlErrorReader.superclass.constructor.call(this, { record : 'field', success: '@success' }, ['id', 'msg' ] ); };
Ext.extend(Ext.form.XmlErrorReader, Ext.data.XmlReader);
