/*
 * Copyright(c) 2009, Soft Idiom Limtied
 * www.softidiom.com and www.4dsites.com
*/

//Ehances html form fields that contain an ext apptribute.

var Forms = {
	
	init: function() {
		Ext.BLANK_IMAGE_URL = '/shared/ext/v2.2/resources/images/default/s.gif';
		Ext.QuickTips.init();
		Forms.request = Ext.urlDecode(window.location.search.substring(1));
		Forms.page = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
		Forms.pageName = Forms.page.substring(0,Forms.page.lastIndexOf('.'));
		Forms.folders = window.location.pathname.split('/');
		Forms.parentFolder = Forms.folders[Forms.folders.length-3];
		Forms.folder = Forms.folders[Forms.folders.length-2];
		Forms.initStores();
		Forms.enhanceHTMLForms();
	},
		
	initStores: function() {
		//positions
		this.positionStore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: '/shared/php/get_positions.php'
			}),
			// create reader that reads the records
			reader: new Ext.data.JsonReader({
				root: 'results',
				totalProperty: 'total',
				id: 'NodeCode',
				fields: [
					{name: 'id', mapping:'NodeCode'},
					{name:'name', mapping:'ShortLabelE'}
				]
			}),
			sortInfo: {field:'id', direction:'ASC'},
			remoteSort: true
		});
		this.positionStore.load();
		//titles
		this.titleStore = new Ext.data.SimpleStore({
        fields: ['name'],
	        data : [['Mr'], ['Miss'], ['Mrs'],['Ms'],['Other (specify)']]
	    });
		//attendees
		this.attendeesStore = new Ext.data.SimpleStore({
        fields: ['name'],
	        data : [['Booker only (detailed above)'], ['Booker plus one guest (two in total)'], ['Two others (booker not attending)']]
	    });
		//an event loaded from an eventid in the request 
		this.eventStore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: '/shared/php/get_event.php'
			}),
			// create reader that reads the records
			reader: new Ext.data.JsonReader({
				root: 'results',
				totalProperty: 'total',
				id: 'id',
				fields: ['id','recordid','created','content','title','type','venue','memberprice','nonmemberprice','bookable']
			}),
			sortInfo: {field:'id', direction:'ASC'},
			remoteSort: true
		});
		this.eventStore.on('beforeload', function() {
			//mod rewrite uses /book/training|event|paid-event/EVENTNAME/EVENTDATE.html so "folder" is the eventname...
			this.eventStore.baseParams = {event: Forms.folder}
		},this);
		//...and "parentFolder" is the type of event (either "training" or "event");
		if(Forms.parentFolder == 'event' || Forms.parentFolder == 'training' || 'paid-event') { 
			this.eventStore.load();
		}
	},
	
	enhanceHTMLForms: function() {
		//find all form fields with an ext attribute and convert it into an Ext form field, using the properties defined in the attribute value
		Forms.getInputs();
		var items = '',sep = '';
		for (var i = 0; i < Forms.inputs.length; i++) {
			items+=(sep+'{applyTo:"'+Forms.inputs[i].getAttribute("id")+'",'+Forms.inputs[i].getAttribute("ext")+',id:\''+Forms.inputs[i].getAttribute("id")+'\'}');
			sep=',';
		}
		items = eval('['+items+']');
		this.form = new Ext.FormPanel({
			style: 'display:none',
	        items: items
		});
		this.form.render(document.body);
		/*if(Ext.isIE) {//for IE we need to show and hide the fields when a container is scrolled
			var containers = ['mcca-welcome','members-welcome','nonmembers-welcome','jobs-welcome','client-welcome','awards-welcome'];
			for (var c = 0; c < containers.length; c++) {
				var container = Ext.get(containers[c]);
				container.on('scroll',function() {
					for (var i = 0; i < items.length; i++) {
						var f = Ext.get(items[i].id);
						if(f) {
							f.hide();
							f.show();
						}
					}
				},this);
			}
		}*/

	},

	getInputs: function(){
		//Get all inputs that have an ext attribute
		this.inputs = [];
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].getAttribute("ext")) {
				this.inputs.push(inputs[i]);
			}
		}
		var textareas = document.getElementsByTagName("textarea");
		for (var i = 0; i < textareas.length; i++) {
			if (textareas[i].getAttribute("ext")) {
				this.inputs.push(textareas[i]);
			}
		}
	},

	attendeesField: function(field) {
		var form = field.el.id.split('-')[0];
		//if there any 2 and 3 contact fields, disable them initially then enable them based on the attendees field selection
		var attendeefields = [form+'-titleselect',form+'-title',form+'-firstname',form+'-surname',form+'-position',form+'-email'];
		for(i=0;i<attendeefields.length; i++) {
			var field2 = Ext.getCmp(attendeefields[i]+'2');
			if(field2) {field2.disable()}
			var field3 = Ext.getCmp(attendeefields[i]+'3');
			if(field3) {field3.disable()}
		}
		//configure event handler
		field.on('select',function(combo){
			var eventmembercostField = Ext.getCmp(form+'-eventmembercostdisplay');
			var eventtotalField = Ext.getCmp(form+'-eventtotaldisplay');
			if(combo.getValue() == 'Booker only (detailed above)') { //disable all attendee fields
				for(i=0;i<attendeefields.length; i++) {
					var field2 = Ext.getCmp(attendeefields[i]+'2');
					if(field2) {field2.disable();field2.reset();}
					var field3 = Ext.getCmp(attendeefields[i]+'3');
					if(field3) {field3.disable();field3.reset();}
				}
				if(eventtotalField && eventmembercostField) {
					eventtotalField.setValue(eventmembercostField.getValue())
				}
			} 
			if(combo.getValue() == 'Booker plus one guest (two in total)') { //disable all attendee3 fields
				for(i=0;i<attendeefields.length; i++) {
					var field2 = Ext.getCmp(attendeefields[i]+'2');
					if(field2) {field2.enable()}
					var field3 = Ext.getCmp(attendeefields[i]+'3');
					if(field3) {field3.disable();field3.reset();}
				}
				if(eventtotalField && eventmembercostField) {
					eventtotalField.setValue(eventmembercostField.getValue()*2)
				}
			}
			if(combo.getValue() == 'Two others (booker not attending)') { //enable all attendee fields
				for(i=0;i<attendeefields.length; i++) {
					var field2 = Ext.getCmp(attendeefields[i]+'2');
					if(field2) {field2.enable()}
					var field3 = Ext.getCmp(attendeefields[i]+'3');
					if(field3) {field3.enable()}
				}
				if(eventtotalField && eventmembercostField) {
					eventtotalField.setValue(eventmembercostField.getValue()*2)
				}
			}
 		});
	},

	//field specific functions
	titleField: function(field) {
		var form = field.el.id.split('-')[0];
		//if there is a form-title field, disable me until the user select "Other (specify)"
		var selectFieldName = form+'-'+(field.getName().replace(/title/,"titleselect"));
		var titleselect = Ext.getCmp(selectFieldName);
		if(titleselect) {
			field.disable();
			titleselect.on('select',function(combo) {
				if(titleselect.getValue() == 'Other (specify)') {
					field.enable();
					field.focus();
				} else {
					field.disable();
					field.setValue(titleselect.getValue());
				}
			});
		}
		return true;
	},
		
	emailconfirmValidator: function(field,value) {
		var form = field.el.id.split('-')[0];
		//if there is a form-password field, ensure this field value matches
		var emailField = Ext.getCmp(form+'-email');
		if(emailField && emailField.getValue() == value) {
			return true;
		}
		return 'The email entered here does not match the email entered in the email field.';
	},
		
	eventnamedisplay: function(field) {
		if(Forms.eventStore.getCount() > 0) {
			field.setValue(Forms.eventStore.getAt(0).data.title);
		}
		Forms.eventStore.on('load',function(s) {
			field.setValue(Forms.eventStore.getAt(0).data.title);
		})
	},

	eventmembercostdisplay: function(field) {
		if(Forms.eventStore.getCount() > 0) {
			field.setValue(Forms.eventStore.getAt(0).data.memberprice);
		}
		Forms.eventStore.on('load',function(s) {
			field.setValue(Forms.eventStore.getAt(0).data.memberprice);
		})
	},

	eventnonmembercostdisplay: function(field) {
		if(Forms.eventStore.getCount() > 0) {
			field.setValue(Forms.eventStore.getAt(0).data.nonmemberprice);
		}
		Forms.eventStore.on('load',function(s) {
			field.setValue(Forms.eventStore.getAt(0).data.nonmemberprice);
		})
	},

	eventdatedisplay: function(field) {
		//mod rewrite uses /book/training|event|paid-event/EVENTNAME/EVENTDATE.html so "pageName" is the eventdate
		var y = Forms.pageName.substring(0,4);
		var m = Forms.pageName.substring(5,7);
		var d = Forms.pageName.substring(8,10);
		field.setValue(d+'/'+m+'/'+y);
	},

	blackbookquantityValid: function(field) {
		//if there is a blackbookprice and backbooktotal field update it
		var form = field.el.id.split('-')[0];
		var price = Ext.getCmp(form+'-blackbookprice');
		if(!price) {return}
		var total = Ext.getCmp(form+'-blackbooktotal');
		if(!total) {return}
		total.setValue(price.getValue() * field.getValue());
	},

	blackbooktotalValid: function(field) {
		//if there is a blackbookprice and backbooktotal field update it
		var form = field.el.id.split('-')[0];
		var handytotal = Ext.getCmp(form+'-handybooktotal');
		if(!handytotal) {return}
		var grandtotal = Ext.getCmp(form+'-booktotal');
		if(!grandtotal) {return}
		grandtotal.setValue(handytotal.getValue() + field.getValue());
	},
		
	handybookquantityValid: function(field) {
		//if there is a blackbookprice and backbooktotal field update it
		var form = field.el.id.split('-')[0];
		var price = Ext.getCmp(form+'-handybookprice');
		if(!price) {return}
		var total = Ext.getCmp(form+'-handybooktotal');
		if(!total) {return}
		total.setValue(price.getValue() * field.getValue());
	},

	handybooktotalValid: function(field) {
		//if there is a blackbookprice and backbooktotal field update it
		var form = field.el.id.split('-')[0];
		var blacktotal = Ext.getCmp(form+'-blackbooktotal');
		if(!blacktotal) {return}
		var grandtotal = Ext.getCmp(form+'-booktotal');
		if(!grandtotal) {return}
		grandtotal.setValue(blacktotal.getValue() + field.getValue());
	},

	mustBeChecked: function(field) {
		//validator that ensures a checkbox is checked
		//console.log(field.getValue());
		if(field.getValue()) {
			return true;
		} else {
			return 'You must check this box to proceed';
		}
	},

	postForm: function(button) {
		button.disabled = true;
		var form = button.form;
		var flds = form.elements;
		var data = {form: form.name};
		var errors = [];
		for(i=0;i<flds.length; i++) {
			var f = flds[i];
			var extField = Ext.getCmp(f.id);
			if(extField && !extField.isValid()) {errors.push(extField.name)}
			if(f.name && extField) {
				if(extField.isXType('combo')) {
					data[f.name+'_id'] = extField.getValue();
					data[f.name] = extField.getRawValue();
				} else {
					data[f.name] = extField.getValue();
				}
			} else { //other non-ext fields
				data[f.name] = f.value;
			}
		}
		if(errors.length > 0) {
			button.disabled = false;
			Ext.Msg.show({
				title:'This Form Contains Errors',
				msg: 'Some of the information is missing or incorrect. Please correct the fields marked with<br /><br /><span class="x-form-invalid x-form-focus" style="padding:2px;">red underlines</span></b>',
				buttons: Ext.Msg.OK,
				icon: Ext.MessageBox.WARNING
			});
			return;
		}
		Ext.Ajax.request({
			url: '/shared/php/processFormPost.php',
			scope: this,
			params: {data: Ext.util.JSON.encode(data)},
			success: function(response, opts) {
		   	   //post failed, report the problem
			   if(!Ext.decode(response.responseText).success) {
			   	button.disabled = false;
				Ext.Msg.show({
					title:'Form Error',
					msg: 'We were unable to post this form due to the following error:<br /><br />'+Ext.decode(response.responseText).message,
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.WARNING
				});
				return;
			   }
				//post success - replace the form with the response
				form.parentNode.innerHTML = Ext.decode(response.responseText).message;
			},
			failure: function(response, opts) {
				button.disabled = false;
				Ext.Msg.show({
					title:'Failed to post this form',
					msg: 'We were unable to make a connection with our server. The may a be caused by a problem with your Internet connection or our server may be undergoing maintenace.<br /><br /><hr /><br /><b>Please wait a few minutes and try again. If the problem persists contact us for assistence.</b>',
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.WARNING
				});
			}
		});
	}
	
}

window.addEvent('domready', Forms.init)
