Ext.DemoCalendar = function(mainPanel){

	var tab = mainPanel.getComponent('docs-Demo Staff Calendar');
	if(tab){
		mainPanel.setActiveTab(tab);
	}
	else{	

		/************* Show list store *************/
		var storeShowsDemoCalendar = 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'}
	
	        ])
	    });
		
		storeShowsDemoCalendar.load({params:{query:'', user_id: Ext.userId, user_level: Ext.userLevel }});
	
		var fullShowCalendarStoreDaily = 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'}
	
			 ])
		});
		
	    // 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>'
	    );
	    
		/**
		 * DEMO LIST STORE
		 */
		var storeDemos = 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: 'demo_id', mapping: 'demo_id'},
	            {name: 'demo_nm', mapping: 'demo_nm'}
	        ])
	    });
		storeDemos.load({params:{query:'', user_id: Ext.userId, user_level: Ext.userLevel }});    
	
		/************* 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 }});
	
	    /**
	     * admin color key
	     */
	    if(Ext.user_level == 2){
	    	var adminKey = '<b><span class="blackcell">&nbsp;Gray&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></b>: Personal commitment added by Demonstrator<br /><b><span class="orangecell">&nbsp;Orange&nbsp;</span></b>: Demonstrator assigned elsewhere<br />';
	    	var adminButton = new Ext.Button({
                text: 'Send Notifications',
                id: 'button-outlook-notification',
                iconCls:'icon-page-white-office',
                disabled: true,
                fieldLabel: 'Notify',
                isFormField:true,
                handler: function(){
		    		/* define variables */
		    	    var show_date, show_id, demo_id;
		    	    
		    	    /* assign variables */
		    	    show_date = Ext.getCmp('demo_grid_view_show_date').value;
		    	    show_id = Ext.getCmp('demo_grid_view_show_id').value;
		    	    demo_id = Ext.getCmp('demo_nm_cal').getValue();	    		
            	
		    	    
		    	    Ext.Msg.show({
						title: 'Send Outlook Notifications?',
					   	msg: 'Click OK to send all notifications. Otherwise, click CANCEL to close this window.',
					   	width: 280,
					   	buttons: Ext.MessageBox.OKCANCEL,
					   	fn: function(btn, text, obj){
							if (btn == 'ok'){
								Ext.ux.Toast.msg('Notifying...', 'Sending Outlook notification emails to demonstrators.');
				    	    	Ext.Ajax.request({   
				                    waitMsg: 'One moment...',
				                    url: Ext.urlScriptDir + '/application/calendar.php',
				                    params: { method: 'generate_demo_user', show_date: String(show_date), show_id: String(show_id), demo_id: String(demo_id), outlook_notification: String(1) },
				                    
				                    success:function(form, action){
				                        obj = Ext.util.JSON.decode(form.responseText);
				                        if(obj.success === false){
				                        	Ext.Msg.alert('Error!', obj.errors.reason);
				                        }
				                        else{
				                        	Ext.Msg.alert('Success', 'All Outlook notifications have been sent successfully.');
				                        }
				                    },
				                    
				                    failure:function(form, action){
				                        if(action.failureType == 'server'){
				                            obj = Ext.util.JSON.decode(form.responseText);
				                            Ext.Msg.alert('Request Failed!', obj.errors.reason);
				                        }
				                        else{
				                            Ext.Msg.alert('Warning!', 'Server is unreachable : ' + form.responseText);
				                        }
				                    }
				                });
	    	                }
						},
					   	icon: Ext.MessageBox.QUESTION
					});
               	},
               	tooltipText: 'Click this button to notify all demonstrators in the bottom-half of the screen of all their demo assignments.',
               	listeners: {
					render:	Ext.setFormFieldTooltip
				}           	
            });
	    }
	    else{
	    	var adminKey = '';
	    	var adminButton = '';
	    }
	    
	    var formDemoCalendars = new Ext.form.FormPanel({
	        baseCls: 'x-plain',
	        labelWidth: 80,
	        id: 'resourceAvailFormItemsViewDemo',
	        
	        items: [
	                
		            /* CALENDAR OPTIONS */
		            {
		                layout:'column',
		                anchor: '98%',
		                
		                items:[
		                {
		                    columnWidth:.30,
		                    layout: 'form',
		                    items:[
		                           
								new Ext.form.FullDemoCalendarComboBox({
									fieldLabel: 'Show',
								    store: storeShowsDemoCalendar,
								    id: 'storeShowsDemoCalendar',
								    width: 250,
								    tpl: showTpl,
								    itemSelector: 'div.search-item'
								}),
								new Ext.form.FullDemoCalendarComboBoxDaily({
									fieldLabel: 'Limit',
								    store: fullShowCalendarStoreDaily,
								    id: 'fullDemoCalendarStoreDaily',
								    width: 250,
								    tpl: showTpl,
								    itemSelector: 'div.search-item',
								    disabled: true
								}),
								adminButton
							]
		                },
		                {
		                    columnWidth:.35,
		                    layout: 'form',
		                    items:[
								{
									fieldLabel: "Demos",
									xtype: "multiselect",
								    name: "demo_nm",
								    id: "demo_nm_cal",
								    dataFields: ["demo_id", "demo_nm"],
								    valueField: "demo_id",
								    displayField: "demo_nm",
								    width: 300,
								    height: 105,
								    allowBlank: true,
								
								    data:[],
								
								    store: storeDemos,
								
								    tbar:[
								    {
								        text:"Clear Selected",
								        handler:function(){
											Ext.getCmp('demo_nm_cal').reset();
											Ext.loadDemoCalendar();
								        }
								    }],
								    listeners: {
										after_click: function(){
											Ext.loadDemoCalendar();
										},
										render:	Ext.setFormFieldTooltip
									},
								    tooltipText: "You can choose one or multiple demos to view here; by default, the calendar will show you all available demos for a particular show."
								}
			                ]
		                },	                
		                {
		                    columnWidth:.35,
		                    layout: 'form',
		                    items:[
		                           
		           	            {
		        	            	xtype:'statictextfield',
		        	            	fieldLabel: 'Color Key',
		        	                anchor: '96%',
		        	                fieldClass: 'x-static-text-field',
		        	                rawValue: '<b><span class="greencell">&nbsp;Green&nbsp;&nbsp;&nbsp;</span></b>: No demonstrators assigned<br /><b><span class="literedcell"><font color="#FFFFFF">&nbsp;Red&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font></span></b>: One or more demonstrators assigned<br />'+adminKey
			        	        },
		        	            {
		        	            	xtype: 'hidden',
		        	            	name:'demo_grid_view_show_id',
		        	            	id:'demo_grid_view_show_id',
		        	            	value: 0
		        	            },
		        	            {
		        	            	xtype: 'hidden',
		        	            	name:'demo_grid_view_show_date',
		        	            	id:'demo_grid_view_show_date',
		        	            	value: 0
		        	            },
		        	            {
		        	            	xtype: 'hidden',
		        	            	name:'demo_grid_view_cust_id',
		        	            	id:'demo_grid_view_cust_id',
		        	            	value: 0,
		        	            	listeners: {
		        	            		render: function(){
		        			    			/* wait for the show store to finish loading */
		        	            				storeShowsDemoCalendar.on('load', function(p){
		        	            			    /* select the show */
		        	            				if(Ext.default_show){
		        	            					Ext.selectStore('storeShowsDemoCalendar', 'show_nm', Ext.default_show, Ext.default_show);
		        	            				}
		        	            			});
		        			    		}
		        			    	}
		        	            }
		        	        ]
		                }
		            ]
		        }
		    ]
	    });
	
	    // ***** NORTH *****
	    // Using the generic AdminPanel ux (in rpmPanel), we will create a panel to hold our data
	    var panelDemoCalendarNorth = new Ext.ux.AdminPanel({
	    	region:'north',
	        id:'panelDemoCalendarNorth',
	        height: 120,
	        split: true,
	        collapsible: true,
	        collapseMode: 'mini',
	
	        items: [ formDemoCalendars ]
	    });
	
	    // ***** CENTER *****
	    // The data store for the CENTER region
	    var store = new Ext.data.JsonStore({
	        root: 'data',
	    	totalProperty: 'totalCount',
	    	idProperty: 'id',
	    	remoteSort: true,
	
	    	fields: [
				'id',
				'show_id',
				'show_nm',
				'show_date',
				'demo_location',
				'demo_id',
				'demo_dt',
				'demo_nm',
				'demo_desc',
				'assign_id',
				'0600',
				'0630',
				'0700',
				'0730',
				'0800',
				'0830',
				'0900',
				'0930',
				'1000',
				'1030',
				'1100',
				'1130',
				'1200',
				'1230',
				'1300',
				'1330',
				'1400',
				'1430',
				'1500',
				'1530',
				'1600',
				'1630',
				'1700',
				'1730',
				'1800',
				'1830',
				'1900',
				'1930',
				'2000',
				'2030',
				'2100',
				'2130',
				'2200',
				'2230',
				'2300',
				'2330'
	    	],
	
	    	proxy: new Ext.data.HttpProxy({
	    		url: Ext.urlScriptDir + '/application/calendar.php'
	        }),
	        baseParams: { method: 'generate_demo', user_id: Ext.userId, user_level: Ext.userLevel },
			listeners:{
    			beforeload: function()
				{
					var onload = Ext.getCmp('panelDemoCalendarCenter');
					if (onload)
						onload.getEl().mask('Loading...', 'x-mask-loading');
				},
				load: function()
				{
					var onload = Ext.getCmp('panelDemoCalendarCenter');
					if (onload)
						onload.getEl().unmask();
				},
				loadexception: function()
				{
					var onload = Ext.getCmp('panelDemoCalendarCenter');
					if (onload)
						onload.getEl().unmask();
				}
    		}
	    });
	    store.setDefaultSort('demo_nm', 'asc');
	
	    var action = new Ext.ux.grid.RowActions({
			header:'Export',
			width: 120,
			sortable: false,
			actions:[
			    {
                    iconCls:'icon-pdf',
                    tooltip:'Download PDF'
			    },
			    {
                    iconCls:'icon-email-go',
                    tooltip:'Email to Me'
			    },
			    {
                    iconCls:'icon-print',
                    tooltip:'Printable View'
			    }
			],
			
			callbacks:{
				/* DOWNLOAD PDF ITEM */
            	'icon-pdf':function(grid, record, action, row, col) {
					/* display the toast message */
					Ext.ux.Toast.msg('Downloading PDF...', '{0}', record.json.demo_nm + ' Calendar');
					/* open a new window directly (no need for AJAX) */
					window.open(Ext.urlScriptDir + '/application/print_demo.php?method=generate&user_id='+record.json.demo_id+'&email_id='+Ext.user_id+'&show_id='+record.json.show_id+'&pdf=1&email=0', "printView");					
				},
				
				/* EMAIL TO ME */
            	'icon-email-go':function(grid, record, action, row, col) {
					/* display the toast message */
					Ext.ux.Toast.msg('Emailing Calendar...', '{0}', Ext.user_email);
					/* redirect to print_cust.php to email the customer calendar */
					Ext.Ajax.request({   
	                    url: Ext.urlScriptDir + '/application/print_demo.php',
	                    params: { method: 'generate', user_id: String(record.json.demo_id), email_id: String(Ext.user_id), show_id: String(record.json.show_id), pdf: String(0), email: String(1) },
	                    
	                    success:function(form, action){
	                        obj = Ext.util.JSON.decode(form.responseText);
	                        if(obj.success === false){
	                        	Ext.Msg.alert('Error!', obj.errors.reason);
	                        }
	                    },
	                    
	                    failure:function(form, action){
	                        if(action.failureType == 'server'){
	                            obj = Ext.util.JSON.decode(form.responseText);
	                            Ext.Msg.alert('Request Failed!', obj.errors.reason);
	                        }
	                        else{
	                            Ext.Msg.alert('Warning!', 'Server is unreachable : ' + form.responseText);
	                        }
	                    }
	                }); // end ajax request					
				},	
				
				/* PRINTABLE VIEW */
				'icon-print':function(grid, record, action, row, col) {
					/* display the toast message */
					Ext.ux.Toast.msg('Opening Printable View...', '{0}', record.json.cust_name + '\'s Calendar');
					/* open a new window directly (no need for AJAX) */
					window.open(Ext.urlScriptDir + '/application/print_demo.php?method=generate&user_id='+record.json.demo_id+'&email_id='+Ext.user_id+'&show_id='+record.json.show_id+'&pdf=0&email=0', "printView");
				}
			} // end callbacks
		});  	    
	    
	    
	    // ***** CENTER *****
	    // Create the Grid
	    var panelDemoCalendarCenter = new Ext.grid.GridPanel({
	    	title: 'Demo Calendar',
	    	id: 'panelDemoCalendarCenter',
	    	region:'center',
	
	    	store: store,
			  // Grid columns
			  columns:[{
				  id: 'demo_grid_name', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
				  header: "Demo",
				  dataIndex: 'demo_nm',
			      width: 150,
			      sortable: true
			  },
	          { header: "Date", dataIndex: 'demo_dt', width: 80, sortable: true },
	          { header: "8:00", dataIndex: '0800', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "8:30", dataIndex: '0830', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "9:00", dataIndex: '0900', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "9:30", dataIndex: '0930', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "10:00", dataIndex: '1000', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "10:30", dataIndex: '1030', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "11:00", dataIndex: '1100', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "11:30", dataIndex: '1130', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "12:00", dataIndex: '1200', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "12:30", dataIndex: '1230', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "13:00", dataIndex: '1300', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "13:30", dataIndex: '1330', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "14:00", dataIndex: '1400', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "14:30", dataIndex: '1430', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "15:00", dataIndex: '1500', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "15:30", dataIndex: '1530', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "16:00", dataIndex: '1600', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "16:30", dataIndex: '1630', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "17:00", dataIndex: '1700', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "17:30", dataIndex: '1730', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "18:00", dataIndex: '1800', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "18:30", dataIndex: '1830', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "19:00", dataIndex: '1900', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "19:30", dataIndex: '1930', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "20:00", dataIndex: '2000', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "20:30", dataIndex: '2030', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "21:00", dataIndex: '2100', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "21:30", dataIndex: '2130', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "22:00", dataIndex: '2200', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "22:30", dataIndex: '2230', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "23:00", dataIndex: '2300', width: 55, renderer: renderDemoCalendar, sortable: false },
	          { header: "23:30", dataIndex: '2330', width: 55, renderer: renderDemoCalendar, sortable: false },
	          action,
	          { header: "Demo", dataIndex: 'demo_nm', width: 200, sortable: true }
	          ],
	
	          plugins: [action],
	          
	    	  stripeRows: true,
	    	  autoscroll: true,
	          trackMouseOver:false,
	          disableSelection:true,
	          loadMask: false,
	          tools:[{
	    		    id:'print',
	    		    qtip: 'Print this Calendar',
	    		    handler: function(event, toolEl, panel){
	        	  		Ext.printScreen('panelDemoCalendarCenter');
	          		}
	          }]
	      });
	
	    
	    /**
	     * SOUTH CALENDAR
	     * 
	     * This calendar shows the demonstrators schedule & his or her availability.
	     * First, we create the dataset.
	     */
	    
	    var storeSouth = new Ext.data.JsonStore({
	    	root: 'data',
	    	totalProperty: 'totalCount',
	    	idProperty: 'id',
	    	remoteSort: true,
	
	    	fields: [
	    	         'id',
	    	         'show_id',
	    	         'show_nm',
	    	         'user_id',
	    	         'user_nm',
	    	         'demo_dt',
	    	         '0600',
	    	         '0630',
	    	         '0700',
	    	         '0730',
	    	         '0800',
	    	         '0830',
	    	         '0900',
	    	         '0930',
	    	         '1000',
	    	         '1030',
	    	         '1100',
	    	         '1130',
	    	         '1200',
	    	         '1230',
	    	         '1300',
	    	         '1330',
	    	         '1400',
	    	         '1430',
	    	         '1500',
	    	         '1530',
	    	         '1600',
	    	         '1630',
	    	         '1700',
	    	         '1730',
	    	         '1800',
	    	         '1830',
	    	         '1900',
	    	         '1930',
	    	         '2000',
	    	         '2030',
	    	         '2100',
	    	         '2130',
	    	         '2200',
	    	         '2230',
	    	         '2300',
	    	         '2330'
	    	],
	
	        proxy: new Ext.data.HttpProxy({
	        	url: Ext.urlScriptDir + '/application/calendar.php'
	        }),
	        
	    	baseParams: { method: 'generate_demo_user', user_id: Ext.userId, user_level: Ext.userLevel },
		    
	    	listeners:{
				beforeload: function()
				{
					var onload = Ext.getCmp('panelDemoCalendarSouth');
					if (onload){
						onload.getEl().mask('Loading...', 'x-mask-loading');
					}
				},
				load: function()
				{
					var onload = Ext.getCmp('panelDemoCalendarSouth');
					if (onload){
						onload.getEl().unmask();
						Ext.getCmp('button-outlook-notification').enable();
					}
				},
				loadexception: function()
				{
					var onload = Ext.getCmp('panelDemoCalendarSouth');
					if (onload){
						onload.getEl().unmask();
					}
				}
			}	    
	    });
	    storeSouth.setDefaultSort('tour_cust_id', 'asc');
	
	    var action2 = new Ext.ux.grid.RowActions({
			header:'Export',
			width: 120,
			sortable: false,
			actions:[
			    {
                    iconCls:'icon-pdf',
                    tooltip:'Download PDF'
			    },
			    {
                    iconCls:'icon-email-go',
                    tooltip:'Email to Me'
			    },
			    {
                    iconCls:'icon-print',
                    tooltip:'Printable View'
			    }
			],
			
			callbacks:{
				/* DOWNLOAD PDF ITEM */
            	'icon-pdf':function(grid, record, action, row, col) {
					/* display the toast message */
					Ext.ux.Toast.msg('Downloading PDF...', '{0}', record.json.user_nm + '\'s Calendar');
					/* open a new window directly (no need for AJAX) */
					window.open(Ext.urlScriptDir + '/application/print.php?method=generate&user_id='+record.json.user_id+'&email_id='+Ext.user_id+'&show_id='+record.json.show_id+'&pdf=1&email=0', "printView");					
				},
				
				/* EMAIL TO ME */
            	'icon-email-go':function(grid, record, action, row, col) {
					/* display the toast message */
					Ext.ux.Toast.msg('Emailing Calendar...', '{0}', Ext.user_email);
					/* redirect to print_cust.php to email the customer calendar */
					Ext.Ajax.request({   
	                    url: Ext.urlScriptDir + '/application/print.php',
	                    params: { method: 'generate', user_id: String(record.json.user_id), email_id: String(Ext.user_id), show_id: String(record.json.show_id), pdf: String(0), email: String(1) },
	                    
	                    success:function(form, action){
	                        obj = Ext.util.JSON.decode(form.responseText);
	                        if(obj.success === false){
	                        	Ext.Msg.alert('Error!', obj.errors.reason);
	                        }
	                    },
	                    
	                    failure:function(form, action){
	                        if(action.failureType == 'server'){
	                            obj = Ext.util.JSON.decode(form.responseText);
	                            Ext.Msg.alert('Request Failed!', obj.errors.reason);
	                        }
	                        else{
	                            Ext.Msg.alert('Warning!', 'Server is unreachable : ' + form.responseText);
	                        }
	                    }
	                }); // end ajax request					
				},	
				
				/* PRINTABLE VIEW */
				'icon-print':function(grid, record, action, row, col) {
					/* display the toast message */
					Ext.ux.Toast.msg('Opening Printable View...', '{0}', record.json.user_nm + '\'s Calendar');
					/* open a new window directly (no need for AJAX) */
					window.open(Ext.urlScriptDir + '/application/print.php?method=generate&user_id='+record.json.user_id+'&email_id='+Ext.user_id+'&show_id='+record.json.show_id+'&pdf=0&email=0', "printView");
				}
			} // end callbacks
		});	    
	    
	    /**
	     * SOUTH CALENDAR
	     * 
	     * Now, we create the actual calendar & set up the renderers.
	     */
	    
	    var panelDemoCalendarSouth = new Ext.grid.GridPanel({
	    	title: 'Demo Staff Calendar',
	    	id: 'panelDemoCalendarSouth',
	    	region:'south',
	
	        height: 200,
	        minSize: 50,
	        maxSize: 500,
	        split: true,
	        collapsible: true,
	        collapseMode: 'mini',
	
	    	store: storeSouth,
	    	columns:[{
	    		id: 'demo_grid_name_south', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
	    		header: "Demonstrator",
	    		dataIndex: 'user_nm',
	    		width: 150,
	    		sortable: true
	    	},
	    	{ header: "Date", dataIndex: 'demo_dt', width: 80, sortable: true },
	    	{ header: "8:00", dataIndex: '0800', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "8:30", dataIndex: '0830', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "9:00", dataIndex: '0900', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "9:30", dataIndex: '0930', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "10:00", dataIndex: '1000', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "10:30", dataIndex: '1030', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "11:00", dataIndex: '1100', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "11:30", dataIndex: '1130', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "12:00", dataIndex: '1200', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "12:30", dataIndex: '1230', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "13:00", dataIndex: '1300', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "13:30", dataIndex: '1330', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "14:00", dataIndex: '1400', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "14:30", dataIndex: '1430', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "15:00", dataIndex: '1500', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "15:30", dataIndex: '1530', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "16:00", dataIndex: '1600', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "16:30", dataIndex: '1630', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "17:00", dataIndex: '1700', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "17:30", dataIndex: '1730', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "18:00", dataIndex: '1800', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "18:30", dataIndex: '1830', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "19:00", dataIndex: '1900', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "19:30", dataIndex: '1930', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "20:00", dataIndex: '2000', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "20:30", dataIndex: '2030', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "21:00", dataIndex: '2100', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "21:30", dataIndex: '2130', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "22:00", dataIndex: '2200', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	{ header: "22:30", dataIndex: '2230', width: 55, renderer: renderDemoUserCalendar, sortable: false },
	    	action2,
	        { header: "Demonstrator", dataIndex: 'user_nm', width: 200, sortable: true }
	    	],
	
	    	plugins: [action2],
	    	
	    	stripeRows: true,
	    	autoscroll: true,
	    	trackMouseOver:false,
	    	disableSelection:true,
	    	loadMask: false,
	    	tools:[{
    		    id:'print',
    		    qtip: 'Print this Calendar',
    		    handler: function(event, toolEl, panel){ 
    		    	Ext.printScreen('panelDemoCalendarSouth');
	    		}
	    	}]
	    });
	
	    
	    /**
	     * If an admin is viewing the calendar, show both the Center and South Calendars,
	     * otherwise we will only show the Center Calendar.
	     */
	    
	    if(Ext.user_level == 2){
	    	var border = {
	    			id:'border-panel',
	    			layout:'border',
	    			bodyBorder: true,
	    			iconCls: 'icon-app-list-view',
	    			animFloat: false,
	    			items: [ panelDemoCalendarCenter, panelDemoCalendarNorth, panelDemoCalendarSouth ]
	    	};
	    }
	    else{
	    	var border = {
	    			id:'border-panel',
	    			layout:'border',
	    			bodyBorder: true,
	    			iconCls: 'icon-tour-calendar',
	    			animFloat: false,
	    			items: [ panelDemoCalendarCenter, panelDemoCalendarNorth ]
	    	};
	    }
	
	    // Now that we've created the Panel properly, load the component
	    rpmCom.loadComp(border, 'Demo Staff Calendar', mainPanel, 1, 'icon-demo-cal');
	
	    if(Ext.isIE){
	    	Ext.resizePanelIE();
	    }
	}
};

