/**
 * Function to remove the Edit Tour tab (called from tour_grid_view.js)
 */
Ext.editAvailRemove = function(mainPanel, id, show_id, show_nm, cust_name, avail_user_id, user_name){
    var tab = mainPanel.getComponent('docs-Edit Availability');
    // If the tab exists, destroy it
    if(tab){
    	mainPanel.remove(tab);
    	mainPanel.doLayout();
    }
    // Recreate the tab
    Ext.editAvailability(mainPanel, id, show_id, show_nm, cust_name, avail_user_id, user_name);
};
	
Ext.editAvailability = function(mainPanel, id, show_id, show_nm, cust_name, avail_user_id, user_name){

	var tab = mainPanel.getComponent('docs-Edit Availability');
	if(tab){
		mainPanel.setActiveTab(tab);
	}
	else{	


		/************* Show list store *************/
		var storeShowsUserAvail = 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
	    storeShowsUserAvail.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>'
	    );
	
		/************* users *************/
		var userStore = new Ext.data.Store({
	        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/users.php'}),
	        baseParams: { method: 'list', user_id: Ext.userId, user_level: Ext.userLevel },
	        reader: new Ext.data.JsonReader({
	            root: 'data',
	            totalProperty: 'totalCount',
	            id: 'user_id'
	        },
	        [
	            {name: 'id', mapping: 'user_id'},
	            {name: 'user_name', mapping: 'user_name'},
	            {name: 'user_email', mapping: 'user_email'},
	            {name: 'user_phone_mobile', mapping: 'user_phone_mobile'},
	            {name: 'user_phone_work', mapping: 'user_phone_work'},
	            {name: 'team_id', mapping: 'team_id'},
	            {name: 'customer_association', mapping: 'customer_association'},
	            {name: 'tour_staff', mapping: 'tour_staff'},
	            {name: 'demo_staff', mapping: 'demo_staff'},
	            {name: 'br', mapping: 'br'}
	        ])
	    });
		// We only want users loaded who match up w/ the show selected, so wait to load until after the show is selected
	
		/********** php_users_avail **********/
		var availStore = new Ext.data.Store({
	        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/users.php'}),
	        baseParams: { method: 'list_avail', user_id: Ext.userId, user_level: Ext.userLevel },
	        reader: new Ext.data.JsonReader({
	            root: 'data',
	            totalProperty: 'totalCount',
	            id: 'id'
	        },
	        [
	            {name: 'id', mapping: 'id'},
	            {name: 'user_id', mapping: 'user_id'},
	            {name: 'show_id', mapping: 'show_id'},
	            {name: 'avail_dt', mapping: 'avail_dt'},
	            {name: 'avail_st', mapping: 'avail_st'},
	            {name: 'avail_en', mapping: 'avail_en'},
	            {name: 'avail_comment', mapping: 'avail_comment'},
	            {name: 'reason', mapping: 'reason'},
	            {name: 'br', mapping: 'br'},
	            {name: 'to', mapping: 'to'},
	            {name: 'from', mapping: 'from'},
	            {name: 'date', mapping: 'date'}
	        ])
	    });
	
	    var availTpl = new Ext.XTemplate(
	            '<tpl for="."><div class="search-item">',
	                '{reason} {avail_comment}{br}',
	                '{date} {avail_dt} {from} {avail_st} {to} {avail_en}',
	            '</div></tpl>'
	    );
	
	    // Create the email form that is populated with the Panel display
	    var availForm = new Ext.form.FormPanel({
	        baseCls: 'x-plain',
	        labelWidth: 130,
	        url: Ext.urlScriptDir + '/application/users.php',
	        id: 'availFormItems',
	        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: 'user_id', mapping: 'user_id'},
	                 {name: 'avail_dt', mapping: 'avail_dt'},
	                 {name: 'avail_st', mapping: 'avail_st'},
	                 {name: 'avail_en', mapping: 'avail_en'},
	                 {name: 'avail_comment', mapping: 'avail_comment'}
	           ]
	        }),
	        items: [
	            new Ext.form.ShowUserAvailComboBox({
	                store: storeShowsUserAvail,
	                id: 'storeShowsUserAvail',
	                fieldLabel: 'Shows',
	                anchor: '96%',
	                tpl: showTpl,
	                itemSelector: 'div.search-item'
	            }),
	            new Ext.form.UserAvailComboBox({
	            	store: userStore,
	            	id: 'userAvailStore',
	            	fieldLabel: 'Users',
	            	anchor: '96%',
	            	disabled: true,
	                tooltipText: "Type the first few letters of the user\'s last name to find them.",
	                listeners: { render: Ext.setFormFieldTooltip }
	            }),
	            new Ext.form.UserNotAvailComboBox({
	            	store: availStore,
	            	id: 'userNotAvailStore',
	            	fieldLabel: 'Availability Restrictions',
	            	anchor: '96%',
	            	disabled: true,
	            	tpl: availTpl,
	            	itemSelector: 'div.search-item',
	            	tooltipText: "This field shows a list of when the user is unavailable and why.",
	                listeners: { render: Ext.setFormFieldTooltip }
	            }),{
	            	xtype: 'datefield',
	            	vtype: 'daterange',
	            	fieldLabel: 'Date',
	                name: 'avail_dt',
	                id: 'avail_dt',
	                format: 'M. j, Y',
	                width: 150
	            },
	            {
	            	xtype:'timefield',
	            	fieldLabel: 'Start Time',
	            	id:'avail_st',
	            	name:'avail_st',
	            	width: 150,
	            	format: 'H:i',
	            	minValue: '05:00',
	            	maxValue: '22:30',
	            	increment: 30,
	            	forceSelection: true
	            },
	            {
	            	xtype:'timefield',
	            	fieldLabel: 'End Time',
	            	id:'avail_en',
	            	name:'avail_en',
	            	width: 150,
	            	format: 'H:i',
	            	minValue: '05:30',
	            	maxValue: '23:00',
	            	increment: 30,
	            	forceSelection: true
	            },
		        {
		        	xtype: 'textarea',
		        	fieldLabel: 'Why Unavailable?*',
		        	name: 'avail_comment',
		        	width:250,
		        	grow: true,
		        	allowBlank: false,
		        	tooltipText: "Please enter why you are unavailable for the chosen time period.",
		        	listeners: { render: Ext.setFormFieldTooltip }
		        },
			    {
			    	xtype: 'hidden',
			    	name:'show_id',
			    	id:'show_id_user_avail',
			    	value: 0
			    },
	            {
	            	xtype: 'hidden',
	            	name:'avail_id',
	            	id:'avail_id_user_avail',
	            	value: 0
	            },
			    {
			    	xtype: 'hidden',
			    	name:'user_id_user_avail',
			    	id:'user_id_user_avail',
			    	value: 0,
	            	listeners: {
	            		render: function(){
			    			// If the user level is not an admin ('2'), then we need to disable the add/delete/manage buttons (TODO: hide them completely)
			    			if(Ext.userLevel < 2){
			    				/* disable the manage button, leave the add/delete buttons alone */
			    				Ext.getCmp('userAvailManageButton').disable();
			    			}
	
			    			// Wait for demo combobox to load, then load the form
	            			storeShowsUserAvail.on('load', function(p){
	            			    // If we send in an id, auto load the proper tour
	            			    if(id){
	            			    	
	            			    	/* select the show name in the store */
	            			    	Ext.selectStore('storeShowsUserAvail', 'show_nm', show_nm, show_nm);
	            			    	
	            			    	// Once the select event fires, we need to wait until everything else is loaded before continuing
	            			    	userStore.on('load', function(p){
	            			    		
	            			    		/* select the user_name in the store */
	        			    			Ext.selectStore('userAvailStore', 'user_name', user_name, user_name);
	        			    			
	        			    			availStore.on('load', function(p){
	        			    			
	        			    				/* select the comment in the store */
	            			    			Ext.selectStore('userNotAvailStore', 'avail_comment', cust_name, cust_name);
	            			    			
	                			    	}, this, {single: true}); // Don't forget to make these a single run only!
	            			    	}, this, {single: true}); // Don't forget to make these a single run only!
	            			    }
	            			    else{
	            			    	 /* select the show */
	                				if(Ext.default_show){
	                					Ext.selectStore('storeShowsUserAvail', 'show_nm', Ext.default_show, Ext.default_show);
	                				}	
	            			    }
	            			}, this, {single: true});
	
	            		}
	            	}
			    }
	        ],
	
	        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('availFormItems', 'storeShowsUserAvail', 'editUserAvailSB', '/application/users.php', 'save_avail', 'userNotAvailStore');
	        	}
	        },
	        {
	            text: 'Reset',
	            type: 'reset',
	            handler: function(){
	                // Clear all the values in the form
	        		availForm.getForm().reset();
	        		// Disable some comboboxes
	        		Ext.getCmp('userAvailStore').disabled();
	        		Ext.getCmp('userNotAvailStore').disabled();
	                // Set the focus to the FROM field
	                Ext.getCmp('storeShowsUserAvail').focus();
	            }
	        }]
	    });
	
	    // Using the generic AdminPanel ux (in rpmPanel), we will create a panel to hold our form
	    var availPanel = new Ext.ux.AdminPanel({
	        id:'userAvailPanel',
	        items: [ availForm ],
	        tbar: [
	               {
	            	   	// ADD
	            	   	id: 'userAvailAddButton',
	            	   	icon: Ext.urlScriptDir + Ext.urlIconDir + '/add.png',
	            	   	cls: 'x-btn-icon',
	            	   	tooltip: '<b>New Availability Restriction</b><br />Clear the form and create a new availability restriction.',
	            	   	handler: function(){
	                   		Ext.newResourceGlobal('availFormItems', 'storeShowsUserAvail', 'editUserAvailSB', '/application/users.php', 'save_avail', 'userNotAvailStore');
	               		}
	               },
	               {
	            	   // DELETE
	            	   id: 'userAvailDeleteButton',
	            	   icon: Ext.urlScriptDir + Ext.urlIconDir + '/delete.png',
	            	   cls: 'x-btn-icon',
	            	   tooltip: '<b>Delete Availability Restriction</b><br />Delete loaded user\'s availability restriction from the system.',
	            	   handler: function(){
	                    	Ext.deleteResourceGlobal('availFormItems', 'storeShowsUserAvail', 'editUserAvailSB', '/application/users.php', 'delete_avail', 'userNotAvailStore', 'avail_id_user_avail'); // the field of the id we are deleting
	                	}
	               },
	               '-',
	               {
	            	   	// SAVE
	            	   	icon: Ext.urlScriptDir + Ext.urlIconDir + '/save.gif',
	            	   	cls: 'x-btn-icon',
	            	   	tooltip: '<b>Save Non-Availability</b><br />Save current user\'s availability restriction.',
	            	   	handler: function(){
	            	   		Ext.saveResourceGlobal('availFormItems', 'storeShowsUserAvail', 'editUserAvailSB', '/application/users.php', 'save_avail', 'userNotAvailStore'); // the store we want to reload on a "method: save_as" return from the php file
	            		}
	               },
	               '->',
	            {
	            	text: 'Manage: '
	            },
	            {
	            	id: 'userAvailManageButton',
	                icon: Ext.urlScriptDir + Ext.urlIconDir + '/user.png',
	                cls: 'x-btn-icon',
	                tooltip: '<b>Registered User Details</b><br />Manage individual user details.',
	                handler: function(){
	            		Ext.show.editRegisteredUsers(mainPanel);
	            	}
	            }
	        ],
	        // Bottom Bar which holds the status bar for updates, etc
	        bbar: new Ext.StatusBar({
	            id: 'editUserAvailSB',
	            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(availPanel, 'Edit Availability', mainPanel, 0, 'icon-user-comment');
	    // Set focus to the name field
	    Ext.getCmp('storeShowsUserAvail').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.ShowUserAvailComboBox = 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,

    // private
    initEvents : function(){
        // Call the parent (make sure this matches the object above!)
		Ext.form.ShowUserAvailComboBox.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}});
            }
        }

    },

    onThisSelect: function(record){
        var rowIndex = record.selectedIndex;
        var rowData = record.store.getAt(rowIndex).data;
        var id = rowData.id;

        // Load the users & php_users_avail stores
        Ext.getCmp('userAvailStore').store.load({params:{method:'list', show_id:String(id)}});
        Ext.getCmp('userAvailStore').enable();

   		// Manually set the show_id field
   		Ext.getCmp('show_id_user_avail').setValue(id);

        // Set the date to the show start date
        Ext.getCmp('avail_dt').setMinValue(rowData.show_date_st); // Makes it so you cannot select dates before or after the actual show
        Ext.getCmp('avail_dt').setMaxValue(rowData.show_date_en);
        Ext.getCmp('avail_dt').setValue(rowData.show_date_st);

        // Set the start and end times
        Ext.getCmp('avail_st').setValue('08:00');
        Ext.getCmp('avail_en').setValue('09:00');

   		if(Ext.userLevel < 2){
			// Wait for the user store to load, then auto populate the rest of the fields
			Ext.getCmp('userAvailStore').store.on('load', function(p){
	    		var tourStoreVar = Ext.getCmp('userAvailStore');
		    	tourStoreVar.setValue(Ext.userNameLastFirst);
		    	var selectedIndex = tourStoreVar.store.find('user_name', Ext.userNameLastFirst);
		    	tourStoreVar.selectedIndex = selectedIndex;
		    	// Now fire the second select event, which loads the rest of the form
		    	tourStoreVar.fireEvent('select', tourStoreVar, tourStoreVar.store.getAt(selectedIndex), selectedIndex);
	    	}, this, {single: true}); // Don't forget to make these a single run only!
		}

    }
});

