Ext.booking.customerRestriction = function(mainPanel){

	/************* Show list store *************/
	var showStoreBooking = 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
    showStoreBooking.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>'
    );  	
	
	/********** booking restriction for shows **********/
	var bookingStore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/booking.php'}),
        baseParams: { method: 'list', user_id: Ext.userId, user_level: Ext.userLevel },
        id: 'bookingStoreLoad',
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'booking_id'
        },
        [
            {name: 'id', mapping: 'booking_id'},
            {name: 'show_id', mapping: 'show_id'},
            {name: 'cust_id', mapping: 'cust_id'},
            {name: 'cust_name', mapping: 'cust_name'},
            {name: 'customer_num', mapping: 'customer_num'},
            {name: 'customer_booked', mapping: 'customer_booked'}
        ])
    });
    // Do NOT preload the booking store, as we will query it later using the show_id
	
    var bookingTpl = new Ext.XTemplate(
            '<tpl for="."><div class="search-item">',
                '<b>{cust_name}</b><br />',
                'Tours Booked: {customer_booked} / {customer_num}',
            '</div></tpl>'
        );

	/********** global customers available **********/
	var customerStore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/users.php'}),
        baseParams: { method: 'customer_association', user_id: Ext.userId, user_level: Ext.userLevel },
        reader: new Ext.data.JsonReader({
            root: 'data', 
            totalProperty: 'totalCount', 
            id: 'cust_id'
        },
        [
            {name: 'cust_id', mapping: 'cust_id'},
            {name: 'cust_name', mapping: 'cust_name'}
        ])
    });
    // Preload the resources combobox list
	customerStore.load();    
    
    // Create the email form that is populated with the Panel display
    var bookingForm = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 130,
        url: Ext.urlScriptDir + '/application/booking.php',
        id: 'bookingFormItems',
        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: 'booking_id'},
                     {name: 'show_id', mapping: 'show_id'},
                     {name: 'cust_id', mapping: 'cust_id'},
                     {name: 'cust_name', mapping: 'cust_name'},
                     {name: 'customer_num', mapping: 'customer_num'},
                     {name: 'customer_booked', mapping: 'customer_booked'},
                     {name: 'global_customers', mapping: 'global_customers'}
           ]
        }),
        items: [
            new Ext.form.ShowBookingComboBox({
                store: showStoreBooking,
                id: 'showStoreBooking',
                fieldLabel: 'Shows',
                anchor: '96%',
                tpl: showTpl,
                itemSelector: 'div.search-item'
            }),
            new Ext.form.BookingComboBox({
            	store: bookingStore,
            	id: 'bookingStore',
            	fieldLabel: 'Assigned Restrictions',
            	anchor: '96%',
            	tpl: bookingTpl,
            	itemSelector: 'div.search-item',
            	disabled: true,
           		tooltipText: "Displays a list of customers who have been restricted to a specific number of tours for the show and how many tours they have booked to date.",
           		listeners: { render: Ext.setFormFieldTooltip }
            }),
            {
                fieldLabel: 'Booking Restriction #',
                name:'customer_num',
                id:'bookingName', // named this for redirect purposes
                width:100,
                value:'0',
                tooltipText: "The number of tours per show which can be booked by this customer.",
                listeners: { render: Ext.setFormFieldTooltip }                 
            },
        	new Ext.form.Checkbox({
        		fieldLabel: 'Remove Restriction?',
        		boxLabel: 'Check this box to remove all booking restrictions from the selected customers.',
        		name:'remove_restriction',
        		id: 'remove_restriction'
        	}),        	
            {
            	fieldLabel: "Select/Edit Customers",
            	xtype: "multiselect",
                name: "global_customers",
                id: "global_customers",
                dataFields: ["cust_id", "cust_name"], 
                valueField: "cust_id",
                displayField: "cust_name",
                width: 250,
                height: 200,
                allowBlank: true,
                
                data:[],
                
                store: customerStore,
                
                tbar:[{
                    text:"Clear Selected",
                    handler:function(){
                		bookingForm.getForm().findField("global_customers").reset();
    	            }
                }],
           		tooltipText: "To select customers, please click on the customers you wish to restrict with the same number of tours, then click Save. You can select restrictions one at a time by choosing them from the Assigned Restrictions list, chcking the Remove Restriction box, and clicking Save. If the customer you would like to restrict does not appear on the list, please click on the Manage: Customer List icon in the top right corner of this tab.",
           		listeners: { render: Ext.setFormFieldTooltip }
            },            
		    {
		    	xtype: 'hidden',
		    	name:'show_id',
		    	id:'show_id',
		    	value: 0
		    },
            {
            	xtype: 'hidden',
            	name:'booking_id',
            	id:'booking_id',
            	value: 0,
            	listeners: {
            		render: function(){
		    			/* wait for the show store to finish loading */
            			showStoreBooking.on('load', function(p){
            			    /* select the show */
            				if(Ext.default_show){
            					Ext.selectStore('showStoreBooking', '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('bookingFormItems', 'bookingName', 'editBookingSB', '/application/booking.php', 'save', 'bookingStore');
        	}
        },
        {
            text: 'Reset',
            type: 'reset',
            handler: function(){
                // Clear all the values in the form
                bookingForm.getForm().reset();
                // Set the focus to the FROM field
                Ext.getCmp('bookingName').focus();
            }
        }]
    });

    // Using the generic AdminPanel ux (in rpmPanel), we will create a panel to hold our form
    var bookingPanel = new Ext.ux.AdminPanel({
        id:'bookingPanel',
        items: [ bookingForm ],
        tbar: [
            {
                // ADD
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/add.png',
                cls: 'x-btn-icon',
                tooltip: '<b>New Restriction</b><br />Clear the form and create a new restriction.',
                handler: function(){
                    Ext.newResourceGlobal('bookingFormItems', 'bookingName', 'editBookingSB', '/application/booking.php', 'save', 'bookingStore');
                }
            },
            {
                // DELETE
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/delete.png',
                cls: 'x-btn-icon',
                tooltip: '<b>Delete Restriction</b><br />Delete current restriction from the system.',
                handler: function(){
                    Ext.deleteResourceGlobal('bookingFormItems', 'bookingName', 'editBookingSB', '/application/booking.php', 'delete', 'bookingStore', 'booking_id'); // the field of the id we are deleting
                }
            },
            '-',
            {
                // SAVE
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/save.gif',
                cls: 'x-btn-icon',
                tooltip: '<b>Save Restriction</b><br />Save current restriction information.',
                handler: function(){
            		Ext.saveResourceGlobal('bookingFormItems', 'bookingName', 'editBookingSB', '/application/booking.php', 'save', 'bookingStore'); // the store we want to reload on a "method: save_as" return from the php file
        			// Make sure the 'remove restriction' checkbox is unchecked
        			Ext.getCmp('remove_restriction').setValue(false);            		
            	}
            },
            '->',
            {
            	text: 'Manage: '
            },
            {
                // USER GROUPS
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/group_link.png',
                cls: 'x-btn-icon',
                tooltip: '<b>Customer List</b><br />Manage the entire customer list.',
                handler: function(){
            		Ext.customer.editGlobalCustomers(mainPanel);
            	}
            }        
        ],
        // Bottom Bar which holds the status bar for updates, etc
        bbar: new Ext.StatusBar({
            id: 'editBookingSB',
            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(bookingPanel, 'Booking Restrictions', mainPanel, 0, 'icon-exclamation');
    // Set focus to the name field
    Ext.getCmp('bookingName').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.ShowBookingComboBox = Ext.extend(Ext.form.ComboBox, {
    typeAhead: false,
    displayField: 'show_nm',
    mode: 'remote',
    triggerAction: 'all',
    loadOnTrigger: true,
    emptyText: 'Select a show from the dropdown to edit, or search by typing...',
    selectOnFocus: true,
    minChars: 2,

    id: 'show-booking-combo',

    // private
    initEvents : function(){
        // Call the parent (make sure this matches the object above!)
		Ext.form.ShowBookingComboBox.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('bookingStore').store.load({params:{method:'list', show_id:""+id+""}});
        Ext.getCmp('bookingStore').enable();
        
   		// Manually set the show_id field
   		Ext.getCmp('show_id').setValue(id);
    }
});

Ext.form.BookingComboBox = Ext.extend(Ext.form.ComboBox, {
	typeAhead: false,
	displayField: 'cust_name',
	mode: 'local',
	triggerAction: 'all',
	emptyText: 'Load a show first...',
	selectOnFocus: true,
	minChars: 2,
	
	id: 'customer-booking-combo',
	
	// private
	initEvents : function(){
		// Call the parent (make sure this matches the object above!)
		Ext.form.BookingComboBox.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 booking restriction...';
			this.setValue('Select a booking restriction...');
		}, 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){
		Ext.getCmp('editBookingSB').setStatus({iconCls: 'x-status-cog', clear: true, text: 'Loading selected resource...'});
		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('bookingFormItems');
		
		loc.getForm().load({params:{method:'list', id:""+id+""}});
		
		loc.getForm().on('actioncomplete', function(p){
			Ext.getCmp('editBookingSB').setStatus({iconCls: 'x-status-accept', clear: true, text: 'Resource loaded'});
			// Manually set the id field so we can recall it later
			Ext.getCmp('booking_id').setValue(id);
			Ext.getCmp('show_id').setValue(show_id);
			// Make sure the 'remove restriction' checkbox is unchecked
			Ext.getCmp('remove_restriction').setValue(false);
		}, this);
	}
});