function renderDemoCalendar(data, cell, record, rowIndex, columnIndex, store){
	
	/* color | demo_assign ID | time data | demo guide nm */
	
	/* define variables */
	var color, assign_id, time_data, demo_loc, demo_nm, demo_desc, demo_guide, return_str, show_id, show_nm, str, br;
	show_id = record.data.show_id;
	show_nm = record.data.show_nm;
	demo_nm = record.data.demo_nm;
	demo_loc = record.data.demo_location;
	demo_desc = record.data.demo_desc;
	
	if(data){
		/* split up the primary string */
		var arr = data.split('@');
		return_str = '';
		
		for(var i=0,len=arr.length; value=arr[i], i<len; i++) {
			str = value.split('|');
			/* assign the data to the variables */
			color = str[0];
			assign_id = str[1];
			time_data = str[2]; 
			demo_guide = str[3];
			
			/* if there are multiple demonstrators, we need to add a break */
			if(i > 0){ br = '<br />'; } else { br = ''; }
			
			switch(color){
			
				/* green means no demonstrators are assigned to this demo timeslot */
				case "Green":
					cell.css = "greencell";
					cell.attr = 'ext:qtip="This timeblock has no demonstrator assigned."';
					return_str += "<a href='javascript:Ext.demoAssignRemove(Ext.mainPanelVar, \"" + show_id + "\", \"" + show_nm + "\", \"" + demo_guide + "\", \"" + demo_nm + "\", \"" + time_data + "\")'><font color=\"#000000\"><span ext:qtip=\"<b>Location</b>: "+demo_loc+"\">Avail</span></font></a>";
				break;
				
				/* red means one or more demonstrators are assigned */
				case "Red":
					cell.css = "literedcell";
					return_str += br+"<a href='javascript:Ext.demoAssignRemove(Ext.mainPanelVar, \"" + show_id + "\", \"" + show_nm + "\", \"" + demo_guide + "\", \"" + demo_nm + "\", \"" + assign_id + "\")'><font color=\"#FFFFFF\"><span ext:qtip=\"<b>Demonstrator</b>: "+demo_guide+"<br /><b>Location</b>: "+demo_loc+"\">"+demo_guide+"</span></font></a>";
				break;
					
				default:
					return_str += "";
				break;
			}
		}
		return return_str;
	}	
};

