EMA.Alert.grid.Alarms = Ext.extend(EMA.GridPanel, {
	constructor : function(config) {
		config = config || {};
		
		if (config.title) {
			this.title = config.title;
		} else {
			this.title = 'Alarms Listing';
		}
		
		if (config.alarmsGrid) {
			this.alarmsGrid = config.alarmsGrid;
		} else {
			this.alarmsGrid = false;
		}
		
		this.alarmForm = new Ext.Window({
			title: 'Alarm',
	        //applyTo: 'action-alarm',
	        layout: 'fit',
	        width: 400,
	        height: 220,
	        closeAction: 'hide',
	        plain: true,
	        maximizable: false,
	        modal: true,
	        shim: false,
	        items: []
	    });
	    
		//this.sm = new Ext.grid.CheckboxSelectionModel({
		this.sm = new Ext.grid.RowSelectionModel({
			singleSelect: true,
		});
		
		this.gridColumns = [
			{header: 'Alarm', width: 150, dataIndex: 'Alarm.name'},
			{header: 'Last Run', width: 150, dataIndex: 'Alarm.last_run'},
			{header: 'Start', width: 150, dataIndex: 'Alarm.time_start'}
	    ];
		this.filters = new Ext.ux.grid.GridFilters({
	        encode: false,
	        filters: [
	        	{
		            type: 'numeric',
		            dataIndex: 'Alarm.id'
		        }, {
					dataIndex: 'Alarm.name',
					type: 'string'
				}, {
					dataIndex: 'Alarm.last_run',
					type: 'string'
				}, {
					dataIndex: 'Alarm.time_start',
					type: 'string'
				}
			]
	    });
	    
	    this.storeFields = [
			{name: 'Alarm.id'},
			{name: 'Alarm.name'},
			{name: 'Alarm.last_run', type: 'date', dateFormat: 'Y-m-d H:i:s'},
			{name: 'Alarm.time_start', type: 'date', dateFormat: 'Y-m-d H:i:s'}
		];
		
		
		this.store = new Ext.data.JsonStore({
			autoDestroy: true,
			url: '/alarms',
			root: 'Alarm',
			idProperty: 'Alarm.id',
			autoLoad: false,
			remoteSort: true,
			fields: this.storeFields,
	        sortInfo: {
	            field: 'Alarm.modified',
	            direction: 'DESC'
	        }
		});
		
		this.filterEmptyText = 'Command  . . .';
		this.filterForm = new Ext.form.FormPanel({
			border: true,
			frame: false,
			labelWidth: 71,
			title: false,
			height: 32,
			width: 440,			        
	        bodyStyle: 'padding: 5px',
	        defaults: {
	            anchor: '0'
	        },
	        items: [
	            {
	                xtype: 'compositefield',
	                fieldLabel: 'Run command',
	                msgTarget : 'side',
	                anchor    : '-20',
	                defaults: {
	                    flex: 1
	                },
	                items: [
	                      {
		                    emptyText: this.filterEmptyText,
					        id: 'run_command_box',
					        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: 'Go',
	            			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,
			{
				text: '<strong><u>D</u></strong>eactivate',
				iconCls: 'ema-action-stop',
				listeners: {
					click: function() {
						this.deposit();
					},
					scope: this
				}
			}
		];
	    
		this.tbarItems = this.tbarItems.concat([
			'-',
			{
				text: 'Add an alarm',
				iconCls: 'ema-action-add',
				listeners: {
					click: function() {
						this.addAlarm();
					},
					scope: this
				}
			}
	    ]);
		
	    Ext.apply(this, {
	    	limit: 30,
	        tbar: new Ext.Toolbar({
	            items: this.tbarItems
	        }),
	        keydownFunction: function(key) {
				if (key == Ext.EventObject.D) {
        			this.deposit();
        		} else if (key == Ext.EventObject.W) {
        			this.withdraw();
        		} 
			},
			rowclickFunction: function(grid, rowIndex, e) {
				if (this.commandsGrid) {
					var record = grid.getSelectionModel().getSelected();
					if(record && record.id) {
						this.commandsGrid.onPlayerRowClick(record.id);
					}
				}
            },
            onRowdblclick: function(config, grid, rowIndex, e) {
            	
				var record = grid.getSelectionModel().getSelected();
				if (record && record.id) {
					console.log(record);
	            	config.commandsList.onAlarmRowClick(record.id);
				}
            }
	    });
	    
	    EMA.Alert.grid.Alarms.superclass.constructor.apply(this, arguments);      
	},
    balanceRenderer: function(val, metadata) {
		metadata.attr = 'style="text-align:right;"';
	
		if (val > 0) {
	    	return '<span style="color:green;">' + Ext.util.Format.usMoney(val) + '</span>';
	    } else if (val < 0) {
	    	return '<span style="color:red;">' + Ext.util.Format.usMoney(val) + '</span>';
	    } else {
	    	return '<span style="color:blue;">' + Ext.util.Format.usMoney(val) + '</span>';
	    }
    },
	deposit: function() {
		if (this.getSelectionModel().getSelected()) {
			var s = this.getStore();
			var sm = this.getSelectionModel();
			
			if (this.commandsGrid) {
				var ts = this.commandsGrid.getStore();
			}
			var callback = function(id) {
				if (id) {
					// callback to select record after load
					var reloadCb = function(){
						sm.selectRecords([s.getById(id)]);
					};
					
					s.reload({callback: reloadCb});
					if (ts) {
						ts.reload();
					}
				}
			};
			this.transactionForm.removeAll();
			this.transactionForm.add(new EMA.Alert.form.Transaction({
	            id: 'account-withdrawal-form',
				title: 'Deposit',
				txnType: 'deposit',
				url: '/accounts/deposit',
				parentWindow: this.transactionForm,
				data: this.getSelectionModel().getSelected().data,
				callback: callback
			}));
			this.transactionForm.show();
		}
	},
	withdraw: function() {
		if (this.getSelectionModel().getSelected()) {
			var s = this.getStore();
			var sm = this.getSelectionModel();
			if (this.commandsGrid) {
				var ts = this.commandsGrid.getStore();
			}
			var callback = function(id){
				if (id) {
					// callback to select record after load
					var reloadCb = function(){
						sm.selectRecords([s.getById(id)]);
					};
					
					s.reload({callback: reloadCb});
					if (ts) {
						ts.reload();
					}
				}
			};
			this.transactionForm.removeAll();
			this.transactionForm.add(new EMA.Alert.form.Transaction({
	            id: 'account-withdrawal-form',
				title: 'Withdraw',
				txnType: 'withdraw',
				url: '/accounts/withdraw',
				parentWindow: this.transactionForm,
				data: this.getSelectionModel().getSelected().data,
				callback: callback
			}));
			this.transactionForm.show();
		}
	},
	onSubmit: function() {
		var userFilter = Ext.getDom('run_command_box').value.trim();
		if (userFilter != this.filterEmptyText) {
			this.filters.clearFilters();
			if ((/^\d*$/.test(userFilter))) {			
				var filter = this.filters.filters.get('Account.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('run_command_box').setValue('');
		this.filters.clearFilters();
	},
	addAlarm: function() {
		var s = this.getStore();
		var sm = this.getSelectionModel();
		var parentWindow = this.alarmForm;
		var callback = function(id) {
			if (id) {
				// callback to select record after load
				var reloadCb = function() {
					sm.selectRecords([s.getById(id)]);
				};
				
				s.reload({callback: reloadCb});
				parentWindow.hide();
				
				Ext.Msg.show({
					title: 'Success',
					msg: 'Acount <span style="font-size: 16px;"><b>#' + id + '</b></span> was created.',
					buttons: Ext.Msg.OK
				});
			}
		};
		this.alarmForm.removeAll();
		this.alarmForm.add(new EMA.Alert.form.Alarm({
			title: 'Add a new alarm',
			populate: false,
			url: '/alarms/add',
			parentWindow: this.alarmForm,
			callback: callback
		}));
		this.alarmForm.show();
	},
	editPlayer: function() {
		if (this.getSelectionModel().getSelected()) {
			var s = this.getStore();
			var sm = this.getSelectionModel();
			var parentWindow = this.playerForm;
			var callback = function(id) {
				if (id) {
					// callback to select record after load
					var reloadCb = function() {
						sm.selectRecords([s.getById(id)]);
					};
					
					s.reload({callback: reloadCb});
					parentWindow.hide();
					
					Ext.Msg.show({
						title: 'Success',
						msg: 'Acount <span style="font-size: 16px;"><b>#' + id + '</b></span> was updated.',
						buttons: Ext.Msg.OK
					});
				}
			};
			this.playerForm.removeAll();
			this.playerForm.add(new PPC.Accounting.form.Player({
				title: 'Edit a player',
				populate: true,
				url: '/accounts/edit',
				parentWindow: this.playerForm,
				data: this.getSelectionModel().getSelected().data,
				callback: callback
			}));
			this.playerForm.show();
		}
	}
});
