// A quick-fix to address the issue in the TreePanel when re-ordering items.
// See: http://www.extjs.com/forum/showthread.php?t=91506
Ext.override(Ext.tree.TreeNode, {
  afterAdd : function(node, exists){
    if (this.childrenRendered) {
      // bulk render if the node already exists
      node.render(); //notice there is no exists passed to render.
    } else if(exists){
      // make sure we update the indent
      node.renderIndent(true, true);
    }
  }
});

var tree;
var selectedTodoId = -1;
var taskFieldWin;
var taskField;
var editTaskField;
var editTaskFieldWin;
var taskTypeRadio;

function PluginTodo() {
    tree = new Ext.tree.TreePanel({
        renderTo:'todo-list',
        useArrows:true,
        autoScroll:true,
        animate:true,
        enableDD:true,
        containerScroll: true,
        rootVisible: false,
        frame: false,
        root: {
            nodeType: 'async',
            id: '-1'
        },
        
        // auto create TreeLoader
        dataUrl: 'index.php?fuse=home&action=DoDashboardPluginAction&plugin=todo&pluginAction=listTasks',
        
        listeners: {
            'load':function(){
                Ext.getCmp('todoAddButton').setDisabled(false);
            },
            'checkchange': function(node, checked){
                if(checked){
                    Ext.Ajax.request({
                        url: 'index.php?fuse=home&action=DoDashboardPluginAction',
                        params: { id: node.id, plugin: "todo", pluginAction: "completeTask"}
                    });
                    node.getUI().addClass('complete');
                }else{
                    Ext.Ajax.request({
                        url: 'index.php?fuse=home&action=DoDashboardPluginAction',
                        params: { id: node.id, plugin: "todo", pluginAction: "uncompleteTask"}
                    });
                    node.getUI().removeClass('complete');
                    
                }
                selectedTodoId = node.id;
            },
            'click': function (node) {
                selectedTodoId = node.id;
                editTaskFieldWin.hide();
                Ext.getCmp('todoDelButton').setDisabled(false);
                Ext.getCmp('todoEditButton').setDisabled(false);
            },
            'movenode': function(tree,node,oldParent,newParent,index) {
                Ext.Ajax.request({
                    url: 'index.php?fuse=home&action=DoDashboardPluginAction',
                    params: { id: node.id, plugin: "todo", pluginAction: "moveNode", parentId : newParent.id, index: index}
                });
            }
        },
        
        buttons: [
        {
            id: 'todoAddButton',
            text: lang('Add'),
            scope:this,
            disabled:true,
            handler: function(){
                addTask();
            }
        },
        {
            id: 'todoEditButton',
            text: lang('Edit'),
            scope:this,
            disabled:true,
            handler: function(){
                editTask();
                Ext.getCmp('todoDelButton').setDisabled(true);
                Ext.getCmp('todoEditButton').setDisabled(true);
            }
        },{
            id: 'todoDelButton',
            text: lang('Delete'),
            scope:this,
            disabled:true,
            handler: function(){
                Ext.getCmp('todoDelButton').setDisabled(true);
                Ext.getCmp('todoEditButton').setDisabled(true);
                
                Ext.Ajax.request({
                    url: 'index.php?fuse=home&action=DoDashboardPluginAction',
                    params: { plugin: "todo", pluginAction : "removeTask", id:selectedTodoId},
                    success: reloadTree
                });
            }
        }]
    });

    tree.getRootNode().expand(true);
}

function PluginTodoReload()
{
    tree.root.reload();
    tree.getRootNode().expand();
}