function renderDemoUserCalendar(data, cell, record, rowIndex, columnIndex, store){
	
	/* color | demo_assign ID/avail ID | time data | demo location | comment */
	
	/* define variables */
	var color, assign_id, time_data, demo_loc, demo_nm, demo_desc, demo_guide, return_str, show_id, show_nm, str, br;
	show_id = record.data.show_id;
	show_nm = record.data.show_nm;
	user_id = record.data.user_id;
	user_nm = record.data.user_nm;
	
	if(data){
		/* split up the primary string */
		var arr = data.split('@');
		return_str = '';
		
		for(var i=0,len=arr.length; value=arr[i], i<len; i++) {
			str = value.split('|');
			/* assign the data to the variables */
			color = str[0];
			assign_id = str[1];
			time_data = str[2]; 
			demo_loc = str[3];
			comment = str[4]; // also demo_nm for red array
			
			/* if there are multiple demonstrators, we need to add a break */
			if(i > 0){ br = '<br />'; } else { br = ''; }
			
			switch(color){
			
				/* black means the demonstrator has said he or she is unavailable */
				case "Black":
					cell.css = "blackcell";
					return_str += "<a href='javascript:Ext.editAvailRemove(Ext.mainPanelVar, \"" + assign_id + "\", \"" + show_id + "\", \"" + show_nm + "\", \"" + comment + "\", \"" + user_id + "\", \"" + user_nm + "\")'><font color=\"#000000\"><span ext:qtip=\"<b>Not Available</b>: "+comment+"\">"+comment+"</span></font></a>";
					break;
					
				/* red means this demonstrator is already assigned to a demo */
				case "Red":
					cell.css = "literedcell";
					return_str += br+"<a href='javascript:Ext.demoAssignRemove(Ext.mainPanelVar, \"" + show_id + "\", \"" + show_nm + "\", \"" + user_nm + "\", \"" + comment + "\", \"" + assign_id + "\")'><font color=\"#FFFFFF\"><span ext:qtip=\"<b>Demonstrator</b>: "+user_nm+"<br /><b>Location</b>: "+demo_loc+"\">"+comment+"</span></font></a>";
					break;
					
				/* orange means this demonstrator is assigned to a tour elsewhere */
				case "Orange":
					cell.css = "orangecell";
					return_str += br+"<a href='javascript:Ext.resource.editTourRemove(Ext.mainPanelVar, \"" + assign_id + "\", \"" + show_id + "\", \"" + show_nm + "\", \"" + comment + "\")'><font color=\"#000000\"><span ext:qtip=\"<b>Tour Guide</b>: "+user_nm+"<br /><b>Location</b>: "+demo_loc+"<br /><b>Customer</b>: "+comment+"\">"+comment+"</span></font></a>";
					break;
					
				default:
					return_str += "";
				break;
				
			}
		}
		return return_str;
	}	
};

