EMA.Alert.grid.AlarmCommands = Ext.extend(EMA.GridPanel, {
	constructor : function(config) {
		config = config || {};
		//console.log(config);
		if (config.title) {
			this.title = config.title;
		} else {
			this.title = 'Alarm Commands';
		}
		
		if (config.commandView) { console.log(config.commandView);
			this.commandView = config.commandView;
		} else {
			this.commandView = false;
		}
		
		if (config.dealerView) {
			this.dealerView = config.dealerView;
		} else {
			this.dealerView = false;
		}

		this.sm = new Ext.grid.CheckboxSelectionModel({
			singleSelect: true
		});

		this.gridColumns = [
			//{header: 'AlarmCommand.id', width: 40, dataIndex: 'AlarmCommand.id', hidden: this.commandView},
			//{header: 'Alarm.id', width: 40, dataIndex: 'Alarm.id', hidden: this.commandView},
			{header: 'Alarm', width: 100, dataIndex: 'AlarmCommand.name'},
			{header: 'Start Time', width: 100, dataIndex: 'AlarmCommand.time_start', renderer: EMA.Util.timeRenderer},
			{header: 'End Time', width: 80, dataIndex: 'AlarmCommand.time_end', hidden: this.commandView},
			{header: 'Active', width: 30, dataIndex: 'AlarmCommand.active', renderer: EMA.Util.yesNoStatus},
			{header: 'Last Run', width: 100, dataIndex: 'AlarmCommand.last_run', renderer: EMA.Util.timeRenderer},
			{header: 'Modified', width: 150, dataIndex: 'AlarmCommand.modified', renderer: EMA.Util.dateTimeRenderer, hidden: this.commandView},
			{header: 'Created', width: 150, dataIndex: 'AlarmCommand.created', renderer: EMA.Util.dateTimeRenderer, hidden: this.commandView}
	    ];
		
	    if (this.commandView) {
	    	this.filters = new Ext.ux.grid.GridFilters({
		        encode: false,
		        filters: [
		        	{
			            type: 'numeric',
			            dataIndex: 'AlarmCommand.id'
			        }
				]
		    });
	    } else if (this.dealerView) {
	    	this.filters = new Ext.ux.grid.GridFilters({
		        encode: false,
		        filters: [
		        	{
			            type: 'numeric',
			            dataIndex: 'StaffMember.id'
			        }
				]
		    });
	    } else {
			this.filters = new Ext.ux.grid.GridFilters({
		        encode: false,
		        filters: [
		        	{
			            type: 'numeric',
			            dataIndex: 'Transaction.id'
			        }, {
						dataIndex: 'Transaction.approved',
						type: 'boolean'
					}, {
						dataIndex: 'Transaction.printed',
						type: 'boolean'
					}, {
						dataIndex: 'Transaction.transaction_type_id',
						type: 'list',
						options: EMA.Util.transactionTypes('list'),
				        phpMode: true
					}, {
						type: 'date',
						dataIndex: 'Transaction.created'
					}, {
						dataIndex: 'Account.firstname',
						type: 'string'
					}, {
						dataIndex: 'Account.lastname',
						type: 'string'
					}, {
						dataIndex: 'Account.alias',
						type: 'string'
					}
				]
		    });
	    }
	    
	    this.storeFields = [
			{name: 'AlarmCommand.name'},
			{name: 'AlarmCommand.time_start', type: 'date', dateFormat: 'Y-m-d H:i:s'},
			{name: 'AlarmCommand.time_end', type: 'date', dateFormat: 'Y-m-d H:i:s'},
			{name: 'AlarmCommand.active', type: 'boolean'},
			{name: 'AlarmCommand.last_run', type: 'date', dateFormat: 'Y-m-d H:i:s'},
			{name: 'AlarmCommand.modified', type: 'date', dateFormat: 'Y-m-d H:i:s'},
			{name: 'AlarmCommand.created', type: 'date', dateFormat: 'Y-m-d H:i:s'},
			{name: 'AlarmCommand.deleted', type: 'date', dateFormat: 'Y-m-d H:i:s'},
			{name: 'AlarmCommand.recurring', type: 'date', dateFormat: 'Y-m-d H:i:s'},
			{name: 'AlarmCommand.pid', type: 'date', dateFormat: 'Y-m-d H:i:s'}
		];
		
		this.store = new Ext.data.JsonStore({
			autoDestroy: true,
			url: '/alarm_commands',
			root: 'Alarm Commands',
			idProperty: 'alarm_command.id',
			autoLoad: false,
			remoteSort: true,
			fields: this.storeFields,
	        sortInfo: {
	            field: 'AlarmCommand.created',
	            direction: 'DESC'
	        }
		});
		
		this.tbarItems = [];
		
		if (!this.commandView && !this.dealerView) {
			this.filterEmptyText = 'Command';
			this.filterForm = new Ext.form.FormPanel({
				border: true,
				frame: false,
				labelWidth: 45,
				title: false,
				height: 32,
				width: 445,			        
		        bodyStyle: 'padding: 5px',
		        defaults: {
		            anchor: '0'
		        },
		        items: [
		            {
		                xtype: 'compositefield',
		                fieldLabel: 'Go',
		                msgTarget : 'side',
		                anchor    : '-20',
		                defaults: {
		                    flex: 1
		                },
		                items: [
		                      {
			                    emptyText: this.filterEmptyText,
						        id: 'transaction_list_filter',
						        xtype: 'textfield',
						        enableKeyEvents: true,
							    listeners: { 
							    	scope: this,
		                            keypress: {
		                                fn: function(field, e) {
		                                    if (e.getKey() == Ext.EventObject.ENTER) {
		                                    	this.onSubmit();
		                                    }
		                                }
		                            }
	                        	}
						      }, {
						        xtype:'button',
						        iconCls: 'beezid-action-search',
						        width: 60,
						        handler: this.onSubmit,
		                        scope: this,
		                        text: 'Filter',
		            			tooltip: 'Filter using the selected option'
						      }, {
						        xtype:'button',
						        iconCls: 'beezid-action-refresh',
						        width: 60,
						        handler: this.onReset,
		                        scope: this,
		                        text: 'Reset',
		            			tooltip: 'Reset the filters'
						      }
		                ]
		            }            
		        ]
		    });
		    
		    this.tbarItems = [
	            this.filterForm
			];
		}
		
		this.tbarItems = this.tbarItems.concat([
			'->', 
			{
				text: 'Logged in as  <span style="font-size: 14px;"><b>xxx</b></span>  (Log Out)',
				iconCls: 'ema-action-logout',
				listeners: {
					click: function() {
						location.href = '/logout';
					}
				}
			}
	    ]);
		
	    Ext.apply(this, {
	    	limit: 30,
	        tbar: new Ext.Toolbar({
	            items: this.tbarItems
	        }),
	        initLoad: !this.commandView && !this.dealerView
	    });
	    EMA.Alert.grid.AlarmCommands.superclass.constructor.apply(this, arguments);
	},
	amountRenderer: function(val, metadata, record) {
		metadata.attr = 'style="text-align:right;"';

		if (record.data['Transaction.approved'] != 1) {
	    	metadata.css += 'x-grid3-row-yellow';
	    }
	    
		if (record.data['Transaction.transaction_type_id'] == 1) {
			return '<span style="color:green;">+' + Ext.util.Format.usMoney(val) + '</span>';
		} else {
			return '<span style="color:red;">-' + Ext.util.Format.usMoney(val) + '</span>';
		}
    },
	staffMemberRenderer: function(val, metadata, record) {
		return record.data['StaffMember.firstname'] + ' ' + record.data['StaffMember.lastname'];
    },
    onPlayerRowClick: function(id) {
    	var filter = this.filters.filters.get('Account.id');
		if (filter) {
			filter.setValue({eq: id});
			filter.setActive(true);
		}
    },
    onDealerRowClick: function(id) {
    	var filter = this.filters.filters.get('StaffMember.id');
		if (filter) {
			filter.setValue({eq: id});
			filter.setActive(true);
		}
    },
    onAlarmRowClick: function(id) {
    	console.log('inside onAlarmRowClick. id is: '+id);
    	console.log(this.store.lastOptions);
    	var lastOpts = this.store.lastOptions;
    	Ext.apply(lastOpts.params, {
    	    id: id
    	});
    	///xxxxxxxxxxxxxxxxx
    	/*
    	var record = this.grid.getSelectionModel().getSelected();
    	if (record && record.id) {
    		var id = record.id,
                    g = this.grid,
                    s = g.getStore();
            // callback to reload the grid, fire
            var callback = function(){
                    s.reload();
             };

            var d = new Beezid.CatalogItem.Category.Edit({
                    callback: callback,
                    recordId: record.data['CatalogItemCategory.id'],
                    ownerModule: this.ownerModule,
                    scope: this
            });
            d.show();
    }
    */
    ///xxxxxxxxxxxxxx
    	
    	this.store.reload();
    	console.log(this.store);
    	/*var filter = this.filters.filters.get('StaffMember.id');
		if (filter) {
			filter.setValue({eq: id});
			filter.setActive(true);
		}*/
    },
	onSubmit: function() {
		var userFilter = Ext.getDom('transaction_list_filter').value.trim();
		if (userFilter != this.filterEmptyText) {
			this.filters.clearFilters();
			if ((/^\d*$/.test(userFilter))) {			
				var filter = this.filters.filters.get('Transaction.id');
				if (filter) {
					filter.setValue({eq: userFilter});
					filter.setActive(true);
				}
			} else if ((/ /.test(userFilter))) {	
				var userFilter = userFilter.split(' ');
				var filter = this.filters.filters.get('Account.firstname');
				if (filter) {
					filter.setValue(userFilter[0]);
					filter.setActive(true);
				}
				if (userFilter[1]) {
					var filter = this.filters.filters.get('Account.lastname');
					if (filter) {
						filter.setValue(userFilter[1]);
						filter.setActive(true);
					}
				}
			} else {
				var filter = this.filters.filters.get('Account.alias');
				if (filter) {
					filter.setValue(userFilter);
					filter.setActive(true);
				}
			}
		}
	},
	onReset: function() {
		Ext.getCmp('transaction_list_filter').setValue('');
		this.filters.clearFilters();
	},
	printTransaction: function() {
		var record = this.getSelectionModel().getSelected();

		if(record && record.id) {
			if (record.data['Transaction.approved'] == 0) {
				Ext.Msg.show({
					title: 'Error',
					msg: 'This transaction was not approved.',
					buttons: Ext.Msg.OK
				});
			} else {
				window.open('/transactions/print_any_receipt/' + record.id);
			}
		}
	}
});