Ext.form.UserAvailComboBox = Ext.extend(Ext.form.ComboBox, {
    typeAhead: false,
    displayField: 'user_name',
    mode: 'local',
    triggerAction: 'all',
    emptyText: 'Load a show first...',
    selectOnFocus: true,
    minChars: 2,

    // private
    initEvents : function(){
        // Call the parent (make sure this matches the object above!)
		Ext.form.UserAvailComboBox.superclass.initEvents.call(this);

        // Select fires AFTER you click on a comboBox item (the list is collaspsed)
        this.on('select', this.onThisSelect, this);

        this.store.on('load', function(p){
            this.emptyText = 'Select a registered user...';
            this.setValue('Select a registered user...');
        }, 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}});
            }
        }

    },

    onThisSelect: function(record){
        var rowIndex = record.selectedIndex;
        var rowData = record.store.getAt(rowIndex).data;
        var id = rowData.id;

        var show_id = Ext.getCmp('show_id_user_avail').value;

        // Load the users & php_users_avail stores
        Ext.getCmp('userNotAvailStore').store.load({params:{method:'list_avail', id:String(id), show_id:String(show_id)}});
        Ext.getCmp('userNotAvailStore').enable();

   		// Manually set the show_id field
   		Ext.getCmp('user_id_user_avail').setValue(id);
    }
});