function renderRowDemoGridSouth(data, cell, record, rowIndex, columnIndex, store){
	var temp = data.split('|');

	var id = record.data.id;
	var show_id = record.data.show_id;
	var show_nm = record.data.show_nm;
	var demo_location = record.data.demo_location;
	var type = temp[0];
	var reason = temp[1];
	var assign_id = temp[2];
	var avail = temp[3];
	var avail_user_id = temp[4];
	var user_name = temp[5];

	switch(type){
		case "Black":
			cell.css = "blackcell";
			return "<a href='javascript:Ext.editAvailRemove(Ext.mainPanelVar, \"" + assign_id + "\", \"" + show_id + "\", \"" + show_nm + "\", \"" + reason + "\", \"" + avail_user_id + "\", \"" + user_name + "\")'><font color=\"#000000\"><div ext:qtip=\"<b>Not Available</b>: "+reason+"\">"+reason+"</div></font></a>";
			break;

		case "Red":
			cell.css = "literedcell";
			return "<a href='javascript:Ext.demoAssignRemove(Ext.mainPanelVar, \"" + id + "\", \"" + show_nm + "\", \"" + user_name + "\", \"" + reason + "\", \"" + assign_id + "\")'><font color=\"#FFFFFF\"><div ext:qtip=\"<b>Demonstrator</b>: "+user_name+"<br /><b>Location</b>: "+demo_location+"\">"+reason+"</div></font></a>";
			break;
			
		case "RedTour":
			cell.css = "orangecell";
			return "<a href='javascript:Ext.editTourRemove(Ext.mainPanelVar, \"" + assign_id + "\", \"" + show_id + "\", \"" + show_nm + "\", \"" + reason + "\")'><font color=\"#FFFFFF\"><div ext:qtip=\"<b>TOUR GUIDE</b><br /><br /><b>Customer</b>: "+reason+"\">"+reason+"</div></font></a>";
			
	}
};

