Ext.Report = function(mainPanel){

	var tab = mainPanel.getComponent('docs-Reports');
	if(tab){
		mainPanel.setActiveTab(tab);
	}
		else{	
	
		/************* Show list store *************/
		var storeShowsReport = 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', mapping: 'show_date'},
	            {name: 'show_year', mapping: 'show_year'},
	            {name: 'full_date', mapping: 'full_date'}
	
	        ])
	    });
		storeShowsReport.load({params:{query:'', user_id: Ext.userId, user_level: Ext.userLevel }});
	
		var resourceCalendarStoreDaily = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/shows.php'}),
			baseParams: { method: 'list_daily', 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', mapping: 'show_date'},
			 {name: 'show_year', mapping: 'show_year'},
			 {name: 'full_date', mapping: 'full_date'},
			 {name: 'comma', mapping: 'comma'}
	
			 ])
		});
	
	    // 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}{comma} {show_year}',
	        '</div></tpl>'
	    );
	
		/************* Customer store *************/
		var customerStore = new Ext.data.Store({
	        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/customer.php'}),
	        baseParams: { method: 'list_all', 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 }});
	
	    var reportAvailFormView = new Ext.form.FormPanel({
	        baseCls: 'x-plain',
	        labelWidth: 130,
	        defaultType: 'textfield',
	
	        items: [
	   			new Ext.form.ReportCalendarComboBox({
					fieldLabel: 'Select a Show',
				    store: storeShowsReport,
				    id: 'storeShowsReport',
				    width: 400,
				    tpl: showTpl,
				    itemSelector: 'div.search-item'
				}),
	            new Ext.form.ComboBox({
	            	id: 'report_grid_view_customer_list',
	            	fieldLabel: 'Customers',
	                width: 400,
	                store: customerStore,
	                displayField:'cust_name',
	                mode: 'local',
	                triggerAction: 'all',
	                emptyText:'Limit results to a specific customer...',
	                selectOnFocus:true,
	            	listeners: {
	            		select: function(){
	                		var rowIndex = this.selectedIndex;
	                		var rowData = this.store.getAt(rowIndex).data;
	                		Ext.getCmp('report_grid_view_cust_id').setValue(rowData.id);
	
	                		// Enable the Excel button
	                		Ext.getCmp('report-excel-button').enable();
	
	                		// Load the grid
	                		var show_id, show_date, cust_id;
	        		        show_id = Ext.getCmp('report_grid_view_show_id').value;
	        		        show_date = Ext.getCmp('report_grid_view_show_date').value;
	        		        cust_id = Ext.getCmp('report_grid_view_cust_id').value;
	        		        Ext.getCmp('storeViewReport').store.load({params:{method:'generate', show_date:String(show_date), show_id:String(show_id), cust_id:String(cust_id)}});
	            		}
	            	}
	            }),
	            {
	            	xtype: 'hidden',
	            	name:'report_grid_view_show_id',
	            	id:'report_grid_view_show_id',
	            	value: 0
	            },
	            {
	            	xtype: 'hidden',
	            	name:'report_grid_view_show_date',
	            	id:'report_grid_view_show_date',
	            	value: 0
	            },
	            {
	            	xtype: 'hidden',
	            	name:'report_grid_view_cust_id',
	            	id:'report_grid_view_cust_id',
	            	value: 0,
	            	listeners: {
	            		render: function(){
			    			/* wait for the show store to finish loading */
	            			storeShowsReport.on('load', function(p){
	            			    /* select the show */
	            				if(Ext.default_show){
	            					Ext.selectStore('storeShowsReport', 'show_nm', Ext.default_show, Ext.default_show);
	            				}
	            			});
			    		}
			    	}
	            }
	        ]
	    });
	
	    // Using the generic AdminPanel ux (in a_start.js), we will create a panel to hold our data
	    var reportViewPanel = new Ext.ux.AdminPanel({
	    	region:'north',
	        id:'reportViewPanel',
	        height: 70,
	        minSize: 50,
	        maxSize: 100,
	        collapsible: true,
	        collapseMode: 'mini',
	
	        items: [ reportAvailFormView ]
	    });
	
	      // Create the Data Store
	      var storeReport = new Ext.data.JsonStore({
				root: 'data',
				totalProperty: 'totalCount',
				idProperty: 'id',
				remoteSort: true,
	
				fields: [
				   'id',
				   'cust_nm',
				   'resource_nm',
				   'attendee1_nm',
				   'attendee1_cd',
				   'attendee2_nm',
				   'attendee2_cd',
				   'attendee3_nm',
				   'attendee3_cd',
				   'attendee4_nm',
				   'attendee4_cd',
				   'attendee5_nm',
				   'attendee5_cd',
				   'attendee6_nm',
				   'attendee6_cd',
				   'show_id',
				   'show_nm',
				   'tour_dt',
				   'tour_st',
				   'tour_en',
				   'tour_manager_email',
				   'add_custs',
				   'cust_type',
				   'cust_language',
				   'value',
				   'num',
				   'demos',
				   'topics',
				   'execs',
				   'comments',
				   'tour_nm',
				   'bookedby_nm'
				],
	
				proxy: new Ext.data.HttpProxy({
				  url: Ext.urlScriptDir + '/application/report.php'
				}),
				baseParams: { method: 'customer_metrics', user_id: Ext.userId, user_level: Ext.userLevel },
				listeners:{
	    			beforeload: function()
					{
						var onload = Ext.getCmp('storeViewReport');
						if (onload)
							onload.getEl().mask('Loading...', 'x-mask-loading');
					},
					load: function()
					{
						var onload = Ext.getCmp('storeViewReport');
						if (onload)
							onload.getEl().unmask();
					},
					loadexception: function()
					{
						var onload = Ext.getCmp('storeViewReport');
						if (onload)
							onload.getEl().unmask();
					}
	    		}
	      });
	      storeReport.setDefaultSort('cust_nm', 'asc');
	
	      // Create the Grid
	      var gridReport = new Ext.grid.GridPanel({
	    	  title: 'Customer Metrics',
	    	  id: 'storeViewReport',
	    	  region:'center',
	
	    	  store: storeReport,
	          // Grid columns
	          columns:[
	              {
	            	  header: "Customer",
	            	  dataIndex: 'cust_nm',
	            	  width: 100,
	            	  sortable: false
	              },
	              
		          { header: "Resource", dataIndex: 'resource_nm', width: 100, sortable: false },
		          { header: "Show", dataIndex: 'show_nm', width: 100, sortable: false },
		          { header: "Date", dataIndex: 'tour_dt', width: 80, sortable: false },
		          { header: "Start Time", dataIndex: 'tour_st', width: 80, sortable: false },
		          { header: "End Time", dataIndex: 'tour_en', width: 80, sortable: false },
		          { header: "Add. Customers", dataIndex: 'add_custs', width: 100, sortable: false },
		          { header: "Acct Manager", dataIndex: 'tour_manager_email', width: 150, sortable: false },
		          { header: "Customer Type", dataIndex: 'cust_type', width: 100, sortable: false },
		          { header: "Language", dataIndex: 'cust_language', width: 80, sortable: false },
		          { header: "Topic", dataIndex: 'topics', width: 100, sortable: false },
		          { header: "Demos Req.", dataIndex: 'demos', width: 100, sortable: false },
		          { header: "Pot. Value", dataIndex: 'value', width: 100, sortable: false },
		          { header: "Num Attending", dataIndex: 'num', width: 100, sortable: false },
		          { header: "Attendee 1", dataIndex: 'attendee1_nm', width: 75, sortable: false },
		          { header: "Role 1", dataIndex: 'attendee1_cd', width: 50, sortable: false },
		          { header: "Attendee 2", dataIndex: 'attendee2_nm', width: 75, sortable: false },
		          { header: "Role 2", dataIndex: 'attendee2_cd', width: 50, sortable: false },
		          { header: "Attendee 3", dataIndex: 'attendee3_nm', width: 75, sortable: false },
		          { header: "Role 3", dataIndex: 'attendee3_cd', width: 50, sortable: false },
		          { header: "Attendee 4", dataIndex: 'attendee4_nm', width: 75, sortable: false },
		          { header: "Role 4", dataIndex: 'attendee4_cd', width: 50, sortable: false },
		          { header: "Attendee 5", dataIndex: 'attendee5_nm', width: 75, sortable: false },
		          { header: "Role 5", dataIndex: 'attendee5_cd', width: 50, sortable: false },
		          { header: "Attendee 6", dataIndex: 'attendee6_nm', width: 75, sortable: false },
		          { header: "Role 6", dataIndex: 'attendee6_cd', width: 50, sortable: false },
		          { header: "Executives", dataIndex: 'execs', width: 100, sortable: false },
		          { header: "Comments", dataIndex: 'comments', width: 150, sortable: false },
		          { header: "Tour Guide", dataIndex: 'tour_nm', width: 100, sortable: false },
		          { header: "Booked By", dataIndex: 'bookedby_nm', width: 100, sortable: false }
	          ],
	
	    	  stripeRows: true,
	    	  autoscroll: true,
	          trackMouseOver:false,
	          disableSelection:true,
	          loadMask: false,
	          bbar: new Ext.Toolbar({
	        	  buttons: [{
					  id: 'report-excel-button',
					  iconCls:'icon-page-excel',
					  disabled: true,
					  text: 'Export to Excel...',
					  handler: function(){
	        		  	  /* define variables */
		      		      var show_id, show_date, cust_id;
	  		        
		      		      /* assign variables */
		      		  	  show_id = Ext.getCmp('report_grid_view_show_id').value;
		      		  	  show_date = Ext.getCmp('report_grid_view_show_date').value;
		      		  	  cust_id = Ext.getCmp('report_grid_view_cust_id').value;
	
		      		  	  /* write variables */
		      		  	  Ext.get('show_id_excel').dom.value = show_id;
		      		  	  Ext.get('show_date_excel').dom.value = show_date;
		      		  	  Ext.get('cust_id_excel').dom.value = cust_id;
		      		  	  Ext.get('method_excel').dom.value = 'generate';
		      		  	
		      		  	  /* submit form located on index.html */
		      		  	  Ext.getDom('generate-excel').submit();
	        	  	  }
	  		      }]
			  })
	      });
	
	      var border = {
			  id:'border-panel',
			  layout:'border',
			  bodyBorder: true,
			  iconCls: 'icon-report',
	
			  animFloat: false,
	
			  items: [ gridReport, reportViewPanel ]
	      };
	
	    // Now that we've created the Panel properly, load the component
	    rpmCom.loadComp(border, 'Reports', mainPanel, 1, 'icon-report-user');
	
	    /**
	     * custom IE code to make sure the north/west panels don't collapse
	     */
	    if(Ext.isIE){
	    	Ext.resizePanelIE();
	    }
	}
};

