Ext.show.editRegisteredUsers = function(mainPanel){

	/************* Show list store *************/
	var storeShowsRegistered = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/shows.php'}),
        baseParams: { method: 'list', user_id: Ext.userId, user_level: Ext.userLevel },
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'show_id'
        },
        [
            {name: 'id', mapping: 'show_id'},
            {name: 'show_nm', mapping: 'show_nm'},
            {name: 'show_date_st', mapping: 'show_date_st'},
            {name: 'show_date_en', mapping: 'show_date_en'},
            {name: 'show_length', mapping: 'show_length'},
            {name: 'show_demo_owner', mapping: 'show_demo_owner'},
            {name: 'show_demo_owner_id', mapping: 'show_demo_owner_id'},
            {name: 'show_truck_owner', mapping: 'show_truck_owner'},
            {name: 'show_truck_owner_id', mapping: 'show_truck_owner_id'},
            {name: 'show_marketing_owner', mapping: 'show_marketing_owner'},
            {name: 'show_marketing_owner_id', mapping: 'show_marketing_owner_id'},
            {name: 'show_tour_owner', mapping: 'show_tour_owner'},
            {name: 'show_tour_owner_id', mapping: 'show_tour_owner_id'},
            {name: 'show_meeting_room_owner', mapping: 'show_meeting_room_owner'},
            {name: 'show_meeting_room_owner_id', mapping: 'show_meeting_room_owner_id'},
            {name: 'show_date', mapping: 'show_date'},
            {name: 'show_year', mapping: 'show_year'}

        ])
    });
    // Preload the show combobox list
    storeShowsRegistered.load({params:{query:'', user_id: Ext.userId, user_level: Ext.userLevel }});
    // Custom rendering Template using the 'name' field from above
    var showTpl = new Ext.XTemplate(
        '<tpl for="."><div class="search-item">',
            '<b>{show_nm}</b><br />',
            '{show_date}, {show_year}',
        '</div></tpl>'
    );

	/************* users *************/
	var userStore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/users.php'}),
        baseParams: { method: 'list', user_id: Ext.userId, user_level: Ext.userLevel },
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'user_id'
        },
        [
            {name: 'id', mapping: 'user_id'},
            {name: 'user_name', mapping: 'user_name'},
            {name: 'user_email', mapping: 'user_email'},
            {name: 'user_phone_mobile', mapping: 'user_phone_mobile'},
            {name: 'user_phone_work', mapping: 'user_phone_work'},
            {name: 'team_id', mapping: 'team_id'},
            {name: 'customer_association', mapping: 'customer_association'},
            {name: 'tour_staff', mapping: 'tour_staff'},
            {name: 'demo_staff', mapping: 'demo_staff'},
            {name: 'br', mapping: 'br'}
        ])
    });
	// We only want users loaded who match up w/ the show selected, so wait to load until after the show is selected
    var userTpl = new Ext.XTemplate(
            '<tpl for="."><div class="search-item">',
                '<b>{user_name}</b>{br}',
                '{tour_staff}{br}',
                '{demo_staff}',
            '</div></tpl>'
    );

	/********** demos **********/
	var demoStore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/demo.php'}),
        baseParams: { method: 'list', user_id: Ext.userId, user_level: Ext.userLevel },
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [
            {name: 'id', mapping: 'id'},
            {name: 'show_id', mapping: 'show_id'},
            {name: 'demo_nm', mapping: 'demo_nm'},
            {name: 'demo_id', mapping: 'demo_id'},
            {name: 'demo_desc', mapping: 'demo_desc'},
            {name: 'demo_duration', mapping: 'demo_duration'},
            {name: 'duration', mapping: 'duration'},
            {name: 'br', mapping: 'br'}
        ])
    });

    var demoTpl = new Ext.XTemplate(
	    '<tpl for="."><div class="search-item">',
	        '<b>{demo_nm}</b>{br}',
	        '{demo_desc}{br}',
	        '{duration} {demo_duration}',
	    '</div></tpl>'
    );

    // Create the email form that is populated with the Panel display
    var registeredForm = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 130,
        url: Ext.urlScriptDir + '/application/users.php',
        id: 'registeredFormItems',
        defaultType: 'textfield',
        monitorValid: true,

        reader: new Ext.data.JsonReader({
            root: 'data', // the root of the json array
            totalProperty: 'totalCount',
            id: 'id',
            fields: [
                     {name: 'id', mapping: 'user_id'},
                     {name: 'tour_staff', mapping: 'tour_staff'},
                     {name: 'demo_staff', mapping: 'demo_staff'},
                     {name: 'demo_nm', mapping: 'demo_nm'},
                     {name: 'show_id', mapping: 'show_id'},
                     {name: 'global_demo', mapping: 'global_demo'}
           ]
        }),
        items: [
            new Ext.form.ShowRegisteredComboBox({
                store: storeShowsRegistered,
                id: 'storeShowsRegistered',
                fieldLabel: 'Shows',
                anchor: '96%',
                tpl: showTpl,
                itemSelector: 'div.search-item'
            }),
            new Ext.form.UserRegisteredComboBox({
            	store: userStore,
            	id: 'userRegisteredStore',
            	fieldLabel: 'Registered Users',
            	anchor: '96%',
            	disabled: true,
                tpl: userTpl,
                itemSelector: 'div.search-item',
                tooltipText: "These are users registered for a particular show. To associate an existing user with a show, go to the User menu, Manage, Show Access. To find a user, type the first few letters of his or her last name.",
                listeners: { render: Ext.setFormFieldTooltip }
            }),
        	new Ext.form.Checkbox({
        		fieldLabel: 'Tour Guide?',
        		boxLabel: 'Check if this user is a tour guide',
        		name:'tour_staff',
        		id:'tour_staff'
        	}),
        	new Ext.form.Checkbox({
        		fieldLabel: 'Demonstrator?',
        		boxLabel: 'Check if this user is a demonstrator',
        		name:'demo_staff',
        		id:'demo_staff',
        		listeners: {
	        		check: function(){
	        			var checked = this.getValue();
	        			if(checked == true){
        					this.ownerCt.getForm().findField('global_demo_registered').container.up('div.x-form-item').show();
	        			}
	        			else{
	        				this.ownerCt.getForm().findField('global_demo_registered').container.up('div.x-form-item').hide();
	        				registeredForm.getForm().findField("global_demo_registered").reset();
	        			}
	        		}
	        	}
	       	}),
            {
            	xtype:'statictextfield',
                fieldLabel: 'Suggested Demo',
                name:'demo_nm',
                anchor: '96%',
                fieldClass: 'x-static-text-field',
                rawValue: 'Load a show and select a user to see what demo he or she suggests...'
            },
            {
            	fieldLabel: "Available Demos",
            	xtype: "multiselect",
                name: "global_demo",
                id: "global_demo_registered",
                dataFields: ["id", "demo_nm", "demo_desc"],
                valueField: "id",
                displayField: "demo_nm",
                displayTooltip: "demo_desc",
                width: 250,
                height: 200,
                allowBlank: true,
                disabled: true,

                data:[],

                store: demoStore,

                tbar:[{
                    text:"Clear Selected",
                    handler:function(){
                		registeredForm.getForm().findField("global_demo_registered").reset();
    	            }
                }],
                tooltipText: "To assign demos to a demonstrator, select one or more demos in the list and click Save. You can clear all selections with the Clear Selected Button or deselect demos on at a time by clicking on the highlighted demo(s) you wish to eliminate. If the demo you would like to assign does not appear on the list, please go to the Demo menu, click on Create New/Modify Existing and make sure the demo you are looking for is associated with the show you have selected.",
                listeners: { render: Ext.setFormFieldTooltip }
            },
		    {
		    	xtype: 'hidden',
		    	name:'show_id',
		    	id:'show_id_registered',
		    	value: 0
		    },
            {
            	xtype: 'hidden',
            	name:'demo_id',
            	id:'demo_id_registered',
            	value: 0
            },
		    {
		    	xtype: 'hidden',
		    	name:'registered_id',
		    	id:'registered_id',
		    	value: 0
		    },
            {
            	xtype: 'hidden',
            	name: 'user_name_registered',
            	id:'user_name_registered',
            	value: 0,
            	listeners: {
            		render: function(){
            			// The entire form is rendered, so we can do stuff!
            			this.ownerCt.getForm().findField('global_demo_registered').container.up('div.x-form-item').setVisibilityMode(Ext.Element.DISPLAY);
            			// Hide various fields
            			this.ownerCt.getForm().findField('global_demo_registered').container.up('div.x-form-item').hide();
            			
            			/* wait for the show store to finish loading */
            			storeShowsRegistered.on('load', function(p){
            			    /* select the show */
            				if(Ext.default_show){
            					Ext.selectStore('storeShowsRegistered', 'show_nm', Ext.default_show, Ext.default_show);
            				}
            			});
		    		}
		    	}
            }
        ],

        buttons: [
        {
            text: 'Save',
            type: 'submit',
            formBind:true, // combined with monitorValid above, the submit button will remain disabled until everything is properly validated. -nk
            handler: function(){
        		Ext.saveResourceGlobal('registeredFormItems', 'storeShowsRegistered', 'editRegisteredSB', '/application/users.php', 'save_registered', 'userRegisteredStore');
        	}
        },
        {
            text: 'Reset',
            type: 'reset',
            handler: function(){
                // Clear all the values in the form
                registeredForm.getForm().reset();
                // Set the focus to the FROM field
                Ext.getCmp('storeShowsRegistered').focus();
            }
        }]
    });

    // Using the generic AdminPanel ux (in rpmPanel), we will create a panel to hold our form
    var registeredPanel = new Ext.ux.AdminPanel({
        id:'registeredPanel',
        items: [ registeredForm ],
        tbar: [
            {
                // DELETE
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/delete.png',
                cls: 'x-btn-icon',
                tooltip: '<b>Delete Registration</b><br />Delete current registration from the system.',
                handler: function(){
                    Ext.deleteResourceGlobal('registeredFormItems', 'storeShowsRegistered', 'editRegisteredSB', '/application/users.php', 'delete_registered', 'userRegisteredStore', 'registered_id'); // the field of the id we are deleting
                }
            },
            '-',
            {
                // SAVE
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/save.gif',
                cls: 'x-btn-icon',
                tooltip: '<b>Save Registration</b><br />Save current registration information.',
                handler: function(){
            		Ext.saveResourceGlobal('registeredFormItems', 'storeShowsRegistered', 'editRegisteredSB', '/application/users.php', 'save_registered', 'userRegisteredStore'); // the store we want to reload on a "method: save_as" return from the php file
            	}
            },
            '->',
            {
            	text: 'Manage: '
            },
            {
                // USER GROUPS
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/user_comment.png',
                cls: 'x-btn-icon',
                tooltip: '<b>Registered User Availability</b><br />Manage individual user\'s availability.',
                handler: function(){
            		Ext.show.editRegisteredAvailability(mainPanel);
            	}
            }
        ],
        // Bottom Bar which holds the status bar for updates, etc
        bbar: new Ext.StatusBar({
            id: 'editRegisteredSB',
            defaultText: 'Ready', // The default text when the status is cleared
            defaultIconCls: 'default-icon',
            text: 'Ready', // The default text shown when the SB is first loaded
            iconCls: 'ready-icon'
        })
    });
    // Now that we've created the Panel properly, load the component
    rpmCom.loadComp(registeredPanel, 'Edit Registered Users', mainPanel, 0, 'icon-user');
    // Set focus to the name field
    Ext.getCmp('storeShowsRegistered').focus('', 100);

    if(Ext.isIE){
	    // Resize north panels in various calendars
	    if(Ext.getCmp('fullShowPanel')){
	    	Ext.getCmp('fullShowPanel').setHeight(120);
	    }

	    if(Ext.getCmp('gridViewPanel')){
	    	Ext.getCmp('gridViewPanel').setHeight(120);
	    }

	    if(Ext.getCmp('meetingCalendarViewPanel')){
	    	Ext.getCmp('meetingCalendarViewPanel').setHeight(90);
	    }

	    if(Ext.getCmp('gridViewPanelDemo')){
	    	Ext.getCmp('gridViewPanelDemo').setHeight(40);
	    }

	    if(Ext.getCmp('resourceAvailViewPanel')){
	    	Ext.getCmp('resourceAvailViewPanel').setHeight(70);
	    }

	    if(Ext.getCmp('myViewFormPanel')){
	    	Ext.getCmp('myViewFormPanel').setHeight(50);
	    }

	    if(Ext.getCmp('reportViewPanel')){
	    	Ext.getCmp('reportViewPanel').setHeight(90);
	    }
    }
};