/**
 * load the demo calendar
 * 
 * global function to load the demo calendar
 */

Ext.loadDemoCalendar = function(){
	/* define variables */
    var show_date, show_id, demo_id;
    
    /* assign variables */
    show_date = Ext.getCmp('demo_grid_view_show_date').value;
    show_id = Ext.getCmp('demo_grid_view_show_id').value;
    demo_id = Ext.getCmp('demo_nm_cal').getValue();

    /* load the calendar */
    Ext.getCmp('panelDemoCalendarCenter').store.load({params:{method:'generate_demo', show_date:String(show_date), show_id:String(show_id), demo_id:String(demo_id)}});
    Ext.getCmp('panelDemoCalendarSouth').store.load({params:{method:'generate_demo_user', show_date:String(show_date), show_id:String(show_id), demo_id:String(demo_id)}});	
};

Ext.form.FullDemoCalendarComboBox = Ext.extend(Ext.form.ComboBox, {
    typeAhead: false,
    displayField: 'show_nm',
    mode: 'remote',
    triggerAction: 'all',
    loadOnTrigger: true,
    emptyText: 'Select a show name...',
    selectOnFocus: true,
    minChars: 2,

    // private
    initEvents : function(){
        // Call the parent (make sure this matches the object above!)
		Ext.form.FullShowCalendarComboBox.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(), limit: '1', user_id: Ext.userId}});
            }
        }

    },

    onThisSelect: function(record){
        var rowIndex = record.selectedIndex;
        var rowData = record.store.getAt(rowIndex).data;
		var id = rowData.id;
	    var show_date = rowData.full_date;
	    var filter = 0;
	    var cust_id;
	    
	    /* enable the limit by day dropdown */
        Ext.getCmp('fullDemoCalendarStoreDaily').enable();
	
	    Ext.getCmp('demo_grid_view_show_id').setValue(id);
	    Ext.getCmp('demo_grid_view_show_date').setValue(show_date);
	    
	    /* load the demo list */
	    Ext.getCmp('demo_nm_cal').store.load({params:{method:'list', show_id:String(id)}});
	    
	    Ext.loadDemoCalendar();
	}
});

Ext.form.FullDemoCalendarComboBoxDaily = Ext.extend(Ext.form.ComboBox, {
	typeAhead: false,
	displayField: 'show_nm',
	mode: 'remote',
	triggerAction: 'all',
	loadOnTrigger: true,
	emptyText: 'Limit by day...',
	selectOnFocus: true,
	minChars: 2,

	// private
	initEvents : function(){
		// Call the parent (make sure this matches the object above!)
		Ext.form.FullShowCalendarComboBox.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;
				show_id = Ext.getCmp('demo_grid_view_show_id').value;
				if(show_id){
					this.store.load({params:{query:this.getRawValue(), show_id:String(show_id), user_id: Ext.userId}});
				}
				else{
					this.store.load({params:{query:this.getRawValue(), show_id:'-1', user_id: Ext.userId}});
				}
			}
		}
	},

	onThisSelect: function(record){
		var rowIndex = record.selectedIndex;
		var rowData = record.store.getAt(rowIndex).data;
		var id = rowData.id;
        var show_date = rowData.full_date;

        Ext.getCmp('demo_grid_view_show_id').setValue(id);
        Ext.getCmp('demo_grid_view_show_date').setValue(show_date);

        Ext.loadDemoCalendar();
	}
});