Ext.customer.editGlobalCustomers = function(mainPanel){

	/************* Customer store *************/
	var customerStore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/customer.php'}),
        baseParams: { method: 'list', user_id: Ext.userId, user_level: Ext.userLevel },
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'cust_id'
        },
        [
            {name: 'id', mapping: 'cust_id'},
            {name: 'cust_name', mapping: 'cust_name'}
        ])
    });
    // Preload the combobox list
    customerStore.load({params:{query:'', user_id: Ext.userId, user_level: Ext.userLevel }});
	
    // Create the form which we then put inside the panel
    var customerForm = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 130,
        url: Ext.urlScriptDir + '/application/customer.php',
        id: 'customerFormItems',
        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: 'cust_id'},
                     {name: 'cust_name', mapping: 'cust_name'}
           ]
        }),
        items: [
            new Ext.form.CustomerComboBox({
                store: customerStore,
                id: 'customerStore',
                fieldLabel: 'Customers',
                anchor: '96%',
           		tooltipText: "To find your customer, either start typing the first few characters of the customer\'sname or use the dropdown menu to search alphabetically.",
           		listeners: { render: Ext.setFormFieldTooltip }
            }),
            {
                fieldLabel: 'Customer Name',
                name:'cust_name',
                id: 'customerName',
                anchor: '96%',
           		tooltipText: "You can change the name of a customer you created here, or add new customers by typing them in and clicking Save. If you have previously loaded a customer, you must click the Reset or New button in order to clear out the form to add a new customer.",
           		listeners: { render: Ext.setFormFieldTooltip }
            },
            {
                xtype: 'hidden',
                name:'id',
                id:'cust_id',
                value: 0
            }
        ],

        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('customerFormItems', 'customerName', 'editCustomerSB', '/application/customer.php', 'save', 'customerStore');
        	}
        },
        {
            text: 'Reset',
            type: 'reset',
            handler: function(){
                // Clear all the values in the form
                customerForm.getForm().reset();
                // Set the focus to the FROM field
                Ext.getCmp('customerName').focus();
            }
        }]
    });

    // Using the generic AdminPanel ux (in rpmPanel), we will create a panel to hold our form
    var customerPanel = new Ext.ux.AdminPanel({
        id:'customerPanel',
        items: [ customerForm ],
        tbar: [
            {
                // ADD
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/add.png',
                cls: 'x-btn-icon',
                tooltip: '<b>New Customer</b><br />Clear the form and create a new customer.',
                handler: function(){
                    Ext.newResourceGlobal('customerFormItems', 'customerName', 'editCustomerSB', '/application/customer.php', 'save', 'customerStore');
                }
            },
            {
                // DELETE
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/delete.png',
                cls: 'x-btn-icon',
                tooltip: '<b>Delete Customer</b><br />Delete current customer from the system.',
                handler: function(){
                    Ext.deleteResourceGlobal('customerFormItems', 'customerName', 'editCustomerSB', '/application/customer.php', 'delete', 'customerStore', 'cust_id'); // the field of the id we are deleting
                }
            },
            '-',
            {
                // SAVE
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/save.gif',
                cls: 'x-btn-icon',
                tooltip: '<b>Save Customer</b><br />Save current customer information.',
                handler: function(){
            		Ext.saveResourceGlobal('customerFormItems', 'customerName', 'editCustomerSB', '/application/customer.php', 'save', 'customerStore'); // the store we want to reload on a "method: save_as" return from the php file
            	}
            },
            '->',
            {
            	text: 'Manage: '
            },
            {
                // USER GROUPS
            	id: 'userUserGroupButton',
                icon: Ext.urlScriptDir + Ext.urlIconDir + '/group_edit.png',
                cls: 'x-btn-icon',
                tooltip: '<b>User Groups</b><br />Manage the available user groups.',
                handler: function(){
            		var tab = mainPanel.getComponent('docs-Edit User Groups');
            		if(tab){
            			mainPanel.setActiveTab(tab);
            		}
            		else{
            			Ext.user.editUserGroups(mainPanel);
            		}
            	}
            },            
            {
            	// SHOW ACCESS
            	id: 'userShowAccessButton',
            	icon: Ext.urlScriptDir + Ext.urlIconDir + '/shield.png',
            	cls: 'x-btn-icon',
            	tooltip: '<b>User Show Access</b><br />Manage the user\'s show access.',
            	handler: function(){
        			var tab = mainPanel.getComponent('docs-User Show Access');
        			if(tab){
        				mainPanel.setActiveTab(tab);
        			}
        			else{             	
        				Ext.user.editUserAccess(mainPanel);
        			}
            	}
            }          
        ],
        // Bottom Bar which holds the status bar for updates, etc
        bbar: new Ext.StatusBar({
            id: 'editCustomerSB',
            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(customerPanel, 'Edit Customers', mainPanel, 0, 'icon-group-link');
    // Set focus to the name field
    Ext.getCmp('customerName').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.CustomerComboBox = Ext.extend(Ext.form.ComboBox, {
    typeAhead: false,
    displayField: 'cust_name',
    mode: 'local',
    triggerAction: 'all',
    emptyText: 'Loading...',
    selectOnFocus: true,
    minChars: 2,

    id: 'show-customer-combo',

    // private
    initEvents : function(){
        // Call the parent (make sure this matches the object above!)
		Ext.form.CustomerComboBox.superclass.initEvents.call(this);

        // Select fires AFTER you click on a comboBox item (the list is collaspsed)
        this.on('select', this.onComboSelect, this);

        this.store.on('load', function(p){
            this.emptyText = 'Select a customer...';
            this.setValue('Select a customer...');
        }, 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}});
            }
        }

    },

    onComboSelect: function(record){
        var rowIndex = record.selectedIndex;
        var rowData = record.store.getAt(rowIndex).data;
        var id = rowData.id;
        
		var loc = Ext.getCmp('customerFormItems');
		
		loc.getForm().load({params:{method:'list', id:""+id+""}});        
		loc.getForm().on('actioncomplete', function(p){
			Ext.getCmp('cust_id').setValue(id);
		}, this);          
   		
    }
});