Ext.namespace('Jack');

Jack = function() {
	// Private functions and variables go here.
	var localFirstName;
	var localLastName;
	var localUsername;
	var localEmail;
	var localUserId;
	var localMemberId;
	var localLoggedIn;
	var localUserType;
	var localTypeId;
	var localTypeName;
	var localPhone;
	var localAddress1;
	var localAddress2;
	var localCity;
	var localStateId;
	var localStateAbbrev;
	var localStateName;
	var localZip;
	var appLocalTemplate;
	var appAMPUrl;
	
	var smallFieldWidth = 59;
	var mediumFieldWidth = 92;
	var largeFieldWidth = 150;
	var XLFieldWidth = 202;
	var XXLFieldWidth = 305;
	var frmWidth = 150;
	var labelWidth = 150; 
	var smallLabelWidth = 100;
	var gridHeight = 500; 

	// Default values.  These are overriden by site configuration in the init method
	var loggedInOnly = false;
	var topBottom = 'bottom';
	var ampBarEnabled = true;
	
	var localChangePassword = false;
	
	// used for the custom Jack alert message
	var msgCt;
		
	// Public functions and variables go here.
	return {
		init: function(SiteParams) {
			Ext.QuickTips.init();
		    Ext.form.Field.prototype.msgTarget = 'qtip';
			
			Ext.Msg.minWidth = 350;
			
			localUserId = SiteParams.USER_ID;
			localFirstName = SiteParams.FIRST_NAME;
			localLastName = SiteParams.LAST_NAME;
			localUsername = SiteParams.USERNAME;
			localEmail = SiteParams.EMAIL;
			localMemberId = SiteParams.MEMBER_ID;
			localLoggedIn = SiteParams.LOGGEDIN;
			localUserType = SiteParams.USER_TYPE;
			localTypeId = SiteParams.TYPE_ID;
			localTypeName = SiteParams.TYPE_NAME;
			localPhone = SiteParams.PRIMARY_PHONE;
			localAddress1 = SiteParams.PRIMARY_ADDRESS1;
			localAddress2 = SiteParams.PRIMARY_ADDRESS2;
			localCity = SiteParams.PRIMARY_CITY;
			localStateId = SiteParams.PRIMARY_STATE_ID;
			localStateAbbrev = SiteParams.PRIMARY_STATE_ABBREV;
			localStateName = SiteParams.PRIMARY_STATE_NAME;
			localZip = SiteParams.PRIMARY_ZIP;

			appAMPUrl = SiteParams.AMP_URL;
			appLocalTemplate = SiteParams.LOCAL_TEMPLATE;
			
			topBottom = SiteParams.AMPBAR_LOCATION;
			ampBarEnabled = SiteParams.AMPBAR_ENABLED;
			loggedInOnly = SiteParams.AMPBAR_ONLY_ON_LOGIN;
			
			// reference local blank image
			Ext.BLANK_IMAGE_URL = appAMPUrl + 'js/ext/resources/images/default/s.gif';

			Ext.override(Ext.Container, {
			    removeAll: function() {
			        this.items.each(function(childItem){ this.remove(childItem);}, this);
			    }
			});

			// initialize ampBar if enabled for the site
			if (ampBarEnabled) {
				Jack.ampBar.init();
			}			
		},
		msg: function() {
			return {
				alert: function(title, format){
					function createBox(t, s){
				        return ['<div class="msg">',
				                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
				                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
				                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
				                '</div>'].join('');
				    }
				    
		            if(!msgCt){
		                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
		            }
		            msgCt.alignTo(Ext.getBody(), 'tr',[-275,1]);
		            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
		            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
		            m.slideIn('t',{duration: .8, easing: 'easeIn'}).pause(1.5).ghost("t", {easing: 'easeOut',remove:true,duration: 1.5});
				}
			}
		}(),
		JSONP: function() {
			return {
				request: function(params,callbackFunction,callbackKey) {
					if (typeof(callbackKey) == 'undefined') {
						callbackKey = 'jsonp';
					}
					Ext.ux.JSONP.request(appAMPUrl, {
		                callbackKey: callbackKey,
		                params: params,
		                callback: callbackFunction
		            });
				}
			};
		}(),
		data: function() {
			return {
				getCurrentEvents: function() {
					return new Ext.data.JsonStore({
						url: appLocalTemplate,
						baseParams: { action: 'currentEvents' },
						root: 'data',
						totalProperty: 'totalCount',
						id: 'id',
						fields: [ 
							{name: 'id', type: 'int'},
							{name: 'name', type: 'string'},
							{name: 'topic', type: 'string'},
							{name: 'description', type: 'string'},
							{name: 'date_start', type: 'date', dateFormat: 'Y-m-d H:i:s.u'},
							{name: 'date_end', type: 'date', dateFormat: 'Y-m-d H:i:s.u'},
							{name: 'time_start', type: 'string'},
							{name: 'time_end', type: 'string'},
							{name: 'registration_time', type: 'string'},
							{name: 'advertise_to_date', type: 'date', dateFormat: 'Y-m-d H:i:s.u'},
							{name: 'advertise_from_date', type: 'date', dateFormat: 'Y-m-d H:i:s.u'},
							{name: 'website_content', type: 'string'},
							{name: 'website_content_summary', type: 'string'},
							{name: 'event_capacity', type: 'int'},
							{name: 'organization_id', type: 'int'},
							{name: 'organization_name', type: 'string'},
							{name: 'address1', type: 'string'},
							{name: 'address2', type: 'string'},
							{name: 'city', type: 'string'},
							{name: 'abbrev', type: 'string'},
							{name: 'zip', type: 'string'},
							{name: 'number', type: 'string'},
							{name: 'email', type: 'string'}
						]
					});				 
				},
				getOrganizations: function() {
					return new Ext.data.JsonStore({
						url: appLocalTemplate,
						baseParams: { action: 'organizationDropdown' },
						root: 'data.data',
						totalProperty: 'data.recordcount',
						id: 'id',
						fields: [ 
							{name: 'id', type: 'int'},
							{name: 'name', type: 'string'}
						]
					});	
				},
				getEventDetail: function(event_id) {
					return new Ext.data.JsonStore({
						url: appLocalTemplate,
						baseParams: { action: 'eventDetail', id: event_id },
						root: 'data',
						id: 'id',
						fields: [
						 	{name: 'Activity'},
							{name: 'BillingType'},
							{name: 'EventBillingTypes'},
							{name: 'EventActivities'},
							{name: 'Type'},
							{name: 'custom'},
							{name: 'date_end', type: 'date', dateFormat: 'Y-m-d H:i:s.u'},
							{name: 'date_start', type: 'date', dateFormat: 'Y-m-d H:i:s.u'},
							{name: 'description', type: 'string'},
							{name: 'display_member', type: 'string'},
							{name: 'display_public', type: 'string'},
							{name: 'id', type: 'int'},
							{name: 'last_update', type: 'date', dateFormat: 'Y-m-d H:i:s.u'},
							{name: 'location', type: 'string'},
							{name: 'max_activities', type: 'int'},
							{name: 'name', type: 'string'},
							{name: 'notes', type: 'string'},
							{name: 'site_id', type: 'int'},
							{name: 'type_id', type: 'int'}
						]
					});
				},
				getMemberDirectory: function() {
					return new Ext.data.JsonStore({
						url: appLocalTemplate,
						baseParams: { action: 'memberDirectory' },
						root: 'data',
						totalProperty: 'totalCount',
						id: 'id',
						fields: [
							{name: 'first_name', type: 'string'}
						]
					});
				},
				getMemberTypes: function() {
					return new Ext.data.JsonStore({
				         url: appLocalTemplate,
					     baseParams: { action:'memberTypes' },
				         root: 'data',
				         totalProperty: 'totalCount',
				         id: 'id',
				         fields: [ 
					         {name: 'id', type: 'int'},
					         {name: 'name', type: 'string'}
				         ]
					});
					
				},
				getStates: function() {
					return new Ext.data.JsonStore({
				         url: appLocalTemplate,
					     baseParams: { action:'states' },
				         root: 'data',
				         totalProperty: 'totalCount',
				         id: 'id',
				         fields: [ 
					         {name: 'id', type: 'int'},
					         {name: 'name', type: 'string'},
					         {name: 'abbrev', type: 'string'}
				         ]
					});
				}
			};
		}(),
		contact: function() {
			function resetPassword(user_id) {
				var waitMsg = Ext.Msg.wait("Submitting password reset request...","Please Wait");
				
				Ext.Ajax.request({
					url: appLocalTemplate,
					params: { action: 'forgotPassword', id: user_id },
					success: function(result) {
						response = Ext.util.JSON.decode(result.responseText);
						if (response.success) {
							waitMsg.hide();
							
							Ext.Msg.alert('Complete!', 'Check your email, you have been sent a forgotten password request, and your password has been reset.  Please confirm your identity by logging in and changing your password.');
						} else {
							waitMsg.hide();
							Ext.Msg.alert(response.ERRORMSG, response.ERRORTEXT);
						}
						
						if (typeof(SignupWin) != "undefined") {
							SignupWin.close();
						}
					},
					failure: function() {
						waitMsg.hide();
						Ext.Msg.alert('Error!', 'Password reset not sent');
					}
		        });
			}
			
			function createContactHandler(btn,e,redirect_url,newwin,redirect_event,redirect_args) {
					e.stopEvent();
					
					if (redirect_event) {
						redirect_url = appAMPUrl + '?event=remoteLogin&redirect_event' + redirect_event;
						
						if (redirect_args) {
							redirect_url += '&redirect_args=' + redirect_args;
						}
					}
					
				//	console.log("redirect_url2: " + redirect_url);
					
					if (createForm.getForm().findField('password').getValue() !== createForm.getForm().findField('confirm_password').getValue()) {
						Jack.msg.alert("Password Does Not Match","Your confirm password does not match your password.");
					}
					else {
						createForm.getForm().submit({
							method: 'POST',
							waitTitle: 'Please Wait',
							waitMsg: 'Creating Your Account...',
							failure: function(frm, act) {
							//	console.log(act);
								if (act.result.errortext == "Duplicates found") {
									var dupePersonArray = [];
									var arrayCnt = 0;
									var msg = "";
									
									if (act.result.match_type == "email") {
										msg = "There are one or more records in the system that match your email address. Duplicate email addresses are disallowed, please select the user in this list that matches you, and choose <b>'Send Password Reminder'</b>.  If no users in this list are a match, please contact an administrator.";
									}
									else if (act.result.match_type == "exact_match") {
										msg = "There are one or more records in the system that match your first and last name. ";
									}
									else if (act.result.match_type == "last_name") {
										msg = "There are one or more records in the system that match your last name. ";
									}
									
									if (act.result.match_type !== 'email') {	
										msg = msg + "Select the record that matches your information, and choose <b>'Send Password Reminder'</b>. A password reminder email will be sent to your email address. If no matching records are found choose <b>'Create New Record'</b>.";
									}
									
									// first, get the data into a usable format
									Ext.each(act.result.data.data, function(dupe_person) {
										dupePersonArray[arrayCnt] = [
											dupe_person.id,
											dupe_person.first_name,
											dupe_person.last_name,
											dupe_person.email,
											dupe_person.city,
											dupe_person.state,
											dupe_person.province
										];
										arrayCnt++;
									});
									
									// create a store of the duplicate data
									var dupStore = new Ext.data.ArrayStore({
										fields: [
											{name: 'id', type: 'int'}, 
											{name: 'first_name', type: 'string'},
											{name: 'last_name', type: 'string'},
											{name: 'email', type: 'string'},
											{name: 'city', type: 'string'},
											{name: 'state', type: 'string'},
											{name: 'province', type: 'string'}
										],
										data: dupePersonArray
									});
									
									// open a window, passing the store as an argument
									Jack.ampBar.signup_duplicates(dupStore,act.result.match_type);
									
									setTimeout(function() { Ext.Msg.alert("Duplicates Found",msg); }, 100); 
									
								}
								else {
							 		Jack.msg.alert("Account Creation Failed", act.result.errortext);
							 		
							 		// make sure that fail_on_match is set to true
							 		createForm.getForm().findField("fail_on_match").setValue(true);
								}
							},
							success: function(frm, act) {
								var redirected = false;
								
								SignupWin.close();
							
								if (redirect_url) {
									
									// opening in a new window like this will probably require the user to unblock the site.
									if (newwin) {
										var win = window.open(redirect_url, "ampWin");
									}
									else {
										
									//	document.location.href=redirect_url;
										Jack.remoteLogin(redirect_event,redirect_args);
										redirected = true;
									}
								}
								
								// TODO: pass over a 'refresh' param to this function, to decide whether to force a refresh of the page or not
								if (!redirected) {
									window.location.reload( false );
								}
							}	
						});
					}
				}
				
			function buildCreateForm(action, title, width, bodyStyle, refresh, redirect_url, newwin,redirect_event,redirect_args) {
					var orgStore = Jack.data.getOrganizations();
					orgStore.load();
				//	console.log(store);
				
				
				//	console.log("redirect_url1: " + redirect_url);
					
					createForm = new Ext.form.FormPanel({
						title: title,
				        url: action,
				        baseParams: { action: 'createContact' },
						method: 'POST',
				        labelAlign: 'right',
						labelWidth: 112,
			            autoScroll: true,
			            width: width,
				        frame: true,
						monitorValid: true,
						shadow: true,
						bodyStyle: bodyStyle,
						items:[
							{
								xtype: 'hidden',
								name: 'fail_on_match',
								id: 'fail_on_match',
								value: true
							},
							{
								xtype: 'textfield',
								fieldLabel: 'First Name',
								name: 'first_name',
								id: 'first_name',
								allowBlank: false,
								inputType: 'text',
								anchor: false,
								blankText: 'First Name is required'
							},
							{
								xtype: 'textfield',
								fieldLabel: 'Last Name',
								name: 'last_name',
								id: 'last_name',
								allowBlank: false,
								inputType: 'text',
								anchor: false,
								blankText: 'Last Name is required'
							},
							{
								xtype: 'textfield',
								fieldLabel: 'Title',
								name: 'title',
								id: 'title',
								allowBlank: true,
								inputType: 'text',
								anchor: false
							},
							{
								xtype: 'combo',
								fieldLabel: 'Organization',
								name: 'organization_display',
								id: 'organization_id_id',
								hiddenName: 'organization_id',
								store: orgStore,
								valueField:'id',
								displayField:'name',
								typeAhead: true,
								forceSelection: true,
								mode: 'local',
								triggerAction: 'all',
								selectOnFocus: true,
								minListWidth: 200,
								width: 180,
								allowBlank: true,
								emptyText: 'Select...'
							},
							{
								xtype: 'textfield',
								fieldLabel: 'Phone',
								name: 'phone',
								id: 'phone',
								allowBlank: true,
								inputType: 'text',
								anchor: false
							},
							{
								xtype: 'textfield',
								fieldLabel: 'Email',
								name: 'email',
								id: 'signup_email',
								allowBlank: false,
								inputType: 'text',
								anchor: false,
								blankText: 'Email is required'
							},
							{
								xtype: 'textfield',
								fieldLabel: 'Username',
								name: 'username',
								id: 'username',
								allowBlank: false,
								inputType: 'text',
								anchor: false,
								blankText: 'Username is required'
							},
							{
								xtype: 'textfield',
								fieldLabel: 'Password',
								name: 'password',
								id: 'password',
								allowBlank: false,
								inputType: 'password',
								anchor: false,
								blankText: 'Password is required'
							},
							{
								xtype: 'textfield',
								fieldLabel: 'Confirm Password',
								name: 'confirm_password',
								id: 'confirm_password',
								allowBlank: false,
								inputType: 'password',
								anchor: false,
								blankText: 'Confirm Password is required'
							}
						],
						buttons: [
							{
								text: 'Create',
								formBind: true,
					      //      icon: 'http://ampx.associationsonline.com/images/silk/icons/control_play.png',
					       //     cls: 'x-btn-text-icon',
								handler: function(key,e) {
									Jack.contact.submitContact(key,e,redirect_url,newwin,redirect_event,redirect_args);
								}
							}
						],
						keys: [{
							key: 13,
							fn: function(key,e) {
								if (createForm.getForm().isValid()) {
									Jack.contact.submitContact(key,e,redirect_url,newwin,redirect_event,redirect_args);
								}
							}
						}]
					});
					
					return createForm;
			}
				
			return {
				submitContact: function(btn,e,redirect_url,newwin,redirect_event,redirect_args) {
					createContactHandler(btn,e,redirect_url,newwin,redirect_event,redirect_args);
					return;
				},
				getCreateForm: function(action, container, title, width, bodyStyle, refresh, redirect_url, newwin,redirect_event,redirect_args) {
					var formReturn = buildCreateForm(action, title, width, bodyStyle, refresh, redirect_url, newwin, redirect_event,redirect_args);
					
					formReturn.render(container);
				},
				getCreateFormNoRender: function(action, title, width, bodyStyle, refresh, redirect_url, newwin,redirect_event,redirect_args) {
					formReturn = buildCreateForm(action, title, width, bodyStyle, refresh, redirect_url, newwin,redirect_event,redirect_args);
					return formReturn;
				},
				forgotPassword: function(user_id) {
					resetPassword(user_id);
					return;
				},
				getDuplicateFormNoRender: function(action, title, width, bodyStyle,store,match_type,redirect_event,redirect_args) {
				//	console.log(store);
									
					var sm = new Ext.grid.RowSelectionModel({singleSelect:true});
					
					var dupcm = new Ext.grid.ColumnModel([
						sm,
						{header: "First Name", sortable: true, dataIndex: 'first_name'},
						{header: "Last Name", width: 100, sortable: true, dataIndex: 'last_name'},
						{header: "Email", sortable: true, dataIndex: 'email'},
						{header: "City", sortable: true, dataIndex: 'city'},
						{header: "State", sortable: true, dataIndex: 'state'},
						{header: "Province", sortable: true, dataIndex: 'province'},
						{header: "ID", hidden: true, dataIndex: 'id'}
					]);
						
					var dupGrid = new Ext.grid.GridPanel({
						id: 'dupGrid',
					    store: store,
					    cm: dupcm,
					    sm: sm,
					    stripeRows: true,
					    trackMouseOver: true,
					    autoScroll: true,
					    height: 225,
					    width: 430
					});
					
					dupGrid.on('rowclick', function(grid, rowIndex, e) {
							Ext.getCmp('reminder_button').enable();
					});
					
					var dupPanel = new Ext.Panel({
						title: title,
						id: 'dupPanel',
					//	width: 440,
						height: Ext.getCmp('signupWin').getInnerHeight() - 20,
						autoScroll: true,
						items: [dupGrid],
						buttons: [{
							id: 'reminder_button',
							text: 'Send Password Reminder',
							disabled: true,
							handler: function() {
								var row = Ext.getCmp('dupGrid').getSelectionModel().getSelected();
								Jack.contact.forgotPassword(row.data.id);
								Ext.getCmp('reminder_button').disable();
							}
						}]
					});
					
					// manually add buttons.  If the duplicates are duplicate emails, do not allow a dup to be created
					if (match_type !== "email") {
						dupPanel.addButton({
							text: 'Create New Record',
							handler: function(key,e) {
								createForm.getForm().findField("fail_on_match").setValue(false);
								SignupDupWin.close();
								Jack.contact.submitContact(key,e,redirect_event,redirect_args);
								
							}
						});
					}
					
					return dupPanel;
				}
			};
		}(),
		loginForm: function() {
			var theForm;
			var loginPanel;
			
			
			function logoutHandler(btn, e, args) {
				e.stopEvent();
				
				// TODO: add wait message 
				
				if (typeof args == 'object') {
					doRefresh = args.doRefresh;
				} else {
					doRefresh = args;
				}
				
				document.location.href = appLocalTemplate + '?action=openID&cmd=logout' + ((localUserType == 'site') ? '' : '&local_only=true');
				
				/*
				Ext.Ajax.request({
					url: appLocalTemplate,
					params: { action: 'logout', amp_logout: true },
					success: function(result) {
						if (doRefresh === true)  {
							window.location.reload( false );
						}
						else
						{
							Jack.loginForm.setFirstName('');
							Jack.loginForm.setLastName('');
							Jack.loginForm.setUserId('');
							Jack.loginForm.setEmail('');
							
							Ext.getCmp('hidden_name').setText("");
							Ext.getCmp('hidden_email').setText("");
							
							loginPanel.hide();
							theForm.show();
						}	
					},
					failure: function() {
						Ext.Msg.alert('Error!', 'You could not be logged out.  Guess you\'re stuck.');
						}
		        });
		        */
		     
			}
			
			function forgotPasswordWindowHandler(btn, e, args) {
				
				if (typeof(e) != 'undefined')
					e.stopEvent();
				
				var forgotPasswordWin = new Ext.Window({
						autoScroll: true,
						title: 'Enter Email Address', 
						width: 400,
						autoHeight: true,
						closeAction: 'close',
						modal: true,
						plain: true,
						y: 0 
					});
				
				var passwordForm = new Ext.form.FormPanel({
					method: 'POST',
			        labelAlign: 'top',
					labelWidth: 110,
					autoScroll: true,
					frame: true,
			        width: '100%',
			        autoHeight: true,
					monitorValid: true,
					shadow: false,
					border:false,
					bodyStyle: 'padding-left: 10px;',
					items: [
						{
							xtype: 'textfield',
							fieldLabel: '<span style="font-size: 18px;">Email Address</span>',
							name: 'email',
							id: 'email',
							allowBlank: false,
							value: '',
							height: 30,
							width: 350,
							style: 'font-size: 18px;',
							blankText: 'Email Address is required'
						}
						
					],
					keys: [{
						key: 13,
						fn: function(key,e) {
							if (passwordForm.getForm().isValid()) {
								processForm(key,e);
							}
						}
					}]
				});
				
				function processForm(btn,e) {
					e.stopEvent();
					
					passwordForm.getForm().submit({
						method: 'POST',
						url: appLocalTemplate,
						params: { action: 'forgotPassword'},
						waitTitle: 'Please Wait',
						waitMsg: 'Validating username...',
						failure: function(frm, act) {
					 		Ext.MessageBox.alert(act.result.errors[0].ID, act.result.errors[0].MSG);
						},
						success: function(frm, act) {
							Ext.MessageBox.alert("Email Sent","You should receive an email with your login details.");
							forgotPasswordWin.close();
						//	document.location.href = act.result.success_url;
						}	
					})
				}
						
				passwordForm.addButton({
							xtype: 'button',  
							formBind: true,
							text: 'Send Password', 
							handler: processForm
						});
						
				passwordForm.addButton({
							xtype: 'button',  
							formBind: false,
							text: 'Cancel', 
							handler: function() {forgotPasswordWin.close()}
						});
					
				forgotPasswordWin.add(passwordForm);
				forgotPasswordWin.show();
				forgotPasswordWin.center();
			}
		
			var buildLoginForm = function(action, title, width, bodyStyle, loggedIn, doRefresh, redirect_url, newwin) {
				var loginHide = false;
				var panelHide = true;
				
				if (loggedIn == true) {
					panelHide = false;
					loginHide = true;
				}
				
				if (doRefresh == 'undefined') {
					doRefresh = false;
				}
				
				function loginHandler(btn,e) {
					e.stopEvent();
					
					document.location.href = appLocalTemplate + '?action=openID&cmd=auth';
					
					
					// hax required to get the form to submit to the proper template: http://www.extjs.com/learn/Ext_FAQ_Forms#Standard_Submit
					/*
					try {
						theForm.getForm().getEl().dom.action = action;
					} catch (excpt) {
						// errors in IE, but the submit still seems to work without it
					}
					
					theForm.getForm().submit({
						method: 'POST',
						waitTitle: 'Please Wait',
						waitMsg: 'Validating Login...',
						failure: function(frm, act) {
						//	console.log(act);
					 		Ext.MessageBox.alert("Login Failed", act.result.errortext);
						},
						success: function(frm, act) {
							var redirected = false;
							
							// first name, last name, and email are all returned.  Set those to hidden fields for display
							if (redirect_url) {
								// make them change their password here before redirecting them to the site
								if (act.result.reset_password !== true) {
									// opening in a new window like this will probably require the user to unblock the site.
									if (newwin) {
										var win = window.open(redirect_url, "ampWin");
									}
									else {
										document.location.href=redirect_url;
										redirected = true;
									}
								}
							}
		
							
							if (!redirected) {
								if (act.result.reset_password == true && redirect_url) {
									ampBarPanel.hide();
									Jack.changePasswordForm.setUsername(act.result.username);
									Jack.changePasswordForm.getFormWindow(appLocalTemplate + "?action=changePassword",redirect_url,newwin);	
								}
								else if (doRefresh == true) {
									window.location.reload( false );
								}
								else {
									theForm.hide();
									loginPanel.show();
				
									Jack.loginForm.setFirstName(act.result.first_name);
									Jack.loginForm.setLastName(act.result.last_name);
									Jack.loginForm.setUserId(act.result.user_id);
									Jack.loginForm.setEmail(act.result.email);
									Jack.loginForm.setChangePassword(act.result.reset_password);
				
									Ext.getCmp('hidden_name').setText(act.result.first_name + ' ' + act.result.last_name);
									Ext.getCmp('hidden_email').setText(act.result.email);
								}
							}
						}	
					});
					*/
				}
				
				var theForm = new Ext.form.FormPanel({
					title: title,
					hidden: loginHide,
			        url: action,
					method: 'POST',
			        labelAlign: 'left',
					labelWidth: 55,
		            autoScroll: false,
			        frame: true,
			        autoHeight: true,
			        autoWidth: true,
					monitorValid: true,
					shadow: true,
					bodyStyle: bodyStyle,
					standardSubmit: true, // do not ajaxify this
					items: [{
						xtype: 'hidden',
						name: 'action',
						value: 'openid'
					},{
						xtype: 'hidden',
						name: 'cmd',
						value: 'auth'
					},
						/*{
							xtype: 'textfield',
							fieldLabel: 'Username',
							name: 'username',
							allowBlank: false,
							blankText: 'Username is required',
							anchor: '99%'
						},{
							xtype: 'textfield',
							fieldLabel: 'Password',
							name: 'password',
							allowBlank: false,
							blankText: 'Password is required',
							anchor: '99%',
							inputType: 'password'
						},*/
						{
							xtype: 'box',
							autoEl: {
								html: '<a href="javascript:{}" onclick="javascript:Jack.loginForm.forgotPassword();">Forgot Password?</a>'
							}
						}
						
					],
					keys: [{
						key: 13,
						fn: function(key,e,scope) {
							if (theForm.getForm().isValid()) {
								loginHandler(key,e);
							}
						}
					}],
					buttons: [{
							xtype: 'button', 
							formBind: true, 
							text: 'Login', 
							handler: function(key,e) {
								loginHandler(key,e);
							}
						}]
				});
				
				var loginPanel = new Ext.Panel({
					title: title,
					hidden: panelHide,
			        labelAlign: 'left',
					labelWidth: 55,
		            autoScroll: true,
			        frame: true,
			        autoHeight: true,
			        autoWidth: true,
					monitorValid: true,
					shadow: true,
					bodyStyle: bodyStyle,
					layout: 'form',
					items: [
						{
							xtype: 'box',
							autoEl: { html:'<h2>Logged In:</h2>' }
					},{
						xtype: 'label',
						id: 'hidden_name',
						text: Jack.loginForm.getFirstName() + ' ' + Jack.loginForm.getLastName(),
						width: '100%'
					},{
							xtype: 'box',
							autoEl: { html:'<br/>' }
					},{
						xtype: 'label',
						id: 'hidden_email',
						text: Jack.loginForm.getEmail(),
						width: '100%'
					},{
							xtype: 'box',
							autoEl: { html:'<a href="' + appAMPUrl + '" target="ampWin">' + ((localUserType == 'site') ? 'Open Member Center' : 'Open AMP Window') + '</a>' }
					}],
					buttons: [{
							xtype: 'button',  
							text: 'Logout', 
							handler: logoutHandler.createDelegate(this, [{ doRefresh: true }], true)
						}]
				});
				
				
				
				var formPanel = new Ext.Panel({
			        width: width,
			        autoHeight: true,
			        layout: 'fit',
			        items: [theForm, loginPanel]
			    });		
				
				return formPanel;
			};
		
			// Public functions and variables go here.
			return {
				getForm: function(action, container, title, width, bodyStyle, loggedIn, refresh, redirect_url, newwin) {
					formReturn = buildLoginForm(action, title, width, bodyStyle, loggedIn, refresh, redirect_url, newwin);
					formReturn.render(container);
				},
				getFormNoRender: function(action, title, width, bodyStyle, loggedIn, refresh, redirect_url, newwin) {
					formReturn = buildLoginForm(action, title, width, bodyStyle, loggedIn, refresh, redirect_url, newwin);
					return formReturn;
				},
				getOpenIDForm: function(container) {
					var windowed = false;
					var openIDWin;
					var openIDPanel;
					
					if (typeof(container) == 'undefined') {
						windowed = true;
					}
	
					/*
					openIDPanel = new Ext.Panel({
						frame: true,
						autoLoad: {
							url: appLocalTemplate,
							params: {
								action: 'openID'
							},
							scripts: true
						}
					});
					*/
					
					openIDPanel = new Ext.Panel({
						autoHeight: true,
						autoWidth: true,
						frame: true,
						border: false,
						items: [{
							xtype: 'iframepanel',
							loadMask: { msg: 'Loading...'},
							disableMessaging: false,
							deferredRender: true,
							defaultSrc: appLocalTemplate + '?action=openID&cmd=auth&windowed=true',
							border: true,
							buttonAlign: 'right',
							listeners  :
						         //only subscribe to 'startup' tagged messages 
						         {'message:startup' :function(srcFrame, message){
						                    alert(message.uri + ' says:\n'+ message.data);
						                    srcFrame.sendMessage('Acknowledged!', 'startup'); //to 'startup' tag subscribers
						                   },
						          domready: function(frame){
						                 if(frame.domWritable()){
						                     frame.execScript('init()');
						                  }
						               }
						          }

						}]
					});
				
					
					if (windowed) {
						openIDWin = new Ext.Window({
							layout: 'fit',
						//	bodyStyle: 'padding-left: 5px;',
							title: '',
							closeAction: 'hide',
							modal: false,
							border: false,
							plain: true,
							height: 310,
							width: 340
						});
						
						openIDWin.add(openIDPanel);
						
						openIDWin.show();
					} else {
						openIDPanel.render(container);
					}
					
				},
				getFirstName: function() {
					return localFirstName;
				},
				getLastName: function() {
					return localLastName;
				},
				getEmail: function() {
					return localEmail;
				},
				getUserId: function() {
					return localUserId;
				},
				setFirstName: function(fName) {
					localFirstName = fName;
				},
				setLastName: function(lName) {
					localLastName = lName;
				},
				setEmail: function(email) {
					localEmail = email;
				},
				setUserId: function(user_id) {
					localUserId = user_id;
				},
				getChangePassword: function() {
					return localChangePassword;
				},
				setChangePassword: function(doChange) {
					localChangePassword = doChange;
				},
				logout: logoutHandler.createDelegate(this, [{doRefresh: true}], true),
				forgotPassword: function(btn,e,args) {
					forgotPasswordWindowHandler(btn,e,args);
				}
			};			
		}(),
		changePasswordForm: function() {
			// Private functions and variables go here.
			var localUsername = '';
			var localPassword = '';
			
			var buildPasswordForm = function(action,redirect_url,newwin) {				
			    var fp = new Ext.FormPanel({
			        id: 'pwchange_form',
			        method: 'POST',
			        url: action,
			        labelAlign: 'right',
					labelWidth: 110,
			        width: 360,
		    		height: 170,
			        buttonAlign: 'center',
			        border: false,
			        frame:true,
			        monitorValid: true,
			        bodyStyle: 'padding:10px 10px 0;',
			        defaults: {
			            anchor: '95%',
			            allowBlank: false,
			            selectOnFocus: true,
			            msgTarget: 'side',
			            height: 30
			        },
			        items:[{
			        	xtype: 'textfield',
			            fieldLabel: 'Username',
						name: 'username',
						id: 'login_username',
						blankText: 'Username is required',
						value: localUsername,
						style: 'font-size: 18px;',
						disabled: true
			        },{
						xtype: 'textfield',
						fieldLabel: 'New Password',
						name: 'new_password',
						id: 'new_password',
						inputType: 'password',
						style: 'font-size: 18px;',
						blankText: 'Password is Required',
						validator: function(value) {
							return formValidator('password',value);
						}
					},{
						xtype: 'textfield',
						fieldLabel: 'Confirm Password',
						name: 'confirm_password',
						id: 'confirm_password',
						inputType: 'password',
						style: 'font-size: 18px;',
						blankText: 'Confirm Password is Required',
						validator: function(value) {
							return formValidator('confirm_password',value);
						}
					}],
					keys: [{
						key: 13,
						fn: function(key,e) {
							if (fp.getForm().isValid()) {
								formHandler(key,e);
							}
						}
					}],
					buttons: [{
							text: 'Change',
							monitorValid: true,
							handler: formHandler
						}
					]
			    });
			    
			    var formPanel = new Ext.Panel({
			        width: 380,
			        autoHeight: true,
			        border: false,
			        layout: 'fit',
			        items: fp
			       /* ,
			        bbar: new Ext.ux.StatusBar({
			            id: 'form-statusbar',
			            defaultText: '',
			            plugins: new Ext.ux.ValidationStatus({form:'pwchange_form',showText:'Invalid Entries (click for details)'})
			        }) */
			    });			
				
			    function formValidator(field,value) {
			    	var passwordVal = Ext.getCmp('new_password').getValue();
					var success = true;
					var msg = "";
					var fieldLabel = "";
					
					if (field == 'password') {
						fieldLabel = "Password";
						
						/*
						if (value.length > 0 && value.length < 6) {
							success = false;
							msg = 'Password must be at least 6 characters, including one number.';
						}
						
						re = /[0-9]/; 
						if(success == true && !re.test(value)) { 
							success = false;
							msg = 'Password must contain at least 1 number';
						} 
						*/
					}
					else if (field == "confirm_password") {
						fieldLabel = "Confirm Password";
						
						if (passwordVal !== value) {
							success = false;
							msg = 'Confirm password does not match password.';
						}
					}
					
					if (success == true)
						return true;
					else
						return msg;
			    }
		
			    function formHandler(btn,e) {
					e.stopEvent();
					
					if (fp.getForm().isValid()) {
					//	var sb = Ext.getCmp('form-statusbar');
	                //    sb.showBusy('Updating Password...');
	                    fp.getEl().mask();
	                    fp.getForm().submit({
	                    	method: 'POST',
	                        success: function(frm,act){
	                        	var redirected = false;
								
								if (redirect_url) {
									// opening in a new window like this will probably require the user to unblock the site.
									if (newwin) {
										var win = window.open(redirect_url, "ampWin");
									}
									else {
										document.location.href=redirect_url;
										redirected = true;
									}
								}
			
								
								if (!redirected) {
								/*	sb.setStatus({
		                                text:'Changed Password.', 
		                                iconCls:'',
		                                clear: true
		                            }); */
		                            fp.getEl().unmask();
		                            window.location.reload( false );
								}
								
	                         //   document.location.href = act.result.success_url;
	                        },
	                        failure: function(frm, act) {
						 		Ext.Msg.alert(act.result.errors[0].ID, act.result.errors[0].MSG);
							}
	                    });
					}
				}
				
				return formPanel;
			};
			       
			// Public functions and variables go here.
			return {
				getFormNoRender: function(action,redirect_url,newwin) {
					var formReturn = buildPasswordForm(action,redirect_url,newwin);
					return formReturn;
				},
				getFormWindow: function(action,redirect_url,newwin) {
					var formReturn = buildPasswordForm(action,redirect_url,newwin);
					
					changePasswordWin = new Ext.Window({
						title: 'Password Change Form',
						autoScroll: true,
						width: 395,
						autoHeight: true,
						autoScroll: false,
						closable: false,
						closeAction: 'close',
						modal: true,
						plain: true,
						y: 0
					});
		
					changePasswordWin.add(formReturn);
					changePasswordWin.show();
					changePasswordWin.center();
					
					// set initial focus
					 // Focus won't set without a delay on this form, so 10ms should do it
			    	(function() { 
			    		Ext.getCmp('new_password').focus(true);
			    	}).defer(10);
				},
				getUsername: function() {
					return username;
				},
				setUsername: function(username) {
					localUsername = username;
				},
				getPassword: function() {
					return password;
				},
				setPassword: function(password) {
					localPassword = password;
				}
			};
		}(),
		ampBar: function() {
			return {
				init: function() {
				//	bodyReal = Ext.getBody();
				//	ampBarContainer = Ext.get('ampBarContainer');
					
				//	console.log(body2);
					
					ampBarTBar = new Ext.Toolbar({
						id: 'ampBarTBar'
					});
					
					ampBarPanel = new Ext.Panel({
						id: 'ampBarPanel',
						cls: 'ampBar',
						floating: true,
						width: '100%',
						shadow: false,
						tbar: ampBarTBar
					});
		
					var eventsMenu = new Ext.menu.Menu({
						id: 'eventsMenu',
						items: [{
							text: 'View Current Events', 
							icon: appAMPUrl + 'images/silk/icons/calendar.png',
							cls: 'x-btn-text-icon',
							handler: Jack.events.getCurrentEvents
						},{
							text: 'Register for an Event', 
							icon: appAMPUrl + 'images/silk/icons/calendar_link.png',
							cls: 'x-btn-text-icon'
						},{
							text: 'My Event Registrations', 
							icon: appAMPUrl + 'images/silk/icons/calendar_edit.png',
							cls: 'x-btn-text-icon'
						}]
				    });
		
					var profileMenu = new Ext.menu.Menu({
						id: 'profileMenu',
						items: [{
							text: 'Edit Profile', 
							icon: appAMPUrl + 'images/silk/icons/user_edit.png',
							cls: 'x-btn-text-icon',
							handler: Jack.profile.myProfile
						}]
				    });
		
					ampBarPanel.on('render', function(tb) {
						viewSize = Ext.getBody().getViewSize();
						
						if (localUserId !== '' && localUserId > 0) {
							ampBarPanel.show();
							
							ampBarTBar.add({
								xtype: 'box',
								style: 'margin-right: 10px;',
								autoEl: { html: '<img src="' + appAMPUrl + 'images/amplogo_small_bar.gif" onclick="window.open(\'http://www.associationsonline.com\');" style="cursor: hand; cursor: pointer;" />' },
								pageX: 0
							},{
								xtype: 'box',
								style: 'font-weight: bold; float: left; position: relative; margin-right: ' + (viewSize.width - 500) + 'px;',
								autoEl: { html: 'Welcome back ' + localFirstName + '!' }
							},new Ext.SplitButton({
								text: 'Events',
								icon: appAMPUrl + 'images/silk/icons/calendar.png',
								cls: 'x-btn-text-icon',
								handler: Jack.events.getCurrentEvents,
								menu: eventsMenu
							})
							/*,{
								text: 'Profile',
								icon: appAMPUrl + 'images/silk/icons/user.png',
								cls: 'x-btn-text-icon',
								handler: Jack.profile.myProfile
							},{
								text: 'Member Directory',
					            icon: appAMPUrl + 'images/silk/icons/group.png',
					            cls: 'x-btn-text-icon' //,
								//handler: Jack.member.getDirectory
							}*/,{
								text: 'Logout',
					            icon: appAMPUrl + 'images/silk/icons/lightning_delete.png',
					            cls: 'x-btn-text-icon',
								handler: Jack.loginForm.logout
							});
						} else {
							if (loggedInOnly) {
								ampBarPanel.hide();
							}
							
							ampBarTBar.add({
								xtype: 'box',
								style: 'font-weight: bold; margin-right: ' + (viewSize.width - 138) + 'px;',
								autoEl: { html: '&nbsp;' }
							},{
								text: 'Login',
					            icon: appAMPUrl + 'images/silk/icons/lightning_go.png',
					            cls: 'x-btn-text-icon',
								handler: Jack.ampBar.login
							},{
								xtype: 'button',
								text: 'Signup',
					            icon: 'http://ampx.associationsonline.com/images/silk/icons/lightning_go.png',
					            cls: 'x-btn-text-icon',
								handler: Jack.ampBar.signup
							});					
						}
					});
					
					ampBarPanel.render('ampBarContainer');
			//		bodyReal.setStyle("overflow-y: scroll;position: relative;");
					
					ampBarPanelEl = Ext.get('ampBarPanel');
					
					if (topBottom == 'top') {
						// there's nothing wrong with setPosition(0,0), but 'alignTo' is consistent with the alignTo used below.
						ampBarPanelEl.alignTo(Ext.getBody(),'tl',[0,0]);
					} else {					
						// This combination of factors is what it takes, along with the injected ampBar stylesheet, to position the AMP Bar at the bottom of the page
						
						// anchoring messes up Safari and Google Chrome.  Since both browsers report (currently) as isSafari, this fix works for both.				
						if (!Ext.isSafari) {
							ampBarPanelEl.anchorTo(Ext.getBody(),'bl',[0,-27],true,true);
						}
						ampBarPanelEl.alignTo(Ext.getBody(),'bl',[0,-27]);
//					//	ampBarPanel.setPosition(0, topY);
						
					/*	var scrollEl = Ext.get(document.documentElement || document.body);
						
						scrollEl.on('scroll', function() {
						
					//	Ext.getDoc().on('scroll', function() {							
							var el = Ext.get('ampBarPanel');
							
							viewSize = Ext.getBody().getViewSize();				
							topY = viewSize.height - 27 + document.documentElement.scrollTop;
							
						//	ampBarPanel.setPosition(0, topY);
							
							el.shift({
							    x: 0,
							    y: topY,
							    easing: 'easeOut',
							    duration: .35
							});
							
						});*/
					}
				},
				login: function(key,e,redirect_url,newwin) {
					LoginWin = new Ext.Window({
						autoScroll: true,
						title: 'Member Login', 
						width:268,
						autoHeight: true,
						closeAction: 'close',
						modal: true,
						plain: true,
						y: 0
					});
		
					LoginFormReturn = Jack.loginForm.getFormNoRender(appLocalTemplate, '', 250, 'padding-left: 2px;', false, true, redirect_url, newwin);
		
					LoginWin.add(LoginFormReturn);
					LoginWin.show();
					LoginWin.center();
				},
				// forceLogin prompts the user to signup or login, and passes over the redirect_url.  newwin is true/false and indicates whether a new window should be opened upon login to the new location
				forceLogin: function(redirect_url,newwin,redirect_event,redirect_args) {
					
					var processResult = function(btn,txt,redirect_event,redirect_args) {
						var args = {};
						var urlParameters = window.location.search.substring(1);
						
						// ok = login
						if (btn == 'ok') {
							args.amp_login = true;
							
							if (Ext.isIE) {
								ch = '&amp;';
							} else {
								ch = '&';
							}
							
							document.location.href = window.location.search.substring(0) + ((urlParameters.length > 0) ? (urlParameters + ch) : '?') + Ext.urlEncode(args) + ch + 'redirect_url=' + redirect_url;
						//	Jack.ampBar.login(btn,'',redirect_url,newwin);
						}
						// yes = signup
						else if (btn == 'yes') {
							Jack.ampBar.signup(btn,'',redirect_url,newwin,redirect_event,redirect_args);
						}
					}
					
					Ext.Msg.show({
					   title:'Login Required',
					   msg: 'In order to proceed, you must either sign in to your existing account, or create a new one.  Please indicate your preference below.',
					   buttons: {ok:'Login', yes: 'Sign Up', cancel:'Cancel'},
					   fn: function(btn, txt){
					   		processResult(btn,txt,redirect_event,redirect_args);
					   },
					   icon: Ext.MessageBox.QUESTION
					});
				},
				signup: function(key,e,redirect_url,newwin,redirect_event,redirect_args) {
					SignupWin = new Ext.Window({
						autoScroll: true,
						id: 'signupWin',
						title: 'Signup - Create Account', 
						width: 350,
						autoHeight: true,
						closeAction: 'close',
						modal: true,
						plain: true,
						y: 0,
						x: 10
					});
					
					// when this window closes, close the duplicates window as well
					SignupWin.on('close',function() {
						if (typeof(SignupDupWin) != "undefined") {
							SignupDupWin.close();
						}
					});
		
					SignupWinReturn = Jack.contact.getCreateFormNoRender(appLocalTemplate, '', 330, 'padding-left: 5px;', false, redirect_url, newwin, redirect_event, redirect_args);
		
					SignupWin.add(SignupWinReturn);
					SignupWin.show();
					SignupWin.center();
					SignupWin.setPosition(10);
				},
				signup_duplicates: function(store,match_type,redirect_event,redirect_args) {
					if (typeof(SignupDupWin) != "undefined") {
						SignupDupWin.close();
					}
						
					SignupDupWin = new Ext.Window({
						autoScroll: true,
						title: 'Is This You?', 
						width: 450,
						height: Ext.getCmp('signupWin').getInnerHeight() + Ext.getCmp('signupWin').getFrameHeight() - 1,
						closeAction: 'close',
						modal: true,
						plain: true,
						y: 0
					});
				
					SignupDupWinReturn = Jack.contact.getDuplicateFormNoRender(appLocalTemplate, '', 400, 'padding-left: 5px;', store, match_type,redirect_event,redirect_args);
		
					SignupDupWin.add(SignupDupWinReturn);
					SignupDupWin.show();
					SignupDupWin.anchorTo('signupWin','tr');
				}
			};		
		}(),
		profile: function() {
			return {
				myProfile: function() {
					var localStates = Jack.data.getStates();

					localStates.setDefaultSort('name', 'ASC');
					localStates.on('load', function() {
						Ext.getCmp('profile_form').getForm().findField('profile_state_id').setValue(localStateId);
					});

					if (typeof(ProfileWin) != "undefined") {
						ProfileWin.close();
					}

					ProfileWin = new Ext.Window({
						autoScroll: true,
						title: 'Profile: ' + localFirstName + ' ' + localLastName, 
						height: 450,
						width: 405,
						closeAction: 'close',
						modal: true,
						plain: true,
						y: 0
					});
					
					ProfileForm = new Ext.FormPanel({
						id: 'profile_form',
				        url:'amp_ext.cfm?action=registerEvent',
						method: 'POST',
						layout: 'form',
				        labelAlign: 'right',
			            autoScroll: true,
				        frame: true,
				        width: 388,
				        height: 400,
						monitorValid: true,
						items: [{
							xtype: 'textfield',
							fieldLabel: 'First Name',
							name: 'profile_first_name',
							id: 'profile_first_name',
							allowBlank: false,
							value: localFirstName,
							anchor: '98%',
							blankText: 'First Name is required'
						},{
							xtype: 'textfield',
							fieldLabel: 'Last Name',
							name: 'profile_last_name',
							id: 'profile_last_name',
							allowBlank: false,
							value: localLastName,
							anchor: '98%',
							blankText: 'Last Name is required'
						},{
							xtype: 'textfield',
							fieldLabel: 'Email',
							name: 'profile_email',
							id: 'profile_email',
							allowBlank: false,
							value: localEmail,
							anchor: '98%',
							blankText: 'Email is required'
						},{
							xtype: 'textfield',
							fieldLabel: 'Phone',
							name: 'profile_phone',
							id: 'profile_phone',
							allowBlank: true,
							value: localPhone,
							anchor: '98%',
							blankText: 'Phone is required'
						},{
							xtype: 'textfield',
							fieldLabel: 'Address 1',
							id: 'profile_address_1',
							name: 'profile_address_1',
							allowBlank: false,
							value: localAddress1,
							anchor: '98%',
							blankText: 'Address 1 is required'
						},{
							xtype: 'textfield',
							fieldLabel: 'Address 2',
							id: 'profile_address_2',
							name: 'profile_address_2',
							allowBlank: true,
							value: localAddress2,
							anchor: '98%',
							blankText: 'Address 2 is required'
						},{
							xtype: 'textfield',
							fieldLabel: 'City',
							id: 'profile_city',
							name: 'profile_city',
							allowBlank: false,
							value: localCity,
							anchor: '98%',
							blankText: 'City is required'
						},{
							xtype: 'panel',
							layout: 'column',
							defaults: {
								xtype: 'panel',
								layout: 'form'
							},
							items: [{
								width: '60%',
								labelWidth: smallLabelWidth,
								items: [
									//AMP.Form.buildComboBox('State', 'event_registration_state_display', 'event_registration_state_id', false, true, true, mediumFieldWidth, mediumFieldWidth, localState, localStates, 'local', '98%')
									{
										xtype: 'combo',
										fieldLabel: 'State',
										name: 'profile_state_display',
										id: 'profile_state_component_id',
										hiddenName: 'profile_state_id',
										store: localStates,
										valueField:'id',
										displayField:'abbrev',
										typeAhead: true,
										forceSelection: true,
										mode: 'local',
										triggerAction: 'all',
										selectOnFocus: true,
										minListWidth: mediumFieldWidth,
										allowBlank: false,
										value: localStateId,
										anchor: '98%',
										blankText: 'State is required',
										emptyText: 'Select...'
									}
								]	
							},{
								width: 145,
								labelWidth: 40,
								items: [
									// AMP.Form.buildTextField('Zip', 'event_registration_zip', 'event_registration_zip', false, localZip, mediumFieldWidth, '', '98%')
									{
										xtype: 'textfield',
										fieldLabel: 'Zip',
										name: 'profile_zip',
										id: 'profile_zip',
										allowBlank: false,
										value: localZip,
										anchor: '98%',
										blankText: 'Zip is required'
									}
								]
							},{
								xtype: 'panel',
								title: 'Preferences',
								width: '100%',
								layout: 'column',
								items: [{
									xtype: 'panel',
									layout: 'form',
									title: 'Contact',
									columnWidth: 0.5,
									items: [{
										xtype: 'checkbox',
										height: 25,
										hideLabel: true,
										boxLabel: 'Receive Emails from AMP',
										id: 'preference_receive_email',
										name: 'preference_receive_email',
										inputValue: 1,
										checked: true
									},{
										xtype: 'checkbox',
										height: 25,
										hideLabel: true,
										boxLabel: 'Receive Faxes from AMP',
										id: 'preference_receive_fax',
										name: 'preference_receive_fax',
										inputValue: 1,
										checked: true
									},{
										xtype: 'checkbox',
										height: 25,
										hideLabel: true,
										boxLabel: 'Receive Mail from AMP',
										id: 'preference_receive_mail',
										name: 'preference_receive_mail',
										inputValue: 1,
										checked: true
									}] 
								},{
									xtype: 'panel',
									title: 'Misc.',
									layout: 'form',
									columnWidth: 0.5,
									items: [{
										xtype: 'checkbox',
										height: 25,
										hideLabel: true,
										boxLabel: 'Do Not Sell',
										id: 'preference_do_not_sell',
										name: 'preference_do_not_sell',
										inputValue: 1,
										checked: true
									},{
										xtype: 'checkbox',
										height: 25,
										hideLabel: true,
										boxLabel: 'Show in Directory',
										id: 'preference_show_in_public_directory',
										name: 'preference_show_in_public_directory',
										inputValue: 1,
										checked: false
									},{
										xtype: 'checkbox',
										height: 25,
										hideLabel: true,
										boxLabel: 'Show in Member Directory',
										id: 'preference_show_in_member_directory',
										name: 'preference_show_in_memver_directory',
										inputValue: 1,
										checked: true
									}]
								}]
							}]
						}],
						buttons: [{
							text: 'Submit',
							monitorValid: true,
							handler: function() {}
						},{
							text: 'Close',
							monitorValid: false,
							handler: function() { ProfileWin.close(); }
						}]
					});
					
					ProfileForm.on('render', function() {
						localStates.load();
					});
					
					ProfileWin.add(ProfileForm);
					
					ProfileWin.show();
				}
			};
		}(),
		member: function() {
			return {
				getDirectory: function() {
					var theStore = Jack.data.getMemberDirectory();

					if (typeof(DirectoryWin) != "undefined") {
						DirectoryWin.close();
					}

					DirectoryWin = new Ext.Window({
						autoScroll: true,
						title: 'Member Directory', 
						height: 550,
						width: 750,
						closeAction: 'close',
						modal: true,
						plain: true,
						y: 0
					});
					
					var buildMemberSearchForm = function(){
						localTypes = Jack.data.getMemberTypes();	 
						localTypes.setDefaultSort('name', 'ASC');
						localTypes.load();
				
						function loadMemberGrid() {
							theStore.reload({
								params:{
									action: 'memberDirectory',
									first_name: Ext.get('search_member_first_name').getValue(),
									last_name: Ext.get('search_member_last_name').getValue(),
									email: Ext.get('search_member_email').getValue(),
									phone: Ext.get('search_member_phone').getValue(),
									start: 0,
									limit: 18
								}
							});
						}
						
						return new Ext.Panel({
							title: 'Search',
							id: 'member_search_form',
							region: 'west',
							split: true,
							width: 275,
							autoHeight: true,
							collapsible: true,
							collapsed: false,
							items: [{
								xtype: 'form',
								labelAlign: 'left',
								labelWidth: smallLabelWidth,
								border: false,
								bodyStyle: 'padding-left: 5px;',
								items: [{
									xtype: 'textfield',
									fieldLabel: 'First Name',
									name: 'first_name',
									id: 'search_member_first_name',
									width: largeFieldWidth
								},{
									xtype: 'textfield',
									fieldLabel: 'Last Name',
									name: 'last_name',
									id: 'search_member_last_name',
									width: largeFieldWidth
								},{
									xtype: 'textfield',
									fieldLabel: 'Email',
									name: 'email',
									id: 'search_member_email',
									width: largeFieldWidth
								},{
									xtype: 'textfield',
									fieldLabel: 'Phone',
									name: 'phone',
									id: 'search_member_phone',
									width: largeFieldWidth
								}],
								buttons: [{
									text: 'Search',
									handler: loadMemberGrid
								}],
								keys: [{
									key: 13,
									fn: function(key,e) {
										loadMemberGrid();
									}
								}]
							}]
						});
					};
					
					var buildMemberResultsGrid = function() {
						// This got turned into a function to share search functionality with 'email all' and enable code re-use
						function getSearchBaseParams(nolimit) {
							if (nolimit == 'undefined')
								nolimit = false;
								
							return {
								json: 'true',
								action: 'memberDirectory',
								first_name: (Ext.get('search_member_first_name')) ? Ext.get('search_member_first_name').getValue() : '',
								last_name: (Ext.get('search_member_last_name')) ? Ext.get('search_member_last_name').getValue() : '',
								email: (Ext.get('search_member_email')) ? Ext.get('search_member_email').getValue() : '',
								phone: (Ext.get('search_member_phone')) ? Ext.get('search_member_phone').getValue() : ''
							};
							
						}
						 
						theStore.on('beforeload', function() {
							theStore.baseParams = getSearchBaseParams();
						});
						theStore.load();
						
						anchorStore = new Ext.data.ArrayStore({
							fields: [
								{name: 'id', type: 'int'},
						        {name: 'first_name', type: 'string'},
						        {name: 'last_name', type: 'string'},
								{name: 'member_status_id', type: 'string'},
								{name: 'member_type_id', type: 'string'},
								{name: 'comments', type: 'string' },
								{name: 'roles', type: 'string'},
								{name: 'primary_email', type: 'string'},
								{name: 'primary_phone', type: 'string'},
								{name: 'primary_address', type: 'string'},
								{name: 'primary_email_id', type: 'int'},
								{name: 'primary_phone_id', type: 'int'},
								{name: 'primary_address_id', type: 'int'},
								{name: 'categories'},
						        {name: 'active', type: 'string'}
							]
						});
						
						// create selection model
						sm = new Ext.grid.CheckboxSelectionModel({
							singleSelect: false,
							header: ''
						});
						
						// create column model with checkbox				
						var member_colModel = new Ext.grid.ColumnModel([
							sm,
							{
								header: "",
								width: 25,
								sortable: false,
								dataIndex: 'id',
								renderer: function(value) {
									isAnchor = anchorStore.find('id', value);
									
									if (isAnchor == -1) {
										return '<div align="center"><img src="images/silk/icons/anchor_off.png" style="cursor: pointer;" /></div>';
									} else {
										return '<div align="center"><img src="images/silk/icons/anchor_on.png" style="cursor: pointer;" /></div>';
									}
								} 
							},
							{
								header: "First Name",
								width: 75,
								sortable: true,
								dataIndex: 'first_name'
							},{
								header: "Last Name", 
								width: 75,
								sortable: true, 
								dataIndex: 'last_name'
							},{
								header: "Type",
								width: 100,
								sortable: true,
								dataIndex: 'member_type_id',
								renderer: function(value) {
									var typeIndex = localTypes.find('id', value);
									
									if (typeIndex >= 0) {
										return localTypes.getAt(typeIndex).get('name');
									} else {
										return 'Select...';
									}
								}
							},{
								header: "Labels",
								id: 'labels', 
								width: 175, 
								sortable: false, 
								editable: false,
								dataIndex: 'categories',
								renderer: function(value) {
									returnVal = '';
						
				  					Ext.each(value, function(i) {
				  						if (i.color !== '') {
											txtColor = parseInt(i.color.substr(1),16);
											
											if(txtColor < 4194303 || txtColor > 12582909) {
												txtColor = '#000000';
											} else {
												txtColor = "#EEEEEE";
											}
					  		
											returnVal = returnVal + '<div style="float: left; border: 1px solid black; margin: 1px; padding: 1.5px; color: ' + txtColor + '; background-color: ' + i.color + ';" title="' + i.name + '">' + i.name + '</div>';
				  						}
									});
									return returnVal;
								}
							},{
								header: "Primary Email", 
								width: 130, 
								sortable: true, 
								dataIndex: 'primary_email'
							},{
								header: "Primary Address",
								hidden: true,
								width: 225,
								sortable: true,
								dataIndex: 'primary_address'
							},{
								header: "Primary Phone",
								width: 100,
								sortable: true,
								dataIndex: 'primary_phone'
							}
						]);
								
						// create the Grid
						var memberGrid = new Ext.grid.EditorGridPanel({
							id: 'memberGrid',
							region: 'center',
						    store: theStore,
						    cm: member_colModel,
						    sm: sm,
						    stripeRows: true,
						    trackMouseOver: true,
						    autoExpandColumn: 'labels',
							clicksToEdit: 1,
						    bbar: new Ext.PagingToolbar({
						        pageSize: 18,
						        store: theStore,
						        autoWidth: true
						    })
						});
				
						function displayAnchor(theStore) {
							var memberSort = memberGrid.getStore().getSortState();
							var anchorCnt = 0;
							
							anchorStore.sort(memberSort.field, memberSort.direction);
				
							anchorStore.each(function(item) {
								memberIndex = theStore.find('id', item.data.id);
								
								if (memberIndex > -1) {
									memberRecord = theStore.getAt(memberIndex);
									theStore.remove(memberRecord);
								}
				
								theStore.insert(anchorCnt, item);
				
								anchorCnt++;
							});
						}
						
						memberGrid.on('cellclick', function(grid, rowIndex, columnIndex, e) {
							var record = grid.getStore().getAt(rowIndex);  // Get the Record
							var fieldName = grid.getColumnModel().getDataIndex(columnIndex); // Get field name
							var data = record.get(fieldName);
							
							if (columnIndex == 1) {
								isAnchor = anchorStore.find('id', data);
				
								if (isAnchor > -1) {
									anchorRecord = anchorStore.getAt(isAnchor);
									
									anchorStore.remove(anchorRecord);
				
									displayAnchor(memberGrid.getStore());
									
									memberGrid.getStore().fireEvent('datachanged');
								} else {
									memberIndex = memberGrid.getStore().find('id', data);
									memberRecord = memberGrid.getStore().getAt(memberIndex);
									anchorRecord = memberRecord.copy();
									
									anchorStore.add(anchorRecord);
				
									displayAnchor(memberGrid.getStore());
				
									memberGrid.getStore().fireEvent('datachanged');
								}
							}
						});
						
						memberGrid.getStore().on('load', function(theStore, records, options) {
							displayAnchor(theStore);
						});
						
						return memberGrid;
					};
					
					DirectoryPanel = new Ext.Panel({
						layout: 'border',
						items: [
							buildMemberSearchForm(),
							buildMemberResultsGrid()
						]
					});

					DirectoryWin.add(DirectoryPanel);
					DirectoryWin.show();
				}
			};
		}(),
		events: function() {
			return {
				getCurrentEvents: function() {
					var theStore = Jack.data.getCurrentEvents();

					if (typeof(EventWin) != "undefined") {
						EventWin.close();
					}

					EventWin = new Ext.Window({
						autoScroll: true,
						title: 'Current Events', 
						height: 550,
						width: 750,
						closeAction: 'close',
						modal: true,
						plain: true,
						y: 0
					});

					function eventDetail(value, p, record) {
						return String.format(
							'<div>' +
							'	<div style="font-weight: bold; font-size:  16px; padding-bottom: 5px;">{0} - <span style="font-size: 14px;">{7}</span></div>' +
							'	<div style="font-size: 12px; margin-left: 10px; padding-bottom: 5px;"><span style="font-weight: bold;">{7}</span> - {8}, ' + ((record.data.address2 !== '') ? '{9}, ' : '') + '{10}, {11} {12} (<a onclick="Jack.events.mapIt(\'{8}, {10}, {11} {12}\');" style="cursor: pointer;">map</a>)</div>' +
							'	<div style="font-weight: bold; font-size: 12px; margin-left: 10px; padding-bottom: 10px;">{2} {4} - {3} {5} (on-site registration time: {6})</div>' +
							'	<div style="font-size: 12px;">{13}</div>' +
							'</div>', 
							value, record.data.topic, Ext.util.Format.date(record.data.date_start), Ext.util.Format.date(record.data.date_end), record.data.time_start, record.data.time_end, record.data.registration_time, record.data.organization_name, record.data.address1, record.data.address2, record.data.city, record.data.abbrev, record.data.zip, record.data.website_content_summary);
					}

					RegExp.escape = function(text) {
					  if (!arguments.callee.sRE) {
					    var specials = [
					      '/', '.', '*', '+', '?', '|',
					      '(', ')', '[', ']', '{', '}', '\\',
					      '"'
					    ];
					    arguments.callee.sRE = new RegExp(
					      '(\\' + specials.join('|\\') + ')', 'g'
					    );
					  }
					  return text.replace(arguments.callee.sRE, '\\$1');
					};

					function eventTools(value, p, record) {
						var locationName = record.data.organization_name;
						locationName = RegExp.escape(locationName);
						//locationName = locationName.replace(/([\[\\\^\$\.\|\?\*\+\(\)\"])/gm, function(i) {return "\\" + i});
						
						var websiteContent = record.data.website_content;
						websiteContent = RegExp.escape(websiteContent);
						//websiteContent = websiteContent.replace(/([\[\\\^\$\.\|\?\*\+\(\)\"])/gm, function(i) {return "\\" + i});
						
						return String.format(
							'<div>' +
						//	'	<div><a onclick="Jack.events.registerEvent({0}, {6}, \'{7}\', true);" style="cursor: pointer;">Register Now</a></div>' +
							'	<div><a onclick="Jack.events.registerEvent({0}, true);" style="cursor: pointer;">Register Now</a></div>' +
							'	<div><a onclick="Jack.events.viewDetail({6}, true)" style="cursor: pointer;">More Info</a></div>' +
							'	<div><a onclick="Jack.events.mapIt(\'{1}, {2}, {3} {4}\', \'{8}\', false);" style="cursor: pointer;">Map Location</div>' +
							'</div>',
							value, record.data.address1, record.data.city, record.data.abbrev, record.data.zip, websiteContent, localMemberId, record.data.name, locationName);
					}

					// create column model with checkbox				
					var cm = new Ext.grid.ColumnModel([
						{id: 'name', header: "Event", width: 450, sortable: true, dataIndex: 'name', renderer: eventDetail},
						{width: 100, sortable: false, dataIndex: 'id', renderer: eventTools}
					]);
					
					// create the Grid
					var eventsGrid = new Ext.grid.GridPanel({
						id: 'eventsGrid',
					    store: theStore,
					    cm: cm,
					    stripeRows: true,
					    trackMouseOver: true,
					    autoExpandColumn: 'name',
					    height: 485,
					    width: '100%'
					});
					
					eventsGrid.on('render', function(){
						theStore.load();
					});
					
					eventsPanel = new Ext.TabPanel({
						id: 'eventsPanel',
						header: true,
						height: 500,
						autoWidth: true,
						border: true,
			            activeTab: 0,
						deferredRender: false,
						layoutOnTabChange: true,
						enableTabScroll: true,
						defaults: {
							xtype: 'panel',
							autoScroll: true
						},
						items: [{
							title: 'Events',
							items: [
								eventsGrid
							] 
						}]
					});
		
					EventWin.add(eventsPanel);
					EventWin.show();
				},
				registerEvent: function(event_id,newwindow) {
					// do an asynchronous call to get the register link for this event
					Ext.Ajax.request({
						url: appLocalTemplate,
						params: { action: 'getRegisterLink', event_id: event_id, newwindow: newwindow },
						success: function(result) {
							response = Ext.util.JSON.decode(result.responseText);
							if (response.success) {
								if (newwindow) {
									var win = window.open(response.link, "ampWin");
								}
								else {
									document.location.href = response.link;
								}
							} else {
								Jack.msg.alert('Error!', response.errorText);
							}
						},
						failure: function() {
							Jack.msg.alert('Error!', 'Unable to register for this event at this time.  Please try again later.');
						}
					});
				},
				registerEvent_old: function(event_id, member_id, event_name, new_tab) {
					var theStore = Jack.data.getEventDetail(event_id);

					theStore.on('load', function() {
						eventRecord = theStore.getAt(0);
						
						localEventActivities = eventRecord.get('EventActivities');
						localEventBillingTypes = eventRecord.get('EventBillingTypes');
						localEventType = eventRecord.get('Type');
						localEventCustom = eventRecord.get('custom');
						localEventDateEnd = eventRecord.get('date_end');
						localEventDateStart = eventRecord.get('date_start');
						localEventDescription = eventRecord.get('description');
						localEventDisplayMember = eventRecord.get('display_member');
						localEventDisplayPublic = eventRecord.get('display_public');
						localEventId = eventRecord.get('id');
						localEventLastUpdate = eventRecord.get('last_updated');
						localEventLocation = eventRecord.get('location');
						localEventMaxActivities = eventRecord.get('max_activities');
						localEventName = eventRecord.get('name');
						localEventNotes = eventRecord.get('notes');
						localEventSiteid = eventRecord.get('site_id');
						localEventTypeId = eventRecord.get('type_id');
						
						if (typeof new_tab != 'undefined' && ! new_tab) {
							if (typeof(RegistrationWin) != "undefined") {
								RegistrationWin.close();
							}
		
							var RegistrationWin = new Ext.Window({
								autoScroll: true,
								title: 'Registration For: ' + event_name, 
								height: 500,
								width: 500,
								closeAction: 'close',
								modal: true,
								plain: true,
								y: 0
							});
							
							RegistrationWin.add(buildEventRegistrationForm());

							RegistrationWin.show();
						} else {
							var RegistrationTab = new Ext.Panel({
								title: 'Registration For: ' + event_name,
								closable: true,
								height: 485
							});

							RegistrationTab.add(buildEventRegistrationForm());
							RegistrationTab.doLayout();
	
							Ext.getCmp('eventsPanel').add(RegistrationTab).show();
						}
						
						EventRegForm = Ext.getCmp('event_registration_form').getForm();

						if (localFirstName !== '') {
							EventRegForm.findField('event_registration_first_name').setValue(localFirstName);
							EventRegForm.findField('event_registration_first_name').disable();
						}
						
						if (localLastName !== '') {
							EventRegForm.findField('event_registration_last_name').setValue(localLastName);
							EventRegForm.findField('event_registration_last_name').disable();
						}
						
						if (localPhone !== '') {
							EventRegForm.findField('event_registration_phone').setValue(localPhone);
							EventRegForm.findField('event_registration_phone').disable();
						}
						
						if (localEmail !== '') {
							EventRegForm.findField('event_registration_email').setValue(localEmail);
							EventRegForm.findField('event_registration_email').disable();
						}
						
						if (localAddress1 !== '') {
							EventRegForm.findField('event_registration_address_1').setValue(localAddress1);
							EventRegForm.findField('event_registration_address_1').disable();
						}
						
						if (localAddress2 !== '') {
							EventRegForm.findField('event_registration_address_2').setValue(localAddress1);
							EventRegForm.findField('event_registration_address_2').disable();
						}
						
						if (localCity !== '') {
							EventRegForm.findField('event_registration_city').setValue(localCity);
							EventRegForm.findField('event_registration_city').disable();
						}
						
						if (localStateId !== '') {
							EventRegForm.findField('event_registration_state_id').setValue(localStateId);
							EventRegForm.findField('event_registration_state_id').disable();
						}
						
						if (localZip !== '') {
							EventRegForm.findField('event_registration_zip').setValue(localZip);
							EventRegForm.findField('event_registration_zip').disable();
						}
					});
					
					theStore.load();
						
					// START COMMUNITY REGISTRATION						
					// Private Functions go here.
					var activityCostTotal = 0;
					var activityPricingStore;
					var localStates;					
					
					function clearEventRegistrationForm() {
						/*localMemberId = '';
						localFirstName = '';
						localLastName = '';
						localOrganization = '';
						localTitle = '';
						localUserType = '';
						localPhone = '';
						localEmail = '';
						localAddress1 = '';
						localAddress2 = '';
						localCity = '';
						localZip = '';*/
					}
					
					function registerEvent(btn,e) {
						e.stopEvent();
						
						Ext.getCmp('event_registration_form').getForm().findField('Body').setValue(Ext.getCmp('registrationSummaryPanel').getEl().dom.innerHTML);
						
						Ext.getCmp('event_registration_form').getForm().submit({
							method: 'POST',
							waitTitle: 'Please Wait',
							waitMsg: 'Validating and saving registration...',
							url: 'index.cfm?event=registerEventAction',
							failure:
								function (frm, act) {
									Ext.MessageBox.alert('Error!', act.result.errors.MSG);
								},
							success:
								function (frm, act) {
									Ext.MessageBox.alert('Complete!', 'Your registration is complete.');
									
									if (act.result.success == true){
										step1Tab = Ext.getCmp('eventRegistrationStep1');
										step2Tab = Ext.getCmp('eventRegistrationStep2');
										step3Tab = Ext.getCmp('eventRegistrationStep3');
										step4Tab = Ext.getCmp('eventRegistrationStep4');
				
										step1Tab.setDisabled(true);
										step2Tab.setDisabled(true);
										step3Tab.setDisabled(true);
										step4Tab.setDisabled(false);
									 	theTabPanel.setActiveTab(step4Tab);
									 	theButton.setText('Close Registration');
									} else {
										Ext.MessageBox.alert("Failed", act.result.errors.MSG);
										Ext.getCmp('eventsPanel').remove(Ext.getCmp('eventsPanel').getActiveTab());
									}
								}
						});
					}
					
					function buildEventRegistrationForm() {
						return new Ext.form.FormPanel({
							id: 'event_registration_form',
					        url:'amp_ext.cfm?action=registerEvent',
							method: 'POST',
							layout: 'fit',
					        labelAlign: 'right',
				            autoScroll: true,
					        frame: true,
					        autoWidth: true,
					        height: '100%',
							monitorValid: true,
							items: [{
						            xtype:'tabpanel',
						            id: 'eventRegistrationTabPanel',
						            activeTab: 0,
									deferredRender: true,
									layoutOnTabChange: true,
						            defaults:{height: 380, autoScroll: true}, 
						            items:[{
						            	title: 'Step 1: Registration',
						            	id: 'eventRegistrationStep1',
										listeners: {
										    'activate': function(p) {
										        p.doLayout();
											 	Ext.getCmp('registration_continue').setText('Step 2: Summary');
										    }
										},
										layout: 'border',
										items: [buildRegistrationFormPanel(),buildRegistrationActivityPanel()]
						            },{
						            	title: 'Step 2: Summary',
						            	id: 'eventRegistrationStep2',
										disabled: true,
										listeners: {
										    'activate': function(p) {
											 	Ext.getCmp('registration_continue').setText('Step 3: Payment');
												calculateActivityCost();
											 	this.items.each(function(childItem){ this.remove(childItem);}, this);
											 	this.add(buildRegistrationSummaryPanel());
										        p.doLayout();
										    }
										},
										items: [{ xtype: 'panel' }]
						            },{
						            	title: 'Step 3: Payment',
						            	id: 'eventRegistrationStep3',
										disabled: true,
										listeners: {
										    'activate': function(p) {
											 	Ext.getCmp('registration_continue').setText('Complete Registration');
												calculateActivityCost();
											 	this.items.each(function(childItem){ this.remove(childItem);}, this);
											 	this.add(buildRegistrationPaymentPanel());
										        p.doLayout();
										    }
										},
										items: [{ xtype: 'panel' }]
						            },{
						            	title: 'Step 4: Receipt',
						            	id: 'eventRegistrationStep4',
										disabled: true,
										listeners: {
										    'activate': function(p) {
											 	Ext.getCmp('registration_continue').setText('Close Registration');
											 	this.items.each(function(childItem){ this.remove(childItem);}, this);
											 	this.add(buildRegistrationReceiptPanel());
										        p.doLayout();
										    }
										},
										items: [{ xtype: 'panel' }]
						            }
								]
							}], 
							buttons: [{
									xtype: 'button',
									text: 'Step 2: Summary',
									id: 'registration_continue',
									formBind: true,
									handler: function(btn,e) {
										theTabPanel = Ext.getCmp('eventRegistrationTabPanel');
										ActiveTab = theTabPanel.getActiveTab().getId();
										theButton = Ext.getCmp('registration_continue');
										 
										if (ActiveTab == 'eventRegistrationStep1') {
											step2Tab = Ext.getCmp('eventRegistrationStep2');
											
											step2Tab.setDisabled(false);
										 	theTabPanel.setActiveTab(step2Tab);
										 	theButton.setText('Step 3: Payment');
										} else if (ActiveTab == 'eventRegistrationStep2') {
											step3Tab = Ext.getCmp('eventRegistrationStep3');
											
											step3Tab.setDisabled(false);
										 	theTabPanel.setActiveTab(step3Tab);
										 	theButton.setText('Complete Registration');
										} else if (ActiveTab == 'eventRegistrationStep3') {
											if (Ext.getCmp('event_registration_form').getForm().findField('payment_option').getValue() == '') {
												Ext.Msg.alert('Error', 'Please select a payment option');	
											} else {
												registerEvent(btn,e);
											}
										} else {
											RegistrationTab.close();
										}
									}
								},{
									xtype: 'button',
									text: 'Close',
									handler: function() { Ext.getCmp('eventsPanel').remove(Ext.getCmp('eventsPanel').getActiveTab()); }
								}
							],
							listeners: {
								clientvalidation: function(panel, valid) {
									if (!valid) {
										step2Tab = Ext.getCmp('eventRegistrationStep2');
										step3Tab = Ext.getCmp('eventRegistrationStep3');
										
										step2Tab.setDisabled(true);
										step3Tab.setDisabled(true);
									}
								},
								render: function() {
									this.getForm().isValid();
								}
							},
					        bbar: new Ext.ux.StatusBar({
					            id: 'eventregistrationform-statusbar',
					            defaultText: '',
					            plugins: new Ext.ux.ValidationStatus({form:'event_registration_form',showText:'Invalid Entries (click for details)'})
					        })
						});
					}
					
					function buildActivityFormField(activity, bodyPadding) {
						var returnField = '';
						var returnFieldLabel = '';
						var selectedMemberTypeId;
						
					   	activityPricingStore = new Ext.data.ArrayStore({
							fields: [
								{name: 'name', type: 'string'},
								{name: 'member_type_id', type: 'int'},
								{name: 'cost', type: 'int'},
								{name: 'valid_from', type: 'date'},
								{name: 'valid_from_time', type: 'string'},
								{name: 'valid_to', type: 'date'},
								{name: 'valid_to_time', type: 'string'},
								{name: 'display'}
							],
							data: activity.activity_pricing
						});
				
						//if (activity.children.length > 0) {
							theForm = Ext.getCmp('event_registration_form');
							
							if (theForm) {
								theForm = theForm.getForm();
								theSelectedMemberTypeId = theForm.findField('event_registration_member_type_id').getValue();
								memberPricingIndex = activityPricingStore.find('member_type_id', theSelectedMemberTypeId);
							
								if (memberPricingIndex == -1) {
									memberPricingIndex = activityPricingStore.find('member_type_id', 0);
								}
				
								memberPricingRow = activityPricingStore.getAt(memberPricingIndex);
								
								returnFieldLabel = (activity.activity_required == 'yes') ? activity.text + ' (required)' + ' - (' + Ext.util.Format.usMoney(memberPricingRow.data.cost) + ')' : activity.text + ' - (' + Ext.util.Format.usMoney(memberPricingRow.data.cost) + ')';
							} else {
								returnFieldLabel = (activity.activity_required == 'yes') ? activity.text + ' (required) - (select member)' : activity.text + ' - (select member)';
							}
				
							indexCounter = 0;
							parentActivityIndex = -1;
							Ext.each(localEventActivities, function(event_activity) {
								if (event_activity.activity_id == activity.activity_parent_id) {
									parentActivityIndex = indexCounter; 
								}
								indexCounter++;
							});
							
							// check to see if we have a parent, if so, check the parent's max child options to see if this should be a radio or checkbox.
							parentActivity = localEventActivities[parentActivityIndex];
						
							if (parentActivity && parentActivity.activity_max_child_options == 1) {
								returnField = {
									xtype: 'radio',
									name: 'child_activity_id_' + parentActivity.activity_id,
									inputValue: activity.activity_id,
									boxLabel: returnFieldLabel
								}; 
								
								
							//	AMP.Form.buildCheckbox(activity.id, returnFieldLabel, 1, (activity.activity_required == 'yes') ? true : false);
							} else {
								returnField = {
									xtype: 'checkbox',
									boxLabel: returnFieldLabel,
									inputValue: activity.activity_id,
									checked: (activity.activity_required == 'yes') ? true : false
								}; 
							}
							
							if (activity.activity_required == 'yes') { returnField.disabled = true; }
						//} else {
							
						//}
						
						returnPanel = {
							xtype: 'panel',
							width: (returnFieldLabel.length * 5) + bodyPadding + 40,
							bodyStyle: 'padding-left: ' + bodyPadding + 'px;',
							items: [returnField]
						};
						
						return returnPanel;
					}
				
					function createActivities(ActivityDisplayPanel) {
				        ActivityDisplayPanel.items.each(function(childItem){ ActivityDisplayPanel.remove(childItem);}, ActivityDisplayPanel);
						
						if (localEventActivities.length > 0) {
							Ext.each(localEventActivities, function(activity) {
								ActivityDisplayPanel.add(buildActivityFormField(activity, 10));
								if (activity.children.length > 0) {
									Ext.each(activity.children, function(child1){
										ActivityDisplayPanel.add(buildActivityFormField(child1, 30));
										if (child1.children.length > 0) {
											Ext.each(child1.children, function(child2){
												ActivityDisplayPanel.add(buildActivityFormField(child2, 50));
												if (child2.children.length > 0) {
													Ext.each(child2.children, function(child3){
														ActivityDisplayPanel.add(buildActivityFormField(child3, 70));
														if (child3.children.length > 0) {
															Ext.each(child3.children, function(child4){
																ActivityDisplayPanel.add(buildActivityFormField(child4, 90));
																if (child4.children.length > 0) {
																	Ext.each(child4.children, function(child5){
																		ActivityDisplayPanel.add(buildActivityFormField(child5, 110));
																		if (child5.children.length > 0) {
																			Ext.each(child5.children, function(child6){
																				ActivityDisplayPanel.add(buildActivityFormField(child6, 130));
																				if (child6.children.length > 0) {
																					Ext.each(child6.children, function(child7){
																						ActivityDisplayPanel.add(buildActivityFormField(child7, 150));
																						if (child7.children.length > 0) {
																							Ext.each(child7.children, function(child8){
																								ActivityDisplayPanel.add(buildActivityFormField(child8, 170));
																							});
																						}
																					});
																				}
																			});
																		}
																	});
																}
															});
														}
													});
												}
											});
										}
									});
								}
							});
						}
						
						ActivityDisplayPanel.doLayout();
					}
				
					function buildRegistrationFormPanel() {
						var localStates = Jack.data.getStates();
										 
						localStates.setDefaultSort('name', 'ASC');
						localStates.on('load', function() {
							Ext.getCmp('event_registration_form').getForm().findField('event_registration_state_id').setValue(localStateId);
						});
				
						registrationFormReturn = new Ext.Panel({
							region: 'center',
							title: (localEventName !== "") ? 'Registration for ' + localEventName : 'Registration for New Event',
							bodyStyle: 'padding-left: 5px;',
							layout: 'form',
							labelAlign: 'left',
							labelWidth: smallLabelWidth,
							items: [{
								xtype: 'hidden',
								name: 'event_registration_event_id',
								id: 'event_registration_event_id',
								value: localEventId
							},{
								xtype: 'hidden',
								name: 'event_registration_member_id',
								id: 'event_registration_member_id',
								value: localMemberId
							},{
								xtype: 'hidden',
								name: 'site_id',
								id: 'site_id',
								value: localEventSiteid
							},{
								xtype: 'hidden',
								name: 'amount_paid',
								id: 'amount_paid',
								value: 0
							},{
								xtype: 'hidden',
								name: 'Body',
								id: 'Body',
								value: ''
							},{
								xtype: 'hidden',
								id: 'event_registration_member_type_id',
								name: 'event_registration_member_type_id',
								value: localTypeId
							},{
								xtype: 'textfield',
								fieldLabel: 'First Name',
								id: 'event_registration_first_name',
								name: 'event_registration_first_name',
								allowBlank: false,
								value: localFirstName,
								anchor: '98%',
								blankText: 'First Name is required'
							},{
								xtype: 'textfield',
								fieldLabel: 'Last Name',
								id: 'event_registration_last_name',
								name: 'event_registration_last_name',
								allowBlank: false,
								value: localLastName,
								anchor: '98%',
								blankText: 'Last Name is required'
							/*},{
								xtype: 'textfield',
								fieldLabel: 'Organization',
								id: 'event_registration_organization',
								name: 'event_registration_organization',
								allowBlank: true,
								value: localOrganization,
								anchor: '98%',
								blankText: 'Organization is required'
							},{
								xtype: 'textfield',
								fieldLabel: 'Title',
								id: 'event_registration_title',
								name: 'event_registration_title',
								allowBlank: false,
								value: localTitle,
								anchor: '98%',
								blankText: 'Title is required'*/
							},{
								xtype: 'textfield',
								fieldLabel: 'Phone',
								id: 'event_registration_phone',
								name: 'event_registration_phone',
								allowBlank: false,
								value: localPhone,
								anchor: '98%',
								blankText: 'Phone is required'
							},{
								xtype: 'textfield',
								fieldLabel: 'Email',
								id: 'event_registration_email',
								name: 'event_registration_email',
								allowBlank: false,
								value: localEmail,
								anchor: '98%',
								blankText: 'Email is required'
							},{
								xtype: 'textfield',
								fieldLabel: 'Address 1',
								id: 'event_registration_address_1',
								name: 'event_registration_address_1',
								allowBlank: false,
								value: localAddress1,
								anchor: '98%',
								blankText: 'Address 1 is required'
							},{
								xtype: 'textfield',
								fieldLabel: 'Address 2',
								id: 'event_registration_address_2',
								name: 'event_registration_address_2',
								allowBlank: true,
								value: localAddress2,
								anchor: '98%',
								blankText: 'Address 2 is required'
							},{
								xtype: 'textfield',
								fieldLabel: 'City',
								id: 'event_registration_city',
								name: 'event_registration_city',
								allowBlank: false,
								value: localCity,
								anchor: '98%',
								blankText: 'City is required'
							},{
								xtype: 'panel',
								layout: 'column',
								defaults: {
									xtype: 'panel',
									layout: 'form'
								},
								items: [{
									width: '60%',
									labelWidth: smallLabelWidth,
									items: [
										{
											xtype: 'combo',
											fieldLabel: 'State',
											name: 'event_registration_state_display',
											id: 'event_registration_state_component_id',
											hiddenName: 'event_registration_state_id',
											store: localStates,
											valueField:'id',
											displayField:'abbrev',
											typeAhead: true,
											forceSelection: true,
											mode: 'local',
											triggerAction: 'all',
											selectOnFocus: true,
											minListWidth: mediumFieldWidth,
											allowBlank: false,
											value: localStateId,
											anchor: '98%',
											blankText: 'State is required',
											emptyText: 'Select...'
										}
									]	
								},{
									width: 134,
									labelWidth: 40,
									items: [
										// AMP.Form.buildTextField('Zip', 'event_registration_zip', 'event_registration_zip', false, localZip, mediumFieldWidth, '', '98%')
										{
											xtype: 'textfield',
											fieldLabel: 'Zip',
											name: 'event_registration_zip',
											id: 'event_registration_zip',
											allowBlank: false,
											value: localZip,
											anchor: '98%',
											blankText: 'Zip is required'
										}
									]
								}]
							},{
								xtype: 'textarea',
								fieldLabel: 'Special Needs',
								name: 'event_registration_special_needs',
								id: 'event_registration_special_needs',
								height: 40,
								anchor: '98%'
							},{
								xtype: 'textarea',
								fieldLabel: 'Physical Needs',
								name: 'event_registration_physical_needs',
								id: 'event_registration_physical_needs',
								height: 40,
								anchor: '98%'
							}]
						});
						
						//Ext.getCmp('event_registration_member_type_id').on('select', function(n) {
						//	createActivities(Ext.getCmp('activityDisplayPanel'));
						//});
				
						registrationFormReturn.on('render', function() {
							localStates.load();
							createActivities(Ext.getCmp('activityDisplayPanel'));
						});
						
						return registrationFormReturn;
					}
					
					function calculateActivityCost() {
						activityCostTotal = 0;
				
						function addActivityCost(activity) {
						   	activityPricingStore = new Ext.data.ArrayStore({
								fields: [
									{name: 'name', type: 'string'},
									{name: 'member_type_id', type: 'int'},
									{name: 'cost', type: 'int'},
									{name: 'valid_from', type: 'date'},
									{name: 'valid_from_time', type: 'string'},
									{name: 'valid_to', type: 'date'},
									{name: 'valid_to_time', type: 'string'},
									{name: 'display'}
								],
								data: activity.activity_pricing
							});
				
							theSelectedMemberTypeId = Ext.getCmp('event_registration_form').getForm().findField('event_registration_member_type_id').getValue();
							memberPricingIndex = activityPricingStore.find('member_type_id', theSelectedMemberTypeId);
						
							if (memberPricingIndex == -1) {
								memberPricingIndex = activityPricingStore.find('member_type_id', 0);
							}
				
							memberPricingRow = activityPricingStore.getAt(memberPricingIndex);
							activityCostTotal += (memberPricingRow.data.cost > 0) ? memberPricingRow.data.cost : 0;		
						}
						
						CostActivityItems = Ext.getCmp('activityDisplayPanel').findBy(function(c) {
							if (c.constructor.xtype == 'checkbox' || c.constructor.xtype == 'radio')
								return true;
							else
								return false;
						});
				
						Ext.each(CostActivityItems, function(activity_item){
							activity_item_id = (activity_item.value) ? activity_item.value : activity_item.inputValue;
				
							Ext.each(localEventActivities, function(activity) {
								if (activity_item_id == activity.activity_id && activity_item.checked) addActivityCost(activity);
								if (activity.children.length > 0) {
									Ext.each(activity.children, function(child1){
										if (activity_item_id == child1.activity_id && activity_item.checked) addActivityCost(child1);
										if (child1.children.length > 0) {
											Ext.each(child1.children, function(child2){
												if (activity_item_id == child2.activity_id && activity_item.checked) addActivityCost(child2);
												if (child2.children.length > 0) {
													Ext.each(child2.children, function(child3){
														if (activity_item_id == child3.activity_id && activity_item.checked) addActivityCost(child3);
														if (child3.children.length > 0) {
															Ext.each(child3.children, function(child4){
																if (activity_item_id == child4.activity_id && activity_item.checked) addActivityCost(child4);
																if (child4.children.length > 0) {
																	Ext.each(child4.children, function(child5){
																		if (activity_item_id == child5.activity_id && activity_item.checked) addActivityCost(child5);
																		if (child5.children.length > 0) {
																			Ext.each(child5.children, function(child6){
																				if (activity_item_id == child6.activity_id && activity_item.checked) addActivityCost(child6);
																				if (child6.children.length > 0) {
																					Ext.each(child6.children, function(child7){
																						if (activity_item_id == child7.activity_id && activity_item.checked) addActivityCost(child7);
																						if (child7.children.length > 0) {
																							Ext.each(child7.children, function(child8){
																								if (activity_item_id == child8.activity_id && activity_item.checked) addActivityCost(child8);
																							});
																						}
																					});
																				}
																			});
																		}
																	});
																}
															});
														}
													});
												}
											});
										}
									});
								}
							});
						});
						
						Ext.getCmp('amount_paid').setValue(activityCostTotal);
					}
					
					function buildRegistrationActivityPanel() {
						var ActivityDisplayPanel = new Ext.Panel({
							title: 'Activities',
							id: 'activityDisplayPanel',
							region: 'east',
							width: 325,
							height: 445,
							layout: 'form',
							autoScroll: true,
							items: [new Ext.Panel()]
						});
						
						if (localEventActivities.length > 0) {
							createActivities(ActivityDisplayPanel);
						}
						
						return ActivityDisplayPanel;
					}
					
					function buildRegistrationSummaryPanel(show_title) {
						var theForm = Ext.getCmp('event_registration_form').getForm();
						
						if (show_title == false) {
							show_title = false;
						} else {
							show_title = true;
						}
				
						registrationSummaryPanel = new Ext.Panel({
							xtype: 'panel',
							id: 'registrationSummaryPanel',
							layout: 'form',
							title: (show_title) ? 'Registration for ' + localEventName + ': ' + theForm.findField('event_registration_first_name').getValue() + ' ' + theForm.findField('event_registration_last_name').getValue() : '',
							bodyStyle: 'padding-left: 20px;',
							autoScroll: true,
							items: [{
								xtype: 'box',
								autoEl: { 
									html:	'<div style="clear: both;">' +
											'	<div style="font-weight: bold; font-size: 14px; color: #666;">Member Info:</div>' +
											'</div>' +
											'<div style="clear: both">&nbsp;</div>' +
											'<div style="clear: both; color: #666; padding-left: 20px;">' +
											'	<div style="clear: both;">' +
											'		<div style="float: left; width: 100px; font-weight: bold;">First Name:</div>' +
											'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_first_name').getValue() + '</div>' +
											'	</div>' +
											'	<div style="clear: both;">' +
											'		<div style="float: left; width: 100px; font-weight: bold;">Last Name:</div>' +
											'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_last_name').getValue() + '</div>' +
											'	</div>' +
											'	<div style="clear: both;">' +
											'		<div style="float: left; width: 100px; font-weight: bold;">Type:</div>' +
											'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_member_type_id').getRawValue() + '</div>' +
											'	</div>' +
/*												'	<div style="clear: both;">' +
												'		<div style="float: left; width: 100px; font-weight: bold;">Organization:</div>' +
												'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_organization').getValue() + '</div>' +
												'	</div>' +
												'	<div style="clear: both;">' +
												'		<div style="float: left; width: 100px; font-weight: bold;">Title:</div>' +
												'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_title').getValue() + '</div>' +
												'	</div>' + */
											'	<div style="clear: both;">' +
											'		<div style="float: left; width: 100px; font-weight: bold;">Phone:</div>' +
											'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_phone').getValue() + '</div>' +
											'	</div>' +
											'	<div style="clear: both;">' +
											'		<div style="float: left; width: 100px; font-weight: bold;">Email:</div>' +
											'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_email').getValue() + '</div>' +
											'	</div>' +
											'	<div style="clear: both;">' +
											'		<div style="float: left; width: 100px; font-weight: bold;">Address:</div>' +
											'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_address_1').getValue() + '</div>' +
											'	</div>' +
											'	<div style="clear: both;' + ((theForm.findField('event_registration_address_2').getValue() !== '') ? '' : 'display: none') + '">' +
											'		<div style="float: left; width: 100px; font-weight: bold;">&nbsp;</div>' +
											'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_address_2').getValue() + '</div>' +
											'	</div>' +
											'	<div style="clear: both;">' +
											'		<div style="float: left; width: 100px; font-weight: bold;">&nbsp;</div>' +
											'		<div style="float: left; font-weight: bold;">' + theForm.findField('event_registration_city').getValue() + ',&nbsp;</div>' +
											'		<div style="float: left; font-weight: bold;">' + theForm.findField('event_registration_state_id').getRawValue() + '&nbsp;</div>' +
											'		<div style="float: left; font-weight: bold;">' + theForm.findField('event_registration_zip').getValue() + '</div>' +
											'	</div>' +
/*												'	<div style="clear: both;">' +
												'		<div style="float: left; width: 100px; font-weight: bold;">&nbsp;</div>' +
												'		<div style="float: left; width: 300px; font-weight: bold;">' + theForm.findField('event_registration_comments').getValue() + '</div>' +
												'	</div>' + */
											'</div>' +
											'<div style="clear: both">&nbsp;</div>' +'<div style="clear: both;">' +
											'	<div style="font-weight: bold; font-size: 14px; color: #666">Selected Activities:</div>' +
											'</div>' +
											'<div style="clear: both">&nbsp;</div>'
								}
							}]
						});
						
						function buildActivityDisplayField(activity, display, padding) {
							if (display) {
							   	activityPricingStore = new Ext.data.ArrayStore({
									fields: [
										{name: 'name', type: 'string'},
										{name: 'member_type_id', type: 'int'},
										{name: 'cost', type: 'int'},
										{name: 'valid_from', type: 'date'},
										{name: 'valid_from_time', type: 'string'},
										{name: 'valid_to', type: 'date'},
										{name: 'valid_to_time', type: 'string'},
										{name: 'display'}
									],
									data: activity.activity_pricing
								});
				
								theSelectedMemberTypeId = theForm.findField('event_registration_member_type_id').getValue();
								memberPricingIndex = activityPricingStore.find('member_type_id', theSelectedMemberTypeId);
							
								if (memberPricingIndex == -1) {
									memberPricingIndex = activityPricingStore.find('member_type_id', 0);
								}
				
								memberPricingRow = activityPricingStore.getAt(memberPricingIndex);
				
								return {
									xtype: 'panel',
									html:	'<div style="clear: both; padding-left: ' + padding + 'px;">' +
											'	<div style="float: left; width: ' + (500 - padding) + 'px; font-weight: bold; color: #666;">' +
													activity.activity_name + 
											'	</div>' + 
											'	<div align="right" style="float: left; width: 100px; font-style: italic; color: #666;">' +
													Ext.util.Format.usMoney(memberPricingRow.data.cost) +  
											'	</div>' + 
											'</div>' + 
											'<div style="clear: both;"></div>'
								};
							} else {
								return new Ext.Panel();
							}
						}
						
						ActivityItems = Ext.getCmp('activityDisplayPanel').findBy(function(c) {
							if (c.constructor.xtype == 'checkbox' || c.constructor.xtype == 'radio')
								return true;
							else
								return false;
						});
						
						Ext.each(ActivityItems, function(activity_item){
							activity_item_id = (activity_item.value) ? activity_item.value : activity_item.inputValue;
				
							Ext.each(localEventActivities, function(activity) {
								if (activity_item_id == activity.activity_id) registrationSummaryPanel.add(buildActivityDisplayField(activity, activity_item.checked, 10));
								if (activity.children.length > 0) {
									Ext.each(activity.children, function(child1){
										if (activity_item_id == child1.activity_id) registrationSummaryPanel.add(buildActivityDisplayField(child1, activity_item.checked, 30));
										if (child1.children.length > 0) {
											Ext.each(child1.children, function(child2){
												if (activity_item_id == child2.activity_id) registrationSummaryPanel.add(buildActivityDisplayField(child2, activity_item.checked, 50));
												if (child2.children.length > 0) {
													Ext.each(child2.children, function(child3){
														if (activity_item_id == child3.activity_id) registrationSummaryPanel.add(buildActivityDisplayField(child3, activity_item.checked, 70));
														if (child3.children.length > 0) {
															Ext.each(child3.children, function(child4){
																if (activity_item_id == child4.activity_id) registrationSummaryPanel.add(buildActivityDisplayField(child4, activity_item.checked, 90));
																if (child4.children.length > 0) {
																	Ext.each(child4.children, function(child5){
																		if (activity_item_id == child5.activity_id) registrationSummaryPanel.add(buildActivityDisplayField(child5, activity_item.checked, 110));
																		if (child5.children.length > 0) {
																			Ext.each(child5.children, function(child6){
																				if (activity_item_id == child6.activity_id) registrationSummaryPanel.add(buildActivityDisplayField(child6, activity_item.checked, 130));
																				if (child6.children.length > 0) {
																					Ext.each(child6.children, function(child7){
																						if (activity_item_id == child7.activity_id) registrationSummaryPanel.add(buildActivityDisplayField(child7, activity_item.checked, 150));
																						if (child7.children.length > 0) {
																							Ext.each(child7.children, function(child8){
																								if (activity_item_id == child8.activity_id) registrationSummaryPanel.add(buildActivityDisplayField(child8, activity_item.checked, 170));
																							});
																						}
																					});
																				}
																			});
																		}
																	});
																}
															});
														}
													});
												}
											});
										}
									});
								}
							});
						});
							
						registrationSummaryPanel.add({
							xtype: 'panel',
							html:	'<div style="width: 605px;"><hr/></div>' +
									'<div style="clear: both;">' +
									'	<div style="float: left; width: 500px;font-weight: bold; color: #666; font-size: 14px;">' +
									'		Total Cost:' + 
									'	</div>' + 
									'	<div align="right" style="float: left; width: 100px; font-style: italic; color: #666; font-size: 14px;">' +
											Ext.util.Format.usMoney(activityCostTotal) +  
									'	</div>' + 
									'</div>' + 
									'<div style="clear: both;"></div>'
						});
						
						return registrationSummaryPanel;
					}
					
					function buildRegistrationPaymentPanel() {
						paymentOptionsPanel = new Ext.Panel({
							id: 'paymentOptionsPanel',
							autoScroll: true,
							bodyStyle: 'padding-left: 10px;',
							items: [new Ext.Panel()]
						});
						
						paymentFormPanel = new Ext.Panel({
							id: 'paymentFormPanel',
							autoScroll: true,
							bodyStyle: 'padding-left: 10px;',
							items: [new Ext.Panel()]
						});
				
						registrationPaymentPanel = new Ext.Panel({
							layout: 'form',
							title: 'Payment for ' + localEventName + ': ' + Ext.getCmp('event_registration_first_name').getValue() + ' ' + Ext.getCmp('event_registration_last_name').getValue(),
							autoScroll: true,
							bodyStyle: 'padding-left: 10px;',
							items: [
								{
									xtype: 'box',
									autoEl: { html: '<div style="font-size: 14px; font-weight: bold; color: #666">Please select a payment option:</div>' }
								},
								paymentOptionsPanel,
								paymentFormPanel
							]
						});
				
					   	eventBillingStore = new Ext.data.ArrayStore({
							fields: [
								{name: 'member_type_id', type: 'int'},
								{name: 'member_type_name', type: 'string'},
								{name: 'billing_types'}
							]
						});
						
						eventBillingStore.on('load', function() {
						//	console.log(eventBillingStore);
							
							localBillingTypes = new Ext.data.JsonStore({
						         url: 'index.cfm',
							     baseParams: { event:'billingTypesJSON' },
						         root: 'content',
						         totalProperty: 'totalCount',
						         id: 'id',
						         fields: [ 
							         {name: 'id', type: 'int'},
							         {name: 'name', type: 'string'}
						         ]
							});				 
				
							localBillingTypes.setDefaultSort('name', 'ASC');
				
							localCreditTypes = new Ext.data.JsonStore({
						         url: 'index.cfm',
							     baseParams: { event:'creditTypesJSON' },
						         root: 'content',
						         totalProperty: 'totalCount',
						         id: 'id',
						         fields: [ 
							         {name: 'id', type: 'int'},
							         {name: 'name', type: 'string'},
							         {name: 'logo', type: 'string'}
						         ]
							});				 
				
							localCreditTypes.setDefaultSort('name', 'ASC');
							
							localCreditTypes.on('load', function() {
								CreditCardPanel = Ext.getCmp('credit_card_panel');
								
								localCreditTypes.each(function(credit_card) {
									CreditCardPanel.add({
										xtype: 'radio',
										name: 'event_registration_credit_card_type',
										boxLabel: '<img src="' + credit_card.data.logo + '" alt="' + credit_card.data.name + '" />',
										style: 'vertical-align: middle;',
										inputValue: credit_card.data.name
									});
									
									CreditCardPanel.doLayout();
								});
							});
							
							localBillingTypes.on('load', function() {
								monthArray = [
									[0, 'January'],
									[1, 'February'],
									[2, 'March'],
									[3, 'April'],
									[4, 'May'],
									[5, 'June'],
									[6, 'July'],
									[7, 'August'],
									[8, 'September'],
									[9, 'October'],
									[10, 'November'],
									[11, 'December']
								];
								
								localMonths = new Ext.data.ArrayStore({
									fields: [
										{name: 'month', type: 'int'},
										{name: 'name', type: 'string'}
									],
									data: monthArray
								});
								
								thisDate = new Date();
								thisYear = thisDate.getFullYear();
								
								yearArray = [];
								yearArrayCnt = 0;
								for (i=thisYear;i<=(thisYear + 10);i++) {
									yearArray[yearArrayCnt] = [i];
									yearArrayCnt++;
								}
								
								localYears = new Ext.data.ArrayStore({
									fields: [
										{name: 'year', type: 'int'}
									],
									data: yearArray
								});
				
								function buildRegistrationOnlinePaymentForm() {
									onlinePaymentForm = new Ext.Panel({
										xtype: 'panel',
										layout: 'column',
										width: 930,
										bodyStyle: 'padding-top: 50px;',
										defaults: {
											xtype: 'panel',
											layout: 'form',
											labelWidth: labelWidth,
											labelAlign: 'left',
											columnWidth: 0.5,
											bodyStyle: 'padding-left: 20px;'
										},
										items: [{
											title: 'Credit Card Information',
											items: [{
												xtype: 'panel',
												layout: 'column',
												style: 'padding-bottom: 10px;',
												items: [{
													xtype: 'box',
													width: 155,
													// forcing style to match ext labels
													autoEl: { html: '<div class="x-form-item x-tab-item"><label class="x-form-item-label" style="width: 150px;" for="event_name">Credit Card Type:</label></div>' }
												},{
														xtype: 'panel',
														layout: 'column',
														width: '60%',
														id: 'credit_card_panel'
												}]
											},{
												xtype: 'textfield',
												fieldLabel: 'First Name',
												name: 'event_registration_card_first_name',
												id: 'event_registration_card_first_name',
												allowBlank: true,
												anchor: '98%'
											},{
												xtype: 'textfield',
												fieldLabel: 'Last Name',
												name: 'event_registration_card_last_name',
												id: 'event_registration_card_last_name',
												allowBlank: true,
												anchor: '98%'
											},{
												xtype: 'textfield',
												fieldLabel: 'Company Name',
												name: 'event_registration_card_company_name',
												id: 'event_registration_card_company_name',
												allowBlank: true,
												anchor: '98%'
											},{
												xtype: 'textfield',
												fieldLabel: 'Credit Card Number',
												name: 'event_registration_card_number',
												id: 'event_registration_card_number',
												allowBlank: false,
												anchor: '98%'
											},{
												xtype: 'panel',
												layout: 'column',
												defaults: {
													xtype: 'panel',
													layout: 'form',
													labelAlign: 'left'
												},
												items: [{
													xtype: 'box',
													width: 155,
													autoEl: { html: '<div class="x-form-item x-tab-item"><label class="x-form-item-label" style="width: 150px;" for="event_name">Expiration Date:</label></div>' }
												},{
													xtype: 'panel',
													layout: 'column',
													width: 285,
													defaults: {
														xtype: 'panel',
														layout: 'form',
														labelWidth: 40
													},
													items: [{
														items: [{
															xtype: 'combo',
															fieldLabel: 'Month',
															name: 'event_registration_expiration_month_display',
															id: 'event_registration_expiration_month_id',
															hiddenName: 'event_registration_expiration_month',
															store: localMonths,
															valueField:'month',
															displayField:'name',
															typeAhead: true,
															forceSelection: true,
															mode: 'local',
															triggerAction: 'all',
															selectOnFocus: true,
															minListWidth: mediumFieldWidth,
															allowBlank: false,
															width: 125,
															value: thisDate.getMonth(),
															emptyText: 'Select...'
														}]
													},{
														bodyStyle: 'padding-left: 5px;',
														items: [{
															xtype: 'combo',
															fieldLabel: 'Year',
															name: 'event_registration_expiration_year_display',
															id: 'event_registration_expiration_year_id',
															hiddenName: 'event_registration_expiration_year',
															store: localYears,
															valueField:'year',
															displayField:'year',
															typeAhead: true,
															forceSelection: true,
															mode: 'local',
															triggerAction: 'all',
															selectOnFocus: true,
															minListWidth: mediumFieldWidth,
															allowBlank: false,
															width: 60,
															value: thisDate.getFullYear(),
															emptyText: 'Select...'
														}]
													}]
												}]
											},{
												xtype: 'textfield',
												fieldLabel: 'Security Code',
												name: 'event_registration_card_security_code',
												id: 'event_registration_card_security_code',
												allowBlank: true,
												width: 35
											}]
										},{
											title: 'Billing Address',
											items: [{
												xtype: 'checkbox',
												name: 'event_registration_billing_same',
												id: 'event_registration_billing_same',
												fieldLabel: 'Same as Registration', 
												inputValue: 1,
												checked: false
											},{
												xtype: 'textfield',
												fieldLabel: 'Address 1',
												name: 'event_registration_billing_address_1',
												id: 'event_registration_billing_address_1',
												allowBlank: true,
												anchor: '98%'
											},{
												xtype: 'textfield',
												fieldLabel: 'Address 2',
												name: 'event_registration_billing_address_2',
												id: 'event_registration_billing_address_2',
												allowBlank: true,
												anchor: '98%'
											},{
												xtype: 'textfield',
												fieldLabel: 'City',
												name: 'event_registration_billing_city',
												id: 'event_registration_billing_city',
												allowBlank: true,
												anchor: '98%'
											},{
												xtype: 'textfield',
												fieldLabel: 'State',
												name: 'event_registration_billing_state_id',
												id: 'event_registration_billing_state_id',
												allowBlank: true,
												anchor: '98%'
											},{
												xtype: 'textfield',
												fieldLabel: 'Zip',
												name: 'event_registration_billing_zip',
												id: 'event_registration_billing_zip',
												allowBlank: true,
												anchor: '98%'
											}]
										}]
									});
									
									onlinePaymentForm.on('render', function() {
										localCreditTypes.load();
										
										Ext.getCmp('event_registration_billing_same').on('check', function(cb) {
											if (cb.checked) {
												Ext.getCmp('event_registration_billing_address_1').setValue(Ext.getCmp('event_registration_address_1').getValue());
												Ext.getCmp('event_registration_billing_address_2').setValue(Ext.getCmp('event_registration_address_2').getValue());
												Ext.getCmp('event_registration_billing_city').setValue(Ext.getCmp('event_registration_city').getValue());
												Ext.getCmp('event_registration_billing_state_id_id').setValue(Ext.getCmp('event_registration_state_id_id').getValue());
												Ext.getCmp('event_registration_billing_zip').setValue(Ext.getCmp('event_registration_zip').getValue());
											} else {
												Ext.getCmp('event_registration_billing_address_1').setValue('');
												Ext.getCmp('event_registration_billing_address_2').setValue('');
												Ext.getCmp('event_registration_billing_city').setValue('');
												Ext.getCmp('event_registration_billing_state_id_id').setValue('');
												Ext.getCmp('event_registration_billing_zip').setValue('');
											}
										});
									});
									
									return onlinePaymentForm;
								}
								
								memberBillingIndex = eventBillingStore.find('member_type_id', Ext.getCmp('event_registration_member_type_id_id').getValue());
								
								if (memberBillingIndex == -1) {
									memberBillingIndex = eventBillingStore.find('member_type_id', 0);
								}
								
								billingTypeArray = eventBillingStore.getAt(memberBillingIndex).data.billing_types;
								
								Ext.each(billingTypeArray, function(type) {
									tempBillingIndex = localBillingTypes.find('id', type);
									tempBillingType = localBillingTypes.getAt(tempBillingIndex);
									
									paymentOptionsPanel.add({
										xtype: 'radio',
										name: 'payment_option',
										allowBlank: false,
										inputValue: tempBillingType.data.id,
										boxLabel: tempBillingType.data.name,
										listeners: {
											check: function(cb) {
												if (cb.checked) {
												 	paymentFormPanel.items.each(function(childItem){ paymentFormPanel.remove(childItem);}, paymentFormPanel);
													
													if (cb.inputValue == 1) {
														paymentFormPanel.add(buildRegistrationOnlinePaymentForm());
													} else if (cb.inputValue == 2) {
														paymentFormPanel.add({
															xtype: 'box',
															style: 'padding-top: 75px;',
															autoEl: { html: '<div style="font-weight: bold; font-size: 14px; color: #666;">You have chosen to be invoiced please complete your registration.</div>' }
														});
													} else if (cb.inputValue == 4) {
														paymentFormPanel.add({
															xtype: 'box',
															style: 'padding-top: 75px;',
															autoEl: { html: '<div style="font-weight: bold; font-size: 14px; color: #666;">You have chosen to pay at the door, please complete your registration.</div>' }
														});
													} else {
														paymentFormPanel.add({
															xtype: 'box',
															style: 'padding-top: 75px;',
															autoEl: { html: '<div style="font-weight: bold; font-size: 14px; color: #666;">You have marked this registration as complimentary, please complete your registration.</div>' }
														});
													}
				
													paymentFormPanel.doLayout();
												}
											}
										}
									});
								});
								
								paymentOptionsPanel.doLayout();
				
								if (paymentOptionsPanel) {
									paymentOptionsPanel.cascade(function(item) {
										if (item.isFormField) {
											Ext.getCmp('event_registration_form').form.items.add(item);
										}
									});
								}
							});
				
							localBillingTypes.load();
						});
						
						eventBillingStore.loadData(localEventBillingTypes);
				
						return registrationPaymentPanel;
					}
				
					function buildRegistrationReceiptPanel() {
						var theForm = Ext.getCmp('event_registration_form').getForm();
				
						registrationReceiptPanel = new Ext.Panel({
							xtype: 'panel',
							id: 'registrationReceiptPanel',
							layout: 'form',
							title: 'Receipt for ' + localEventName + ': ' + theForm.findField('event_registration_first_name').getValue() + ' ' + theForm.findField('event_registration_last_name').getValue(),
							bodyStyle: 'padding-left: 20px;',
							autoScroll: true,
							tbar: [{
								text: 'Print',
					            icon: appAMPUrl + 'images/silk/icons/printer.png',
					            cls: 'x-btn-text-icon',
								handler: function() {
									var win = window.open("", "win", "width=300,height=200"); // a window object
									win.document.open("text/html", "replace");
									win.document.write(Ext.getCmp("registrationSummaryPanel").getEl().dom.innerHTML);
									win.document.close();
									win.print();
								}
							},{
								text: 'Email To',
					            icon: appAMPUrl + 'images/silk/icons/email.png',
					            cls: 'x-btn-text-icon',
								handler: function() {
									emailToWin = new Ext.Window({
										autoScroll: true,
										title: 'Please enter a recipient email address',
										width: 400,
										height: 150,
										closeAction: 'close',
										modal: true,
										plain: true,
										y: 0
									});
												
									function emailToSubmit(btn,e) {
										e.stopEvent();
										
										emailAddress = emailToForm.getForm().findField('email').getValue();
										emailArray = [0, emailAddress, emailAddress];
										
										emailToForm.getForm().findField('to').setValue(emailArray);
										Ext.getCmp('event_email_to_form').getForm().findField('Body').setValue(Ext.getCmp('registrationSummaryPanel').getEl().dom.innerHTML);
				
										Ext.getCmp('event_email_to_form').getForm().submit({
											method: 'POST',
											waitTitle: 'Please Wait',
											waitMsg: 'Validating and send email...',
											failure:
												function (frm, act) {
													Ext.MessageBox.alert('Error!', 'There was an error sending your email.  Please try again later.');
													emailToWin.close();
												},
											success:
												function (frm, act) {
													emailToWin.close();
												}
										});
									}
				
									var emailToForm = new Ext.form.FormPanel({
										height: '100%',
										width: '100%',
								        url:'index.cfm?event=registrationSendEmail',
								        id: 'event_email_to_form',
										method: 'POST',
										bodyStyle: 'padding: 10px;',
										labelAlign: 'side',
										labelWidth: smallLabelWidth,
										monitorValid: true,
										items: [{
											xtype: 'textfield',
											fieldLabel: 'Recipient Email',
											name: 'email',
											id: 'email',
											allowBlank: 'false',
											width: XLFieldWidth,
											vtype: 'email'
										},{
											xtype: 'hidden',
											id: 'Body',
											name: 'Body'
										},{
											xtype: 'hidden',
											id: 'to',
											name: 'to'
										}],
										buttons: [{
											text: 'Submit',
											formBind: true,
											handler: emailToSubmit
										},{
											text: 'Close',
											formBind: false,
											handler: function(ev) { emailToWin.close(); }
										}],
										keys: [{
											key: 13,
											fn: function(key,e) {
												if (emailToForm.getForm().isValid()) {
													emailToSubmit(key,e);
												}
											}
										}]
									});
				
									emailToWin.add(emailToForm);
									emailToWin.show();
								}
							}],
							items: [
								buildRegistrationSummaryPanel(false)
							]
						});
						
						return registrationReceiptPanel;
					}
				},
				viewDetail: function(member_id, new_tab) {
					var row = Ext.getCmp('eventsGrid').getSelectionModel().getSelected();
					var event_id = row.data.id;
					var website_content = row.data.website_content;
					var event_name = row.data.name;
					
					if (typeof new_tab != 'undefined' && ! new_tab) {
						if (typeof(DetailWin) != "undefined") {
							DetailWin.close();
						}
	
						DetailWin = new Ext.Window({
							autoScroll: true,
							title: 'Detail: ' + event_name, 
							height: 500,
							width: 500,
							closeAction: 'close',
							modal: true,
							plain: true,
							html: website_content,
							y: 0,
							buttonAlign: 'center',
					        buttons: [{
					        	text: 'Register',
					        	handler: function() { Jack.events.registerEvent(event_id, true); }
					        //	handler: function() { Jack.events.registerEvent(event_id, member_id, event_name); }
					        },{
					        	text: 'Close',
					        	handler: function() { Ext.getCmp('eventsPanel').remove(Ext.getCmp('eventsPanel').getActiveTab()); }
					        }]
						});
						
						DetailWin.show();
					} else {
						Ext.getCmp('eventsPanel').add({
							title: 'Detail: ' + event_name,
							closable: true,
							height: 485,
							html: website_content,
							bodyStyle: 'padding-left: 10px; padding-right: 10px;',
							buttonAlign: 'center',
					        buttons: [{
					        	text: 'Register',
					        	handler: function() { Jack.events.registerEvent(event_id, false); }
					        //	handler: function() { Jack.events.registerEvent(event_id, member_id, event_name); }
					        },{
					        	text: 'Close',
					        	handler: function() { Ext.getCmp('eventsPanel').remove(Ext.getCmp('eventsPanel').getActiveTab()); }
					        }]
						}).show();
					}
				},
				mapIt: function(address, location_name, new_tab) {
					if (typeof new_tab != 'undefined' && new_tab) {
						// This doesn't work yet due to cross domain restrictions
						
						Ext.getCmp('eventsPanel').add({
							title: location_name,
							closable: true,
							height: 485,
					        autoLoad: 'http://maps.google.com?q=' + address
						}).show();
					} else {
						window.open('http://maps.google.com?q=' + address);
					}
				}
			};
		}(),
		remoteLogin: function(event,args) {
			document.location.href='/amp_ext.cfm?action=remoteLogin&redirect_event=' + event + '&redirect_args=' + args;
		}
	};
}();