Ext.form.UserNotAvailComboBox = Ext.extend(Ext.form.ComboBox, {
	typeAhead: false,
	displayField: 'avail_comment',
	mode: 'local',
	triggerAction: 'all',
	emptyText: 'Load a show and user first...',
	selectOnFocus: true,
	minChars: 2,

	// private
	initEvents : function(){
		// Call the parent (make sure this matches the object above!)
		Ext.form.UserNotAvailComboBox.superclass.initEvents.call(this);

		// Select fires AFTER you click on a comboBox item (the list is collaspsed)
		this.on('select', this.onThisSelect, this);

		this.store.on('load', function(p){
			this.emptyText = 'Select a saved availability restriction...';
			this.setValue('Select a saved availability 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}});
			}
		}

	},

	onThisSelect: function(record){
		var rowIndex = record.selectedIndex;
		var rowData = record.store.getAt(rowIndex).data;
		var avail_id = rowData.id;
		var show_id = rowData.show_id;
		var user_id = rowData.user_id;

		if(rowData.avail_comment != 'This user has no availability restrictions...'){
			var loc = Ext.getCmp('availFormItems');
			loc.getForm().load({params:{method:'list_avail', id:String(user_id), show_id:String(show_id), avail_id:String(avail_id)}}); // queries from php_users_avail
			loc.getForm().on('actioncomplete', function(p){
				Ext.getCmp('avail_id_user_avail').setValue(avail_id);
				Ext.getCmp('user_id_user_avail').setValue(user_id);
				Ext.getCmp('show_id_user_avail').setValue(show_id);
			}, this);
		}
	}
});