Ext.onReady(function(){

    taskField = new Ext.form.TextField({
        id:         'taskField',
        name:       'taskField',
        fieldLabel: lang("Name"),
        labelStyle: 'font-weight:bold;font-size:11px;',
        border:     false,
        anchor:     '100%'
    });
    
    taskTypeRadio = new Ext.form.RadioGroup({
        id:         'taskFieldType',
        name:       'taskFieldType',
        fieldLabel: lang('Type'),
        labelStyle: 'font-weight:bold;font-size:11px;',
        border:     false,
        anchor:     '100%',
        items:      [
                        {boxLabel: lang('Task'), name: 'taskFieldType', inputValue: 'task', checked: true, autoWidth:true},
                        {boxLabel: lang('Group'), name: 'taskFieldType', inputValue: 'group', autoWidth:true}
                    ]
    
    });
    

    taskFieldWin = new Ext.Window({
        id:           "taskFieldWindow",
        x:            400,
        y:            200,
        labelAlign:   'right',
        layout:       'form',
        width:        300,
        autoHeight:   true,
        defaultType:  'textfield',
        closeAction:  'hide',
        title:        lang("Add Todo Item"),
        plain:        true,
        closable:     true,
        modal:        true,
        buttonAlign:  'right',
        items:        [taskField, taskTypeRadio],
        buttons:      [
                          {
                              id:       'btnTaskAddClient',
                              text:     lang("Add"),
                              disabled: false,
                              hidden:   false,
                              scope: this,
                              handler:  function(){
                                  sendTodoItem();
                              }
                          }
                      ]
    });
    
    
    editTaskField = new Ext.form.TextField({
        id:         'editTaskField',
        name:       'editTaskField',
        fieldLabel: lang("Name"),
        labelStyle: 'font-weight:bold;font-size:11px;',
        border:     false,
        anchor:     '100%'
    });
    
    editTaskFieldWin = new Ext.Window({
        id:           "editTaskFieldWindow",
        x:            400,
        y:            200,
        labelAlign:   'right',
        layout:       'form',
        width:        300,
        autoHeight:   true,
        defaultType:  'textfield',
        closeAction:  'hide',
        title:        lang("Edit Todo Item"),
        plain:        true,
        closable:     true,
        buttonAlign:  'right',
        items:        editTaskField,
        buttons:      [
                          {
                              id:       'btnTaskEditClient',
                              text:     lang("Save"),
                              disabled: false,
                              hidden:   false,
                              scope: this,
                              handler:  function(){
                                  editTodoItem();
                              }
                          }
                      ]
    });

});

function addTask(){
    editTaskFieldWin.hide();
    taskField.reset();
    taskFieldWin.show();
}

function editTask(){
    var node = tree.getNodeById(selectedTodoId);
    if (node == undefined || node == null || selectedTodoId == -1) return;
    taskFieldWin.hide();
    editTaskField.setValue(node.text);
    editTaskFieldWin.show();
}

function sendTodoItem() {
    if (taskField.getValue() != '') {

        Ext.Ajax.request({
            url: 'index.php?fuse=home&action=DoDashboardPluginAction',
            params: { plugin: "todo", pluginAction : "addTask", name:taskField.getValue(),
                      type: taskTypeRadio.getValue().getGroupValue(), selectedId: selectedTodoId},
            success: onCompleteSendTodoItem
        });

    } else {
        message = '';
        newline = "<br>";
        if (taskField.getValue() == '') {
            if (message != '') {
                message += newline;
            }
            message += lang("Todo Item");
        }

        if (message != '') {
            Ext.MessageBox.alert(lang("Errors"), lang("The following form field(s) were incomplete or incorrect") + ":<br><br>" + message + "<br><br>" + lang("Please complete or correct the form and submit again."));
            return;
        }
    }
}

function editTodoItem() {
    if (editTaskField.getValue() != '') {
        new Ajax.Request('index.php?fuse=home&action=DoDashboardPluginAction&plugin=todo&pluginAction=editTask',
             {postBody: 'name=' + editTaskField.getValue() + '&id=' + selectedTodoId,
              onComplete: onCompleteSendTodoItem
             }
        );
    } else {
        message = '';
        newline = "<br>";
        if (editTaskField.getValue() == '') {
            if (message != '') {
                message += newline;
            }
            message += lang("Todo Item");
        }

        if (message != '') {
            Ext.MessageBox.alert(lang("Errors"), lang("The following form field(s) were incomplete or incorrect") + ":<br><br>" + message + "<br><br>" + lang("Please complete or correct the form and submit again."));
            return;
        }
    }
}

function onCompleteSendTodoItem(responseObj)
{
    editTaskFieldWin.hide();
    taskFieldWin.hide();
    tree.root.reload();
}

function reloadTree()
{
    selectedTodoId = -1;
    tree.root.reload();
}