Ext.form.ReportCalendarComboBox = 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.ReportCalendarComboBox.superclass.initEvents.call(this);

        // Select fires AFTER you click on a comboBox item (the list is collaspsed)
        this.on('select', this.onThisSelect, 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, limit: '1'}});
            }
        }
    },

    onThisSelect: function(record){
        var rowIndex = record.selectedIndex;
        var rowData = record.store.getAt(rowIndex).data;
        var id = rowData.id;
        var show_date = rowData.full_date;

        // Enable the Excel button
        Ext.getCmp('report-excel-button').enable();
        
        /* set new values */
        Ext.getCmp('report_grid_view_show_id').setValue(id);
        Ext.getCmp('report_grid_view_show_date').setValue(show_date);
        
		var show_id, show_date, cust_id;
        show_id = Ext.getCmp('report_grid_view_show_id').value;
        show_date = Ext.getCmp('report_grid_view_show_date').value;
        cust_id = Ext.getCmp('report_grid_view_cust_id').value;

        // Load the grid
        Ext.getCmp('storeViewReport').store.load({params:{method:'generate', show_date:String(show_date), show_id:String(show_id), cust_id:String(cust_id)}});
    }
});

Ext.form.ReportCalendarComboBoxDaily = 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.ReportCalendarComboBoxDaily.superclass.initEvents.call(this);

        // Select fires AFTER you click on a comboBox item (the list is collaspsed)
        this.on('select', this.onThisSelect, 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, cust_id;
    			show_id = Ext.getCmp('report_grid_view_show_id').value;
    			cust_id = Ext.getCmp('report_grid_view_cust_id').value;
    			if(show_id){
    				this.store.load({params:{query:this.getRawValue(), show_id:String(show_id), user_id: Ext.userId, cust_id:String(cust_id)}});
    			}
    			else{
    				this.store.load({params:{query:this.getRawValue(), show_id:'-1', user_id: Ext.userId, cust_id:String(cust_id)}});
    			}
            }
        }
    },

    onThisSelect: function(record){
        var rowIndex = record.selectedIndex;
        var rowData = record.store.getAt(rowIndex).data;
        var id = rowData.id;
        var show_date = rowData.full_date;

        // Enable the Excel button
        Ext.getCmp('report-excel-button').enable();
        
        /* set new values */
        Ext.getCmp('report_grid_view_show_id').setValue(id);
        Ext.getCmp('report_grid_view_show_date').setValue(show_date);
        
		var show_id, show_date, cust_id;
        show_id = Ext.getCmp('report_grid_view_show_id').value;
        show_date = Ext.getCmp('report_grid_view_show_date').value;
        cust_id = Ext.getCmp('report_grid_view_cust_id').value;
        
        // Load the grid
        Ext.getCmp('storeViewReport').store.load({params:{method:'generate', show_date:String(show_date), show_id:String(show_id), cust_id:String(cust_id)}});
    }
});