Ext.form.ShowRegisteredComboBox = Ext.extend(Ext.form.ComboBox, {
    typeAhead: false,
    displayField: 'show_nm',
    mode: 'remote',
    triggerAction: 'all',
    loadOnTrigger: true,
    emptyText: 'Select a show from the dropdown or search by typing...',
    selectOnFocus: true,
    minChars: 2,

    // private
    initEvents : function(){
        // Call the parent (make sure this matches the object above!)
		Ext.form.ShowRegisteredComboBox.superclass.initEvents.call(this);

        // Select fires AFTER you click on a comboBox item (the list is collaspsed)
        this.on('select', this.onBookingSelect, this);

    },

    onTriggerClick : function(){
        if(this.disabled){
            return;
        }
        if(this.isExpanded()){
            this.collapse();
            this.el.focus();
        }else {
            this.onFocus({});
            if(this.triggerAction == 'all') {
                this.doQuery(this.allQuery, true);
            } else {
                this.doQuery(this.getRawValue());
            }
            this.el.focus();
            if(this.loadOnTrigger){
                this.store.load({params:{query:this.getRawValue(), user_id: Ext.userId}});
            }
        }

    },

    onBookingSelect: function(record){
        var rowIndex = record.selectedIndex;
        var rowData = record.store.getAt(rowIndex).data;
        var id = rowData.id;

        // Load the resource list based on the show
        Ext.getCmp('userRegisteredStore').store.load({params:{method:'list', show_id:String(id)}});
        Ext.getCmp('userRegisteredStore').enable();

        // Load the demo list based on the show
        Ext.getCmp('global_demo_registered').store.load({params:{method:'list', show_id:String(id)}});
        Ext.getCmp('global_demo_registered').enable();

   		// Manually set the show_id field
   		Ext.getCmp('show_id_registered').setValue(id);

   		if(Ext.userLevel < 2){
			// Wait for the user store to load, then auto populate the rest of the fields
			Ext.getCmp('userRegisteredStore').store.on('load', function(p){
	    		var tourStoreVar = Ext.getCmp('userRegisteredStore');
		    	tourStoreVar.setValue(Ext.userNameLastFirst);
		    	var selectedIndex = tourStoreVar.store.find('user_name', Ext.userNameLastFirst);
		    	tourStoreVar.selectedIndex = selectedIndex;
		    	// Now fire the second select event, which loads the rest of the form
		    	tourStoreVar.fireEvent('select', tourStoreVar, tourStoreVar.store.getAt(selectedIndex), selectedIndex);
	    	}, this, {single: true}); // Don't forget to make these a single run only!
		}
    }
});

