Ext.resource.editDemo = function(mainPanel){

	/************* Show list store *************/
	var showDemoStore = 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 showGroup combobox list
    showDemoStore.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>'
    );

	/********** 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 },
        id: 'demoStore',
        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_desc', mapping: 'demo_desc'},
            {name: 'demo_duration', mapping: 'demo_duration'},
            {name: 'demo_location', mapping: 'demo_location'},
            {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 simple demo location store **/
	var demoLocationStore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/resources.php'}),
        baseParams: { method: 'tourable', user_id: Ext.userId, user_level: Ext.userLevel },
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'resource_id'
        },
        [
            {name: 'resource_id', mapping: 'resource_id'},
            {name: 'resource_nm', mapping: 'resource_nm'}
        ])
    });

    // Create the email form that is populated with the Panel display
    var demoForm = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 130,
        url: Ext.urlScriptDir + '/application/demo.php',
        id: 'demoFormItems',
        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: 'id'},
                     {name: 'show_id', mapping: 'show_id'},
                     {name: 'demo_nm', mapping: 'demo_nm'},
                     {name: 'demo_desc', mapping: 'demo_desc'},
                     {name: 'demo_location', mapping: 'demo_location'},
                     {name: 'demo_location_name', mapping: 'demo_location_name'},
                     {name: 'demo_duration', mapping: 'demo_duration'},
                     {name: 'global_shows', mapping: 'global_shows'}
           ]
        }),
        items: [
            new Ext.form.ShowDemoComboBox({
                store: showDemoStore,
                id: 'showDemoStore',
                fieldLabel: 'Shows',
                anchor: '96%',
                tpl: showTpl,
                itemSelector: 'div.search-item',
                tooltipText: "Select the show you wish to copy the demo from if it already exists, or select the show for which you would like to create a new demo.",
                listeners: { render: Ext.setFormFieldTooltip }
            }),
            new Ext.form.DemoComboBox({
            	store: demoStore,
            	id: 'demoStore',
            	fieldLabel: 'Assigned Demos',
            	anchor: '96%',
            	disabled: true,
            	tpl: demoTpl,
            	itemSelector: 'div.search-item'
            }),
            {
                fieldLabel: 'Demo Name*',
                id: 'demoName',
                name:'demo_nm',
                anchor: '96%',
           		tooltipText: "Please give your demo a generic name in case you want to reuse it for another show. In the title please include the duration to make it easier for sales teams to book tours. For example: <b>LTE-CDMA (15 mins)</b>",
           		listeners: { render: Ext.setFormFieldTooltip }
            },
	        {
	            xtype: 'textarea',
	            fieldLabel: 'Demo Description*',
	            name: 'demo_desc',
	            anchor: '96%',
	            grow: true,
                tooltipText: "Enter a detailed description of this demo. This will be searchable by staff directing customers and will be read by the sales teams booking tours, so please include relevant keywords and make the description complete.",
                listeners: { render: Ext.setFormFieldTooltip },
            	allowBlank: false
	        },
            {
                fieldLabel: 'Duration (mins)*',
                id: 'demo_duration',
                name:'demo_duration',
                width: 50,
                maxLength: 2,
                allowBlank:false,
                maxLengthText:'Please enter a number between 5 and 60',
                validator: validateRange,
                tooltipText: "Please enter a number between 5 and 60. This number represents the duration, in minutes, of the demo.",
                listeners: { render: Ext.setFormFieldTooltip }
            },
            new Ext.form.DemoLocationComboBox({
            	store: demoLocationStore,
            	id: 'demoLocationStore',
            	name: 'demo_location',
            	fieldLabel: 'Tourable Locations*',
            	width: 250,
            	disabled: true,
            	allowBlank: false,
                tooltipText: "Select the location of this demo. Defaults to Booth Tour.",
                listeners: { render: Ext.setFormFieldTooltip }
            }),
            {
            	fieldLabel: "Select/Edit Shows",
            	xtype: "multiselect",
                name: "global_shows",
                id: "global_shows_demo",
                dataFields: ["id", "show_nm"],
                valueField: "id",
                displayField: "show_nm",
                width: 250,
                height: 200,
                allowBlank: true,

                data:[],

                store: showDemoStore,

                tbar:[{
                    text:"Clear Selected",
                    handler:function(){
                		demoForm.getForm().findField("global_shows_demo").reset();
    	            }
                }],
           		tooltipText: "Here you can copy demos from one show to another. The show selected in the Shows drop-down menu at the top is the show this demo will be associated with when you click Save. If you want to associate this demo with another show, highlight that show in this list and it will be copied to the new show. If you wish to copy your demo to multiple shows, please highlight all relevant shows in this list and click Save. To remove a demo from the show you must use the red Delete Demo button in the top left corner of this page.",
           		listeners: { render: Ext.setFormFieldTooltip }
            },
            {
                xtype: 'hidden',
                name:'id',
                id:'demo_id',
                value: 0
            },
            {
            	xtype: 'hidden',
            	name:'demo_location_name',
            	id:'demo_location_name',
            	value: 0
            },
            {
            	xtype: 'hidden',
            	name:'show_id',
            	id:'show_id_demo',
            	value: 0,
            	listeners: {
            		render: function(){
		    			/* wait for the show store to finish loading */
            			showDemoStore.on('load', function(p){
            			    /* select the show */
            				if(Ext.default_show){
            					Ext.selectStore('showDemoStore', '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('demoFormItems', 'demoName', 'editDemoSB', '/application/demo.php', 'save', 'demoStore');
        	}
        },
        {
            text: 'Save As New',
            type: 'submit',
            formBind:true, // combined with monitorValid above, the submit button will remain disabled until everything is properly validated. -nk
            handler: function(){
        		Ext.saveResourceGlobal('demoFormItems', 'demoName', 'editDemoSB', '/application/demo.php', 'save_as', 'demoStore');
        	}
        },
        {
            text: 'Reset',
            type: 'reset',
            handler: function(){
                // Clear all the values in the form
                demoForm.getForm().reset();
                // Set the focus to the FROM field
                Ext.getCmp('demoName').focus();
            }
        }]
    });

    // Using the generic AdminPanel ux (in rpmPanel), we will create a panel to hold our form
    var demoPanel = new Ext.ux.AdminPanel({
        id:'demoPanel',
        items: [ demoForm ],
        tbar: [
            {
                // ADD
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/add.png',
                cls: 'x-btn-icon',
                tooltip: '<b>New Demo</b><br />Clear the form and create a new demo.',
                handler: function(){
                    Ext.newResourceGlobal('demoFormItems', 'demoName', 'editDemoSB', '/application/demo.php', 'save', 'demoStore');
                }
            },
            {
                // DELETE
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/delete.png',
                cls: 'x-btn-icon',
                tooltip: '<b>Delete Demo</b><br />Delete current demo from the show selected in the Shows drop-down menu.',
                handler: function(){
                    Ext.deleteResourceGlobal('demoFormItems', 'demoName', 'editDemoSB', '/application/demo.php', 'delete', 'demoStore', 'demo_id'); // the field of the id we are deleting
                }
            },
            '-',
            {
                // SAVE
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/save.gif',
                cls: 'x-btn-icon',
                tooltip: '<b>Save Demo</b><br />Saves current demo information to the show selected in the Shows drop-down menu.',
                handler: function(){
            		Ext.saveResourceGlobal('demoFormItems', 'demoName', 'editDemoSB', '/application/demo.php', 'save', 'demoStore'); // the store we want to reload on a "method: save_as" return from the php file
            	}
            },
            '->',
            {
            	text: 'Manage: '
            },
            {
                // MANAGE (quick links)
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/server_go.png',
                cls: 'x-btn-icon',
                tooltip: '<b>Demo Staff Assignment</b><br />Manage the demo staff\'s assignments.',
                handler: function(){
            		Ext.resource.demoAssignRemove(mainPanel);
            	}
            }
        ],
        // Bottom Bar which holds the status bar for updates, etc
        bbar: new Ext.StatusBar({
            id: 'editDemoSB',
            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(demoPanel, 'Edit Demos', mainPanel, 0, 'icon-server');
    // Set focus to the name field
    Ext.getCmp('demoName').focus('', 100);

    if(Ext.isIE){
    	Ext.resizePanelIE();
    }
};

Ext.form.ShowDemoComboBox = 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.ShowDemoComboBox.superclass.initEvents.call(this);

        // Select fires AFTER you click on a comboBox item (the list is collaspsed)
        this.on('select', this.onDemoSelect, 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, c:'1'}});
            }
        }

    },

    onDemoSelect: function(record){
        var rowIndex = record.selectedIndex;
        var rowData = record.store.getAt(rowIndex).data;
        var id = rowData.id;

        // Clear all the values in the form
        Ext.getCmp('demoFormItems').getForm().reset();
        // Set the focus to the FROM field
        Ext.getCmp('demoName').focus();
        // Make sure the shows combobox doesn't reset
        this.setValue(rowData.show_nm);
        // Load the demo list based on the show
        Ext.getCmp('demoStore').store.load({params:{method:'list', show_id:""+id+""}});
        Ext.getCmp('demoStore').enable();
        // Load the locations
        Ext.getCmp('demoLocationStore').store.load({params:{method:'tourable', show_id:""+id+""}});
        Ext.getCmp('demoLocationStore').enable();

   		// Manually set the show_id field
   		Ext.getCmp('show_id_demo').setValue(id);
    }
});

