Tasks.js 35.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
/**
 * @class SimpleTasks.controller.Tasks
 * @extends Ext.app.Controller
 */
Ext.define('SimpleTasks.controller.Tasks', {
    extend: 'Ext.app.Controller',

    models: ['Task'],
    stores: ['Tasks'],

    views: [
        'tasks.Grid',
        'tasks.Form',
        'tasks.EditWindow',
        'tasks.DefaultTimeWindow',
        'tasks.ReminderWindow',
        'tasks.ContextMenu'
    ],

    refs: [
        {
            ref: 'listTree',
            selector: 'listTree'
        },
        {
            ref: 'taskForm',
            selector: 'taskForm'
        },
        {
            ref: 'taskGrid',
            selector: 'taskGrid'
        },
        {
            ref: 'tasksToolbar',
            selector: 'tasksToolbar'
        },
        {
            ref: 'taskEditWindow',
            selector: 'taskEditWindow',
            xtype: 'taskEditWindow',
            autoCreate: true
        },
        {
            ref: 'defaultTimeWindow',
            selector: 'defaultTimeWindow',
            xtype: 'defaultTimeWindow',
            autoCreate: true
        },
        {
            ref: 'reminderWindow',
            selector: 'reminderWindow',
            xtype: 'reminderWindow',
            forceCreate: true
        },
        {
            ref: 'contextMenu',
            selector: 'tasksContextMenu',
            xtype: 'tasksContextMenu',
            autoCreate: true
        }
    ],

    init: function() {
        var me = this;
        me.control(
            {
                'taskForm textfield': {
                    specialkey: me.handleSpecialKey
                },
                '[iconCls=tasks-new]': {
                    click: me.focusTaskForm
                },
                '#delete-task-btn': {
                    click: me.handleDeleteClick
                },
                '#delete-task-item': {
                    click: me.handleDeleteClick
                },
                '#mark-complete-item': {
                    click: me.markComplete
                },
                '#mark-complete-btn': {
                    click: me.markComplete
                },
                '#mark-active-item': {
                    click: me.markActive
                },
                '#mark-active-btn': {
                    click: me.markActive
                },
                '#show-all-btn': {
                    click: me.filterAll
                },
                '#show-active-btn': {
                    click: me.filterActive
                },
                '#show-complete-btn': {
                    click: me.filterComplete
                },
                '#edit-task-item': {
                    click: me.handleEditItemClick
                },
                'taskGrid': {
                    recordedit: me.updateTask,
                    deleteclick: me.handleDeleteIconClick,
                    editclick: me.handleEditIconClick,
                    reminderselect: me.setReminder,
                    itemmouseenter: me.showActions,
                    itemmouseleave: me.hideActions,
                    selectionchange: me.toggleButtons,
                    columnresize: me.syncTaskFormFieldWidth,
                    itemcontextmenu: me.showContextMenu
                },
                'tasksToolbar': {
                    afterrender: me.initShowAll
                },
                'taskEditWindow [name=has_reminder]': {
                    change: me.toggleReminderFields
                },
                '#cancel-task-edit-btn': {
                    click: me.hideEditWindow
                },
                '#save-task-edit-btn': {
                    click: me.handleSaveTaskClick
                },
                'taskEditWindow [name=reminder_date]': {
                    change: me.syncReminderField
                },
                'taskEditWindow [name=reminder_time]': {
                    change: me.syncReminderField
                },
                '#toggle-complete-btn': {
                    click: me.toggleCompleteField
                },
                '#delete-task-window-btn': {
                    click: me.deleteTaskAndCloseEditWindow
                },
                'defaultTimeWindow [name=default_time]': {
                    
                },
                '#cancel-default-time-edit-btn': {
                    click: me.hideDefaultTimeWindow
                },
                '#save-default-time-btn': {
                    click: me.saveDefaultTime
                },
                '[cls=snooze-btn]': {
                    click: me.snooze
                },
                '[cls=dismiss-reminder-btn]': {
                    click: me.dismissReminder
                }
            }
        );

        me.initReminderInterval();
    },

    /**
     * Handles a "specialkey" event on an field on the task form.
     * Creates a new task if the enter key is pressed.
     * @param {Ext.form.field.Text} field
     * @param {Ext.EventObject} e
     */
    handleSpecialKey: function(field, e) {
        if(e.getKey() === e.ENTER) {
            this.newTask();
        }
    },

    /**
     * Creates a new task based on the data currently contained in the task form.
     * Saves the new task to the server and adds it to the task list view.
     */
    newTask: function() {
        var me = this,
            form = me.getTaskForm(),
            basicForm = form.getForm(),
            formEl = form.getEl(),
            titleField = form.getForm().findField('title'),
            task = Ext.create('SimpleTasks.model.Task');

        // require title field to have a value
        if(!titleField.getValue()) {
            return;
        }

        // update the new task record with the data from the form.
        basicForm.updateRecord(task);

        // try to blur all of this form's items to make sure that the user can't type into a field while saving
        form.items.each(function(item) {
            var inputEl = item.getEl().down('input')
            if(inputEl) {
                inputEl.blur();
            }
        });

        // mask the form element while saving
        formEl.mask('saving . . .');
        // save the task to the server
        task.save({
            success: function(task, operation) {
                me.getTasksStore().add(task);
                me.refreshFiltersAndCount();
                me.getTasksStore().sort();
                titleField.reset();
                titleField.focus();
                formEl.unmask();
            },
            failure: function(task, operation) {
                var error = operation.getError(),
                    msg = Ext.isObject(error) ? error.status + ' ' + error.statusText : error;

                Ext.MessageBox.show({
                    title: 'Add Task Failed',
                    msg: msg,
                    icon: Ext.Msg.ERROR,
                    buttons: Ext.Msg.OK
                });
                formEl.unmask();
            }
        });
    },

    /**
     * Handles the task list's "recordedit" event.
     * Updates the task on the server whenever a task is updated using the task grid's cell editor
     * @param {SimpleTasks.model.Task} task    The task record that was edited
     */
    updateTask: function(task) {
        var me = this;

        if(task.modified.done === false) {
            task.set('reminder', null);
        }
        task.save({
            success: function(task, operation) {
                me.refreshFiltersAndCount();
                me.getTasksStore().sort();
            },
            failure: function(task, operation) {
                var error = operation.getError(),
                    msg = Ext.isObject(error) ? error.status + ' ' + error.statusText : error;

                Ext.MessageBox.show({
                    title: 'Update Task Failed',
                    msg: msg,
                    icon: Ext.Msg.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        });
    },

    /**
     * Handles a click on a delete icon in the task grid.
     * @param {Ext.grid.View} view
     * @param {Number} rowIndex
     * @param {Number} colIndex
     * @param {Ext.grid.column.Action} column
     * @param {EventObject} e
     */
    handleDeleteIconClick: function(view, rowIndex, colIndex, column, e) {
        this.deleteTask(this.getTasksStore().getAt(rowIndex));
    },

    /**
     * Handles a click on the "delete task" button or context menu item
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    handleDeleteClick: function(button, e) {
        this.deleteTask(this.getTaskGrid().getSelectionModel().getSelection()[0]);
    },

    /**
     * Deletes the task from the server and updates the view.
     * @param {SimpleTasks.model.Task} task
     * @param {Function} successCallback           A function to call after the task has been deleted successfully
     */
    deleteTask: function(task, successCallback) {
        var me = this;
        
        Ext.Msg.show({
            title: 'Delete Task?',
            msg: 'Are you sure you want to delete this task?',
            buttons: Ext.Msg.YESNO,
            fn: function(response) {
                if(response === 'yes') {
                    task.destroy({
                        success: function(task, operation) {
                            me.getTasksStore().remove(task);
                            me.refreshFiltersAndCount();
                            if(successCallback) {
                                successCallback();
                            }
                        },
                        failure: function(task, operation) {
                            var error = operation.getError(),
                                msg = Ext.isObject(error) ? error.status + ' ' + error.statusText : error;

                            Ext.MessageBox.show({
                                title: 'Delete Task Failed',
                                msg: msg,
                                icon: Ext.Msg.ERROR,
                                buttons: Ext.Msg.OK
                            });
                        }
                    });
                }
            }
        });
    },

    /**
     * Refreshes the task grid's list filter, and the task counts in the list tree
     */
    refreshFiltersAndCount: function() {
        // refresh the task filters
        this.getTaskGrid().refreshFilters();
        // refresh the lists list view so that the task counts will be correct
        this.getListTree().refreshView();
    },

    /**
     * Handles a click on the "Edit" context menu item
     * @param {Ext.menu.Item} item
     * @param {EventObject} e
     */
    handleEditItemClick: function(item, e) {
        this.showEditWindow(this.getContextMenu().getTask());
    },

    /**
     * Handles a click on the "Edit Task" action column
     * @param {Ext.grid.View} view
     * @param {Number} rowIndex
     * @param {Number} colIndex
     * @param {Ext.grid.column.Action} column
     * @param {EventObject} e
     */
    handleEditIconClick: function(view, rowIndex, colIndex, column, e) {
        this.showEditWindow(view.getRecord(view.findTargetByEvent(e)));
    },

    /**
     * Handles the task grid's "selectionchange" event.
     * Disables or enables the task-related toolbar buttons depending on whether or not there is a selection.
     * @param {Ext.selection.RowModel} selModel
     * @param {SimpleTasks.model.Task[]} tasks
     */
    toggleButtons: function(selModel, tasks) {
        var deleteTaskBtn = Ext.getCmp('delete-task-btn'),
            markCompleteBtn = Ext.getCmp('mark-complete-btn'),
            markActiveBtn = Ext.getCmp('mark-active-btn');

        if(tasks.length === 0) {
            deleteTaskBtn.disable();
            markCompleteBtn.disable();
            markActiveBtn.disable();
        } else {
            deleteTaskBtn.enable();
            markCompleteBtn.enable();
            markActiveBtn.enable();
        }
    },

    /**
     * Handles a click on the "New Task" button or context menu item
     * focuses the title field on the new task form
     * @param {Ext.Component} component
     * @param {Ext.EventObject} e
     */
    focusTaskForm: function(component, e) {
        this.getTaskForm().query('[name=title]')[0].focus();
    },

    /**
     * Handles a click on the "Mark Complete" button or menu item
     * Sets the selected task's "done" field to true
     * @param {Ext.Component} component
     * @param {Ext.EventObject} e
     */
    markComplete: function(component, e) {
        var contextMenu = this.getContextMenu(),
            task = contextMenu.isVisible() ? contextMenu.getTask() : this.getTaskGrid().getSelectionModel().getSelection()[0];

        task.set('done', true);
        task.set('reminder', null);
        task.save({
            failure: function(task, operation) {
                var error = operation.getError(),
                    msg = Ext.isObject(error) ? error.status + ' ' + error.statusText : error;

                Ext.MessageBox.show({
                    title: 'Mark Complete Failed',
                    msg: msg,
                    icon: Ext.Msg.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        });
        this.refreshFiltersAndCount();
    },

    /**
     * Handles a click on the "Mark Active" button
     * Sets the selected task's "done" field to false
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    markActive: function(button, e) {
        var contextMenu = this.getContextMenu(),
            task = contextMenu.isVisible() ? contextMenu.getTask() : this.getTaskGrid().getSelectionModel().getSelection()[0];

        task.set('done', false);
        task.save({
            failure: function(task, operation) {
                var error = operation.getError(),
                    msg = Ext.isObject(error) ? error.status + ' ' + error.statusText : error;

                Ext.MessageBox.show({
                    title: 'Mark Active Failed',
                    msg: msg,
                    icon: Ext.Msg.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        });
        this.refreshFiltersAndCount();
    },

    /**
     * Handles the task grid columnresize event.
     * Synchronizes the width the column's associated form field with the width of the column
     * @param {Ext.grid.header.Container} headerContainer
     * @param {Ext.column.Column} column
     * @param {Number} width The new column width
     */
    syncTaskFormFieldWidth: function(headerContainer, column, width) {
        var field = this.getTaskForm().query('[name=' + column.dataIndex + ']')[0];
        if (field) {
            field.setWidth(width - 5);
        }
    },

    /**
     * Handles a click on the "Show All" button. Removes any filter on the done field so that all tasks will be displayed
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    filterAll: function(button, e) {
        var tasksStore = this.getTasksStore(),
            filters = tasksStore.filters.getRange(0, tasksStore.filters.getCount() - 1),
            filterCount = filters.length,
            i = 0;

        if(button.pressed) {
            tasksStore.clearFilter();
            for(; i < filterCount; i++) {
                if(filters[i].property === 'done') {
                    filters.splice(i, 1);
                    filterCount --;
                }
            }
            tasksStore.filter(filters);
        } else {
            button.toggle();
        } 
    },

    /**
     * Handles a click on the "Show Active" button. Filters tasks by done = false
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    filterActive: function(button, e) {
        var tasksStore = this.getTasksStore(),
            filters = tasksStore.filters.getRange(0, tasksStore.filters.getCount() - 1),
            filterCount = filters.length,
            i = 0;

        if(button.pressed) {
            tasksStore.clearFilter();
            for(; i < filterCount; i++) {
                if(filters[i].property === 'done') {
                    filters.splice(i, 1);
                    filterCount --;
                }
            }
            filters.push({ property: 'done', value: false });
            this.getTasksStore().filter(filters);
        } else {
            button.toggle();
        } 
    },

    /**
     * Handles a click on the "Show Complete" button. Filters tasks by done = true.
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    filterComplete: function(button, e) {
        var tasksStore = this.getTasksStore(),
            filters = tasksStore.filters.getRange(0, tasksStore.filters.getCount() - 1),
            filterCount = filters.length,
            i = 0;

        if(button.pressed) {
            tasksStore.clearFilter();
            for(; i < filterCount; i++) {
                if(filters[i].property === 'done') {
                    filters.splice(i, 1);
                    filterCount --;
                }
            }
            filters.push({ property: 'done', value: true });
            this.getTasksStore().filter(filters);
        } else {
            button.toggle();
        } 
    },

    /**
     * Handles the tasks toolbar's render event
     * Initializes the "Show All" Button to the pressed state
     * @param {SimpleTasks.view.Toolbar} toolbar
     */
    initShowAll: function(toolbar) {
        toolbar.getComponent('show-all-btn').toggle();
    },

    /**
     * Handles a mouseenter event on a task grid item.
     * Shows the item's action icons.
     * @param {Ext.grid.View} view
     * @param {SimpleTasks.model.Task} task
     * @param {HTMLElement} node
     * @param {Number} rowIndex
     * @param {Ext.EventObject} e
     */
    showActions: function(view, task, node, rowIndex, e) {
        var icons = Ext.DomQuery.select('.x-action-col-icon', node);
        Ext.each(icons, function(icon){
            Ext.get(icon).removeCls('x-hidden');
        });
    },

    /**
     * Handles a mouseleave event on a task grid item.
     * Hides the item's action icons.
     * @param {Ext.grid.View} view
     * @param {SimpleTasks.model.Task} task
     * @param {HTMLElement} node
     * @param {Number} rowIndex
     * @param {Ext.EventObject} e
     */
    hideActions: function(view, task, node, rowIndex, e) {
        var icons = Ext.DomQuery.select('.x-action-col-icon', node);
        Ext.each(icons, function(icon){
            Ext.get(icon).addCls('x-hidden');
        });
    },

    /**
     * Handles the task grid's itemcontextmenu event
     * Shows the task context menu.
     * @param {Ext.grid.View} view
     * @param {SimpleTasks.model.Task} task
     * @param {HTMLElement} node
     * @param {Number} rowIndex
     * @param {Ext.EventObject} e
     */
    showContextMenu: function(view, task, node, rowIndex, e) {
        var contextMenu = this.getContextMenu(),
            markCompleteItem = Ext.getCmp('mark-complete-item'),
            markActiveItem = Ext.getCmp('mark-active-item');

        if(task.get('done')) {
            markCompleteItem.hide();
            markActiveItem.show();
        } else {
            markCompleteItem.show();
            markActiveItem.hide();
        }
        contextMenu.setTask(task);
        contextMenu.showAt(e.getX(), e.getY());
        e.preventDefault();
    },

    /**
     * Shows the "Edit Task" window
     * @param {SimpleTasks.model.Task} task       the task to edit
     */
    showEditWindow: function(task) {
        var me = this,
            taskEditWindow = me.getTaskEditWindow(),
            form =  taskEditWindow.down('form').getForm(),
            reminderCheckbox = form.findField('has_reminder'),
            dateField = form.findField('reminder_date'),
            timeField = form.findField('reminder_time'),
            reminder = task.get('reminder');

        // Set the tasks title as the title of the edit window
        taskEditWindow.setTitle('Edit Task - ' + task.get('title'));
        // load the task data into the form
        taskEditWindow.down('form').loadRecord(task);
        // set the text of the toggle-complete button depending on the tasks "done" value
        Ext.getCmp('toggle-complete-btn').setText(task.get('done') ? 'Mark Active' : 'Mark Complete');
        taskEditWindow.show();

        if(task.get('reminder')) {
            // if the task already has a reminder set check the reminder checkbox and populate the reminder date and reminder time fields
            reminderCheckbox.setValue(true);
            dateField.setValue(Ext.Date.clearTime(reminder, true));
            timeField.setValue(Ext.Date.format(reminder, timeField.format)); 
        } else {
            // if the task does not have a reminder set uncheck the reminder checkbox and set the reminder date and time fields to null
            reminderCheckbox.setValue(false);
            dateField.setValue(null);
            timeField.setValue(null); 
        }

        if(task.get('done')) {
            // if the task is done disable the reminder checkbox (reminders cannot be set on completed tasks)
            reminderCheckbox.disable();
        } else {
            reminderCheckbox.enable();
        }

    },

    /**
     * Handles a click on the "Edit Task" window's cancel button
     * Hides the "Edit Task" window
     * @param {Ext.Button} button
     * @param {Ext.EventObject} e
     */
    hideEditWindow: function(button, e) {
        this.getTaskEditWindow().close();
    },

    /**
     * Handles the change event on the task edit window's "has_reminder" checkbox
     * Toggles the visibility of the reminder date and time fields
     * @param {Ext.form.field.Checkbox} checkbox
     * @param {Boolean} newValue
     * @param {Boolean} oldValue
     */
    toggleReminderFields: function(checkbox, newValue, oldValue) {
        var taskEditWindow = this.getTaskEditWindow(),
            windowEl = taskEditWindow.getEl(),
            form = taskEditWindow.down('form').getForm(),
            task = form.getRecord(),
            dateField = form.findField('reminder_date'),
            timeField = form.findField('reminder_time'),
            defaultTimeDate, defaultTimeMilliseconds;
        
        if(newValue) { // if the "has reminder" checkbox was checked
            windowEl.mask('loading');
            // get the default reminder time from the server or cache
            this.getDefaultReminderTime(function(defaultTime) {
                // enable the date and time fields
                dateField.enable();
                timeField.enable();
                if(!dateField.getValue()) {
                    // if the reminder date has not already been set, default the reminder date to the task's due date
                    // or the current date if the task does not have a due date
                    dateField.setValue(task.get('due') || Ext.Date.clearTime(new Date()));
                    timeField.setValue(defaultTime);
                }
                // set the form's hidden reminder field by combining the reminder date and time fields
                defaultTimeDate = timeField.getValue();
                defaultTimeMilliseconds = defaultTimeDate - Ext.Date.clearTime(defaultTimeDate, true);
                form.findField('reminder').setValue(new Date(dateField.getValue().getTime() + defaultTimeMilliseconds));
                windowEl.unmask();
            });
        } else { // if the "has reminder" checkbox was unchecked
            // nullify the form's hidden reminder field and disable the reminder date and time fields
            form.findField('reminder').setValue(null);
            dateField.disable();
            timeField.disable();
        }
    },

    /**
     * Handles a click on the "Task Edit" window's save button.
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    handleSaveTaskClick: function(button, e) {
        this.saveEditWindow();
    },

    /**
     * Updates the task record with the form data from the edit window and saves the task to the server.
     */
    saveEditWindow: function() {
        var taskEditWindow = this.getTaskEditWindow(),
            windowEl = taskEditWindow.getEl(),
            form = taskEditWindow.down('form').getForm(),
            task = form.getRecord();

        if(form.isValid()) {
            windowEl.mask('saving');
            form.updateRecord(task);
            if(task.modified.done === false) {
                task.set('reminder', null);
            }
            task.save({
                success: function(task, operation) {
                    windowEl.unmask();
                    taskEditWindow.close();
                },
                failure: function(task, operation) {
                    var error = operation.getError(),
                       msg = Ext.isObject(error) ? error.status + ' ' + error.statusText : error;

                    Ext.MessageBox.show({
                        title: 'Edit Task Failed',
                        msg: msg,
                        icon: Ext.Msg.ERROR,
                        buttons: Ext.Msg.OK
                    });
                    windowEl.unmask();
                }
            })
        } else {
            Ext.Msg.alert('Invalid Data', 'Please correct form errors');
        }
    },

    /**
     * Syncronizes the value of the edit window's hidden reminder field whenever "reminder_date", or "reminder_time" is changed
     * @param {Ext.form.field.Picker} field     the date or time picker
     * @param {Date} oldValue
     * @param {Date} newValue
     */
    syncReminderField: function(field, oldValue, newValue) {
        var form = this.getTaskEditWindow().down('form').getForm(),
            reminderField = form.findField('reminder'),
            date = form.findField('reminder_date').getValue(),
            timeDate = form.findField('reminder_time').getValue(),
            time, reminderDate;

        if(date && timeDate) {
            time = timeDate - Ext.Date.clearTime(timeDate, true),
            reminderDate = new Date(date.getTime() + time);
            reminderField.setValue(reminderDate); 
        }
    },

    /**
     * Toggles the edit window's "done" field to true when the "Mark Complete" or "Mark Active" button on the edit window is clicked
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    toggleCompleteField: function(button, e) {
        var taskEditWindow = this.getTaskEditWindow(),
            doneField = taskEditWindow.down('form').getForm().findField('done');

        if(doneField.getValue() === 'true') {
            doneField.setValue(false);
        } else {
            doneField.setValue(true);
        }
        this.saveEditWindow();
    },

    /**
     * Handles a click on the "Delete" button on the edit window.
     * Deletes the task and closes the edit window
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    deleteTaskAndCloseEditWindow: function(button, e) {
        var me = this,
            taskEditWindow = me.getTaskEditWindow(),
            task = taskEditWindow.down('form').getRecord();

        me.deleteTask(task, function() {
            me.getTaskEditWindow().close();
        });
    },

    /**
     * Handles the Task Grid's `reminderselect` event
     * Sets a task's reminder
     * @param {SimpleTasks.model.Task} task    the underlying record of the row that was clicked to show the reminder menu
     * @param {String|Number} value      The value that was selected
     */
    setReminder: function(task, value) {
        var me = this,
            defaultTimeWindow = me.getDefaultTimeWindow(),
            defaultTimeField = defaultTimeWindow.down('form').getForm().findField('default_time'),
            defaultTimeDate, defaultTimeMilliseconds;

        me.getDefaultReminderTime(function(defaultTime) {
            if(value === 'set') {
                // if the user selected "Set Default Time", show the default time window.
                defaultTimeField.setValue(defaultTime);
                defaultTimeWindow.show();
            } else {
                if(Ext.isNumber(value)) {
                    // if the user selected a reminder time, set the reminder by adding the user selected value to the due date
                    defaultTimeDate = Ext.Date.parse(defaultTime, defaultTimeField.format);
                    defaultTimeMilliseconds = defaultTimeDate - Ext.Date.clearTime(defaultTimeDate, true);
                    task.set('reminder', new Date(task.get('due').getTime() - (value * 86400000) + defaultTimeMilliseconds));
                } else {
                    // if the user selected "No Reminder" set the reminder field to null
                    task.set('reminder', null);
                }
                task.save({
                    failure: function(task, operation) {
                        var error = operation.getError(),
                           msg = Ext.isObject(error) ? error.status + ' ' + error.statusText : error;

                        Ext.MessageBox.show({
                            title: 'Set Reminder Failed',
                            msg: msg,
                            icon: Ext.Msg.ERROR,
                            buttons: Ext.Msg.OK
                        });
                    }
                });
            }
        });
    },

    /**
     * Gets the default reminder time and passes it to the callback function.
     * Retrieves default reminder time from the server on the first call, then caches it for future calls.
     * @param {Function} callback
     */
    getDefaultReminderTime: function(callback) {
        var me = this,
            defaultReminderTime;

        if(me.defaultReminderTime) {
            callback(me.defaultReminderTime);
        } else {
            me.defaultReminderTime = '8:00 AM'; // the default time if no value can be retrieved from storage
            if (SimpleTasksSettings.useLocalStorage) {
                defaultReminderTime = localStorage.getItem('SimpleTasks-defaultReminderTime');
                if (defaultReminderTime) {
                    me.defaultReminderTime = defaultReminderTime;
                }
                callback(me.defaultReminderTime);
            } else {
                Ext.Ajax.request({
                    url: 'php/config/read.php',
                    params: {
                        key: 'default.reminder.time'
                    },
                    success: function(response, options) {
                        var responseData = Ext.decode(response.responseText);
                        if(responseData.success && responseData.value) {
                            me.defaultReminderTime = responseData.value;
                        }
                        callback(me.defaultReminderTime);
                    },
                    failure: function(response, options) {
                        callback(me.defaultReminderTime);
                    }
                });
            }
        }
    },

    /**
     * Hides the default reminder time window when the cancel button is clicked
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    hideDefaultTimeWindow: function(button, e) {
        this.getDefaultTimeWindow().close();
    },

    /**
     * Saves the default reminder time to the server when the OK button is clicked
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    saveDefaultTime: function(button, e) {
        var me = this,
            defaultTimeWindow = me.getDefaultTimeWindow(),
            windowEl = defaultTimeWindow.getEl(),
            time = defaultTimeWindow.down('form').getForm().findField('default_time').getRawValue();

        if (SimpleTasksSettings.useLocalStorage) {
            localStorage.setItem('SimpleTasks-defaultReminderTime', time);
            me.defaultReminderTime = time;
            defaultTimeWindow.close();
        } else {
            windowEl.mask('saving');
            Ext.Ajax.request({
                url: 'php/config/update.php',
                params: {
                    key: 'default.reminder.time',
                    value: time
                },
                success: function(response, options) {
                    var responseData = Ext.decode(response.responseText);

                    if(responseData.success) {
                        me.defaultReminderTime = time;
                        defaultTimeWindow.close();
                    } else {
                        Ext.MessageBox.show({
                            title: 'Set Default Time Failed',
                            msg: responseData.message,
                            icon: Ext.Msg.ERROR,
                            buttons: Ext.Msg.OK
                        });
                    }
                    windowEl.unmask();
                },
                failure: function(response, options) {
                    Ext.MessageBox.show({
                        title: 'Set Default Time Failed',
                        msg: response.status + ' ' + response.statusText,
                        icon: Ext.Msg.ERROR,
                        buttons: Ext.Msg.OK
                    });
                    windowEl.unmask();
                }
            });
        }
    },

    /**
     * Initializes checking for tasks that have passed their reminder date at 10 second intervals.
     */
    initReminderInterval: function() {
        var me = this,
            now, reminderDate;

        setInterval(function() {
            now = new Date();
            me.getTasksStore().each(function(task) {
                reminderDate = task.get('reminder');
                if(reminderDate && reminderDate < now && !task.get('done')) {
                    me.showReminderWindow(task);
                }
            });
        }, 10000);
    },

    /**
     * Shows the reminder window for a given task
     * @param {SimpleTasks.model.Task} task
     */
    showReminderWindow: function(task) {
        var reminderWindow = this.getReminderWindow(),
            reminderDetailsBox = reminderWindow.down('[cls=tasks-reminder-details]'),
            title = task.get('title');

        task.set('reminder', null);
        task.save({
            failure: function(task, operation) {
                var error = operation.getError(),
                   msg = Ext.isObject(error) ? error.status + ' ' + error.statusText : error;

                Ext.MessageBox.show({
                    title: 'Clear Reminder Failed',
                    msg: msg,
                    icon: Ext.Msg.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        });
        reminderWindow.setTask(task);
        reminderWindow.setTitle('Reminder - ' + title);
        reminderDetailsBox.update({
            title: title,
            due: task.get('due')
        });
        reminderWindow.show();
    },


    /**
     * Handles a click on the snooze button on the reminder window.
     * Sets the task's reminder date to the current date plus snooze time selected
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    snooze: function(button, e) {
        var reminderWindow = button.findParentByType('window'),
            task = reminderWindow.getTask(),
            snoozeMilliseconds = reminderWindow.down('[name=snooze_time]').getValue() * 60000,
            reminderDate = new Date(new Date().getTime() + snoozeMilliseconds);

        task.set('reminder', reminderDate);
        task.save({
            failure: function(task, operation) {
                var error = operation.getError(),
                   msg = Ext.isObject(error) ? error.status + ' ' + error.statusText : error;

                Ext.MessageBox.show({
                    title: 'Set Reminder Failed',
                    msg: msg,
                    icon: Ext.Msg.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        });
        reminderWindow.close();
    },

    /**
     * Handle's a click on the reminder window's dismiss button.
     * Hides the reminder window.
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     */
    dismissReminder: function(button, e) {
        button.findParentByType('window').close();
    }

});