Ext.form.UserRegisteredComboBox = Ext.extend(Ext.form.ComboBox, {
	typeAhead: false,
	displayField: 'user_name',
	mode: 'local',
	triggerAction: 'all',
	emptyText: 'Load a show first...',
	selectOnFocus: true,
	minChars: 2,

	// private
	initEvents : function(){
		// Call the parent (make sure this matches the object above!)
		Ext.form.UserRegisteredComboBox.superclass.initEvents.call(this);

		// Select fires AFTER you click on a comboBox item (the list is collaspsed)
		this.on('select', this.onBookingSelect, this);

		this.store.on('load', function(p){
			this.emptyText = 'Select a registered user...';
			this.setValue('Select a registered user...');
		}, this);
	},

	onTriggerClick : function(){
		if(this.disabled){
			return;
		}
		if(this.isExpanded()){
			this.collapse();
			this.el.focus();
		}else {
			this.onFocus({});
			if(this.triggerAction == 'all') {
				this.doQuery(this.allQuery, true);
			} else {
				this.doQuery(this.getRawValue());
			}
			this.el.focus();
			if(this.loadOnTrigger){
				this.store.load({params:{query:this.getRawValue(), user_id: Ext.userId}});
			}
		}

	},

	onBookingSelect: function(record){
		var rowIndex = record.selectedIndex;
		var rowData = record.store.getAt(rowIndex).data;
		var id = rowData.id;
		var user_name = rowData.user_name;
		var loc = Ext.getCmp('registeredFormItems');
		var show_id = Ext.getCmp('show_id_registered').value;

		Ext.getCmp('registered_id').setValue(id);
		Ext.getCmp('user_name_registered').setValue(user_name);

		loc.getForm().load({params:{method:'list_registered', id:String(id), show_id:String(show_id)}}); // queries from php_registered_users

		loc.getForm().on('actioncomplete', function(p){
	        if(rowData.demo_staff != 'Demonstrator: No'){
        		loc.getForm().findField('global_demo_registered').container.up('div.x-form-item').show();
	        }
	        else{
	        	loc.getForm().findField('global_demo_registered').container.up('div.x-form-item').hide();
	        }
	    }, this);
	}
});