Ext.form.DemoComboBox = Ext.extend(Ext.form.ComboBox, {
	typeAhead: false,
	displayField: 'demo_nm',
	mode: 'remote',
	triggerAction: 'all',
	loadOnTrigger: true,
	emptyText: 'Load a show, then search for a demo...',
	selectOnFocus: true,
	minChars: 2,

	// private
	initEvents : function(){
		// Call the parent (make sure this matches the object above!)
		Ext.form.DemoComboBox.superclass.initEvents.call(this);

		// Select fires AFTER you click on a comboBox item (the list is collaspsed)
		this.on('select', this.onResourceAvailSelect, this);

		this.store.on('load', function(p){
			Ext.getCmp('editDemoSB').setStatus({iconCls: 'x-status-accept', clear: true, text: 'Select a demo from the dropdown or type in the text box to search'});
		}, 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){
				var show_id = Ext.getCmp('show_id_demo').value;
				this.store.load({params:{query:this.getRawValue(), user_id: Ext.userId, a:'1', show_id: String(show_id)}});
			}
		}

	},

	onResourceAvailSelect: function(record){
		Ext.getCmp('editDemoSB').setStatus({iconCls: 'x-status-cog', clear: true, text: 'Loading selected demo...'});
		var rowIndex = record.selectedIndex;
		var rowData = record.store.getAt(rowIndex).data;
		var id = rowData.id;
		var show_id = rowData.show_id;

		var loc = Ext.getCmp('demoFormItems');

		if(id == 0) { id = -1; }
		loc.getForm().load({params:{method:'list', id:""+id+""}});
		loc.getForm().on('actioncomplete', function(p){
			// Manually set the id field so we can recall it later
			Ext.getCmp('demo_id').setValue(id);
			Ext.getCmp('show_id_demo').setValue(show_id);
			
			/* try to select the demo_location store */
	   		Ext.selectStore('demoLocationStore', 'resource_nm', rowData.demo_location, rowData.demo_location, true);
			
		}, this);
	}
});

Ext.form.DemoLocationComboBox = Ext.extend(Ext.form.ComboBox, {
	typeAhead: false,
	displayField: 'resource_nm',
	mode: 'local',
	triggerAction: 'all',
	emptyText: 'Loading...',
	selectOnFocus: true,
	minChars: 2,

	// private
	initEvents : function(){
		// Call the parent (make sure this matches the object above!)
		Ext.form.DemoComboBox.superclass.initEvents.call(this);

		this.on('select', this.onResourceAvailSelect, this);

		this.store.on('load', function(p){
	        this.emptyText = 'Select a location...';
	        this.setValue('Select a location...');
		}, 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){
				var show_id = Ext.getCmp('show_id_demo').value;
				this.store.load({params:{query:this.getRawValue(), user_id: Ext.userId, b:'1', show_id: String(show_id)}});
			}
		}
	},
	onResourceAvailSelect: function(record){
		var rowIndex = record.selectedIndex;
		var rowData = record.store.getAt(rowIndex).data;
		Ext.getCmp('demo_location_name').setValue(rowData.resource_nm);
	}
});