Wtf.TaskList = function(config) {
    Wtf.apply(this, config);
    
    /* -------------------  Current Task ----------------- */
    
    this.Task = Wtf.data.Record.create([
        {name: 'taskid'},
        {name: 'taskname'},
        {name: 'username'},
        {name: 'projectname'},
        {name: 'maxcredits',type : 'float'},
        {name: 'gaincredits',type : 'float'},
        {name: 'status'},
        {name: 'completestatus'},
        {name: 'context'},
        {name: 'priority'},
        {name: 'contextname'},
        {name: 'priorityname'},
        {name: 'description'},
        {name: 'assignbyuser'},
        {name: 'enddate',type: 'date',dateFormat: 'Y-m-d H:i:s'}, 
        {name: 'startdate',type: 'date',dateFormat: 'Y-m-d H:i:s'}, 
        {name: 'currentdate',type: 'date',dateFormat: 'Y-m-d H:i:s'},
        {name: 'Comments'},
        {name: 'commentcount'}, //number of new comments
    ]);

    this.GridJsonReader = new Wtf.data.KwlJsonReader({
        root: "data",
        totalProperty: 'count'
    }, this.Task);
    
    this.currentTaskStore = new Wtf.data.Store({
        url: "web/phpfiles/tasks.php",
        baseParams: {
            userid : this.userid,
            readby :loginid,
            mode : 9
        },
        reader: this.GridJsonReader
    });
    
    /* -------------------  Complete Task ----------------- */ 
    
    this.completeTask = Wtf.data.Record.create([
        {name: 'taskid'},
        {name: 'taskname'},
        {name: 'description'},
        {name: 'username'},
        {name: 'assignbyuser'},
        {name: 'projectname'},
        {name: 'maxcredits',type : 'float'},
        {name: 'enddate',type: 'date',dateFormat: 'Y-m-d H:i:s'}, 
        {name: 'completedate',type: 'date',dateFormat: 'Y-m-d H:i:s'}, 
        {name: 'gaincredits',type : 'float'},
        {name: 'Comments'}
    ]);

    this.completeTaskJReader = new Wtf.data.KwlJsonReader({
        root: "data",
        totalProperty: 'count'
    }, this.completeTask);
    
    this.completedTaskStore = new Wtf.data.Store({
        url: "web/phpfiles/tasks.php",
        baseParams: {
            userid : this.userid,
            mode : 10
        },
        reader: this.completeTaskJReader
    });
    
    /* -------------------  New Task ----------------- */
    
    this.newTask = Wtf.data.Record.create([
        {name: 'taskname'},
        {name: 'description'},
        {name: 'projectid'},
        {name: 'maxcredits'},
        {name: 'priority'},
        {name: 'id'}, // contextid
        {name: 'duedate',type: 'date',dateFormat: 'Y-m-j'}, 
        {name: 'startdate',type: 'date',dateFormat: 'Y-m-j'} 
    ]);

    this.newTaskJReader = new Wtf.data.KwlJsonReader({
        root: "data",
        totalProperty: 'count'
    }, this.newTask);
    
    this.newTaskStore = new Wtf.data.Store({
        url: "web/phpfiles/tasks.php",
        reader: this.newTaskJReader
    });
    
    /* -----------------            -------------------*/

    this.resourceRecord = Wtf.data.Record.create([
        {name: 'userid'},
        {name: 'username'}
    ]);
    
    this.ds_resource = new Wtf.data.Store({
            url: 'getTaskResources.jsp?taskid=',
            reader: new Wtf.data.KwlJsonReader({ root: 'data' },this.resourceRecord)
    });
    
    this.resCombo = new Wtf.form.ComboBox({
        displayField: 'username',
        valueField: 'userid',
        mode:'local',
        editable: false,
        triggerAction: 'all',
        width: 535,
        typeAhead: false,
        store: this.ds_resource
    });
    if((this.userid != loginid) || (Wtf.roleperms == 1)) {
        this.currtaskcontextCombo = createContextCombo();
        this.newtaskcontextCombo = createContextCombo();

        this.currtaskcontextCombo.on("select",this.onContextSelect,this);
        this.newtaskcontextCombo.on("select",this.onContextSelect,this);
 
        this.currpriorityCombo = createPriorityCombo();
        this.newpriorityCombo = createPriorityCombo();
     }
     
     this.statusCombo = createStatusCombo();
    
    this.projRec = Wtf.data.Record.create([{name: 'projectname'},{name: 'projectid'}]);
    this.projectStore = new Wtf.data.Store({
        url:'web/phpfiles/project.php',
        reader: new Wtf.data.KwlJsonReader({root:'data',totalProperty: 'count'}, this.projRec),
        autoLoad : false,
        baseParams:{mode :15}
    });
    this.projectStore.on("load",this.onProjStoreLoad,this);
    this.projectCombo = new Wtf.form.ComboBox({
        fieldLabel: 'Project',
        name: 'projectid',
        store: this.projectStore,
        emptyText: 'Select project----',
        displayField: 'projectname',
        valueField: 'projectid',
        typeAhead: true,
        mode: 'local',
        width: 260,
        forceSelection: true,
        editable: false,
        triggerAction: 'all',
        selectOnFocus: true
    });
    this.projectCombo.on("select",this.onProjSelect,this);
};

Wtf.extend(Wtf.TaskList, Wtf.Panel, {
      handleStoreLoad: function(store, rec, opt) {
        this.quickSearchTF.StorageChanged(store);      
      },
      onRender: function(config) {
            Wtf.TaskList.superclass.onRender.call(this,config);
            if(Wtf.roleperms == 1) {
                this.projectStore.load();
            }
            
            if(Wtf.roleperms == 4)
               this.taskSM=new Wtf.grid.RowSelectionModel({singleSelect: true});
            else
              this.taskSM=new Wtf.grid.CheckboxSelectionModel();
            this.taskCM = new Wtf.grid.ColumnModel(this.createTaskCM(0));
            // set column editable according to permissions
            if(this.userid == loginid && Wtf.roleperms != 1) {
                this.taskCM.setEditable(2,false);
                this.taskCM.setEditable(3,false);
                this.taskCM.setEditable(4,false);
                this.taskCM.setEditable(5,false);
                this.taskCM.setEditable(6,false);
                this.taskCM.setEditable(7,false);
                this.taskCM.setEditable(8,false);
                this.taskCM.setEditable(9,false);
                this.taskCM.setEditable(10,false);
            }   
            this.createTaskGrid();
            this.createInnerPanel();
            this.innerPanel.doLayout();
            this.add(this.innerPanel);
            if((this.userid != loginid) || (Wtf.roleperms == 1)) {
                if(!Wtf.StoreMgr.containsKey("priority")){
                     Wtf.priorityStore.load();
                     Wtf.StoreMgr.add("priority",Wtf.priorityStore)
                }
                if(!Wtf.StoreMgr.containsKey("context")){
                     Wtf.taskContStore.load();
                     Wtf.StoreMgr.add("context",Wtf.taskContStore)
                }  
            }
            this.currentTaskStore.load({params:{start :0 ,limit : this.assPageToolBar.pageSize}});
            this.completedTaskStore.load({params:{start :0 ,limit : this.assPageToolBar.pageSize}});
            this.currentTaskStore.on("load",this.oncurrentTaskStoreLoad,this);
            this.completedTaskStore.on("load",this.oncompleteTaskLoad,this);
      },
      
      afterRender: function(config) {
            Wtf.TaskList.superclass.afterRender.call(this,config);
            if (this.newTaskStore.getCount()==0)
                this.addBlankRow(this.newTaskStore);
      },
      
      oncurrentTaskStoreLoad : function() {
            var sm = this.taskgrid1.getSelectionModel();
            if(sm.hasSelection()) {
                var record = this.taskgrid1.getSelectionModel().getSelected();
                this.taskdetailPanel.updateDetail(record.data);
            } else {
                /*if(this.editTaskWinBttn)
                    this.editTaskWinBttn.disable();*/
                this.taskdetailPanel.blankDetail();
            } 
      },
      
      oncompleteTaskLoad : function() {
            var sm = this.taskgrid2.getSelectionModel();
            if(sm.hasSelection()) {
                var record = this.taskgrid2.getSelectionModel().getSelected();
                this.taskdetailPanel.updateDetail(record.data);
            }else {
                this.taskdetailPanel.blankDetail();
            } 
      },
      
      addBlankRow: function(store){
        var count = store.getCount();
        var p = new this.newTask({
            taskname: '',
            description: '',
            projectid :'',
            maxcredits:'',
            duedate: '',
            startdate: '',
            priority: '',
            id: '' // contextid
        });
        store.insert(count, p);
        //this.edited[this.theid] = false;
      },
      
      onContextSelect : function(combo,record,index) {
            if(Wtf.roleperms == 1 && record.data.id == '-1') {
               var cntxWin= new Wtf.CreateContext();
                cntxWin.show();
            }  
      },
      
      onProjStoreLoad : function(Store , records,options ) {
            var count = Store.getCount();
            var p = new this.projRec({
                projectid : '-1',
                projectname : 'Personal Task----'
            });
            Store.insert(count, p);
            
            if(Wtf.roleperms == 1) {
                var count = Store.getCount();
                var p = new this.projRec({
                    projectid : '-2',
                    projectname : 'New Project---'
                });
                Store.insert(count, p);
            }
      },
      
      onProjSelect : function(combo,record,index) {
          if(record.data.projectid == '-2') {
              //this.createProject();
              var projWin= new Wtf.CreateProject({
                        flag : true
                    });
                    projWin.show();
                    projWin.on("OnSuccess",function(){
                        this.projectStore.load();
                    },this);
                }    
      },
      
      createTaskGrid : function() {
          var selectionModel = new Wtf.grid.MultiSelectionModel();
          this.taskgrid1 = new Wtf.grid.EditorGridPanel({
                ds: this.currentTaskStore,
                cm: this.taskCM,
                sm: this.taskSM,
                border: false,
                clicksToEdit : 1,
                layout : 'fit',
                loadMask: {
                    msg: 'Loading...'
                },
                viewConfig: {
                    forceFit: true,
                    autoFill: true,
                    getRowClass: function(record,index,rowParams,store) {
                        var duedate = record.data.enddate;
                        duedate = new Date(duedate.getFullYear(), duedate.getMonth(), duedate.getDate());
                        var currentdate = record.get("currentdate");
                        currentdate = new Date(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate());
                        currentdate = currentdate.clearTime(false);
                        duedate = duedate.clearTime(false);
                        var difference = currentdate.getTime() - duedate.getTime();
                        daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
                        if (daysDifference > 0){
                            return  'red-row';
                        }else if (daysDifference == 0){
                            return  'green-row';
                        } else {
                            return '';
                        } 
                        
                    }
                },
                selModel: selectionModel
          }); 
          this.taskgrid1.on('afteredit',this.taskgridAfterEdit, this);
          this.taskgrid1.on('beforeedit', this.disableCells, this);
          this.taskgrid1.on('validateedit', this.assvalidateEdit, this);
          this.taskgrid1.on('cellclick', this.afterCellClick, this);
          this.taskgrid1.on('cellcontextmenu', this.onContextmenu, this);
          this.taskgrid1.getSelectionModel().on('rowselect',function(sm, rowIdx, r){
              /*if(this.editTaskWinBttn)
                  this.editTaskWinBttn.enable();*/
              this.updatecommentlog(sm, rowIdx, r);
              this.displayTaskDetails(sm, rowIdx, r)
          },this);
          this.taskCM = new Wtf.grid.ColumnModel(this.createTaskCM(1));
          this.taskgrid2 = new Wtf.grid.EditorGridPanel({
                ds: this.completedTaskStore,
                cm: this.taskCM,
                border: false,
                sm : new Wtf.grid.RowSelectionModel({singleSelect: true}),
                clicksToEdit : 1,
                layout : 'fit',
                loadMask: {
                    msg: 'Loading...'
                },
                viewConfig: {
                    forceFit: true,
                    autoFill: true
                }
          }); 
          this.taskgrid2.getSelectionModel().on('rowselect',this.displayTaskDetails,this);
          this.taskgrid2.on('cellclick', this.compGrCellClick, this);
          var selectionModel = new Wtf.grid.MultiSelectionModel();
          if((this.userid != loginid) || (Wtf.roleperms == 1)) {
              this.taskCM = new Wtf.grid.ColumnModel(this.createTaskCM(2));
              this.newTaskGrid = new Wtf.grid.EditorGridPanel({
                    ds: this.newTaskStore,
                    cm: this.taskCM,
                    border: false,
                    sm : new Wtf.grid.RowSelectionModel({singleSelect: true}),
                    clicksToEdit : 1,
                    loadMask: {
                        msg: 'Loading...'
                    },
                    viewConfig: {
                        forceFit: true
                    },
                    selModel: selectionModel
                }); 
                this.newTaskGrid.on('afteredit',this.newgridAfterEdit, this);
                this.newTaskGrid.on('validateedit', this.valiNewEditGrid, this);
                this.newTaskGrid.on('cellclick', this.afternewTaskCellClick, this);
                this.newTaskGrid.getSelectionModel().on('rowselect',this.displayTaskDetails,this);
            }
      },
      
      createInnerPanel : function() {
          var gridArr = [this.taskgrid1,this.taskgrid2];
          if((this.userid != loginid) || (Wtf.roleperms == 1)) {
              gridArr =[this.taskgrid1,this.taskgrid2,this.newTaskGrid];
          }
          this.innerPanel = new Wtf.Panel({
                border : false,
                //bodyStyle : "background:transparent;",
                layout : "border",
                //split : true,
                tbar : this.getTBar(),
                items:[
                     {
                        region: 'center',
                        border : false,
                        layout:'fit',
                        items: gridArr
                    },{
                        height: 170,
                        split : true,
                        border : false,
                        region: 'south',
                        id : 'taskdetailPanel'+this.userid,
                        bodyStyle: "background:#FFFFFF;border: solid 4px #5b84ba;",
                        layout: "fit",
                        items: [{
                            xtype: 'taskdetail',
                            layout:'fit',
                            cls:'messagePanelBody',
                            itemId: 'detailPanel'+this.userid
                       }]
                    }],
                bbar : this.getBbar()
          });
          this.taskdetailPanel = this.innerPanel.items.items[1].getComponent('detailPanel'+this.userid);
          this.currentTaskStore.on("load",this.handleStoreLoad,this);
      },
      
      getBbar : function(){
          var bbar = [this.assPageToolBar = this.pg = new Wtf.PagingToolbar({
                        pageSize: 15,
                        displayMsg: "Displaying Tasks {0} - {1} of {2}",
                        emptyMsg: "No Tasks to display",
                        scope:this,
                        store: this.currentTaskStore,
                        plugins : this.pP = new Wtf.common.pPageSize({id : "pPageSizeAssign_"+this.id})
                   })]
           if(Wtf.roleperms == 1) {
               /*bbar.push(this.newTaskWinBttn=new Wtf.Toolbar.Button({
                    text:'Add New Task',
                    tooltip :'create new tasks',
                    hidden : true,
                    id: 'BtnAddNew' + this.id,
                    scope: this,
                    handler:function(){this.openNewTaskWin(true)}
               }));
               bbar.push(this.editTaskWinBttn=new Wtf.Toolbar.Button({
                    text:'Edit Task',
                    tooltip :'edit task',
                     disabled : true,
                    id: 'BtnEdit' + this.id,
                    scope: this,
                    handler:function(){this.openNewTaskWin(false)}
               }));*/
               bbar.push(this.submitBttn=new Wtf.Toolbar.Button({
                        text:'Assign New Tasks',
                        tooltip :'create new tasks',
                        iconCls: 'newTaskIcon',
                        hidden : true,
                        id: 'BtnNew' + this.id,
                        scope: this,
                        handler : this.submitNewTask
               }));
           } 
               bbar.push(this.commentBttn=new Wtf.Toolbar.Button({text : "Add Comment",
                    //enableToggle: true,
                    id:"Comment"+this.id,
                    toggleGroup: 'tasktoggle' + this.id,
                    pressed: false,
                    iconCls: 'Comment',
                    scope : this,

                    handler : function() {
                        if(this.taskgrid1.getSelectionModel().getSelected()) {
                            this.addComment();
                        }
                        else
                            msgBoxShow(2,"Invalid","Select task to add comment");

                  }}));
                if(Wtf.roleperms == 1) {
                  bbar.push(this.markasdoneBttn=new Wtf.Toolbar.Button({text : "Mark as done",
                    id:"Mark"+this.id,
                    iconCls : 'markasdoneIcon',
                    toggleGroup: 'tasktoggle' + this.id,
                    pressed: false,
                    scope : this,

                    handler : function() {
                        var selected = this.taskSM.getSelections();
                        var rec = this.taskgrid1.getSelectionModel().getSelected();
                            jsonData =createJson(selected,this.userid)
                       
                            if((selected.length>0)){
                                    Wtf.Msg.show({
                                        title: 'Mark As Complete',
                                        msg: '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Are you sure you want to update status ?<br>(Task having gain credits 0 will be assigned there maxcredits)</br>',
                                        buttons: Wtf.Msg.YESNO,
                                        fn: function(btn, text) {
                                            if(btn=="yes"){
                                                Wtf.Ajax.requestEx({
                                                   url: 'web/phpfiles/tasks.php',                   
                                                   params : {
                                                        mode : 21,
                                                        jsondata : jsonData,
                                                        field : "completestatus",
                                                        value : 1
                                                   },
                                                   method:'POST'},
                                                   this,
                                                   function(request,response) {
                                                        var suc = request;
                                                        if(suc.success == true) {
                                                           this.currentTaskStore.load({params :{start:0,limit:this.pP.combo.value}});
                                                           this.completedTaskStore.load({params:{start :0 ,limit : this.pP.combo.value}});
                                                        }
                                                   },
                                                   function(request,response){

                                                });
                                            }
                                        },
                                        shadow : false,
                                        scope:this,
                                        animEl: 'elId',
                                        icon: Wtf.MessageBox.QUESTION
                                    });
                            }
                  }}));
                }

           return bbar;
      },
      
      getTBar : function() {
         var tbar = ['Quick Search: ',
                       this.quickSearchTF = new Wtf.KWLQuickSearch({
                           width: 200,
                           field:"taskname"
                    })]
             tbar.push({text : "Current Tasks",
                        enableToggle: true,
                        id:"newAss",
                        toggleGroup: 'tasktoggle' + this.id,
                        pressed: true,
                        scope : this,
                        handler : function() {
                            if(this.submitBttn)
                                this.submitBttn.hide();
                            this.commentBttn.show();
                            if(Wtf.roleperms == 1) 
                                this.markasdoneBttn.show();
                            /*if(this.newTaskWinBttn)
                                this.newTaskWinBttn.hide();
                            if(this.editTaskWinBttn)
                                 this.editTaskWinBttn.show();*/
                            this.taskgrid2.hide();
                            if((this.userid != loginid) || (Wtf.roleperms == 1)) 
                                this.newTaskGrid.hide();
                            this.layout.activeItem = this.taskgrid1;
                            this.taskgrid1.show();
                            this.innerPanel.doLayout();
                            this.doLayout();
                            var sm = this.taskgrid1.getSelectionModel();
                            if(sm.hasSelection()) {
                                var record = this.taskgrid1.getSelectionModel().getSelected();
                                this.taskdetailPanel.updateDetail(record.data);
                            } else {
                                this.taskdetailPanel.blankDetail();
                            } 
                            this.assPageToolBar.bind(this.currentTaskStore);
                            this.currentTaskStore.load({params:{start :0 ,limit : this.pP.combo.value}});
                            this.quickSearchTF.StorageChanged(this.currentTaskStore);
                        }});
             tbar.push('-');
             tbar.push({
                        text : "Completed Tasks",
                        enableToggle: true,
                        toggleGroup: 'tasktoggle' + this.id,
                        scope : this,
                        pressed: false,
                        handler : function() {
                            if(this.submitBttn)
                                this.submitBttn.hide();
                              this.commentBttn.hide();
                              if(Wtf.roleperms == 1) 
                               this.markasdoneBttn.hide();
                            /*if(this.newTaskWinBttn)
                                this.newTaskWinBttn.hide();
                            if(this.editTaskWinBttn)
                                 this.editTaskWinBttn.hide();*/
                            this.taskgrid1.hide();
                            if((this.userid != loginid) || (Wtf.roleperms == 1)) 
                                this.newTaskGrid.hide();
                            this.layout.activeItem = this.taskgrid2;
                            this.taskgrid2.show();
                            this.doLayout();
                            this.innerPanel.doLayout();
                            var sm = this.taskgrid2.getSelectionModel();
                            if(sm.hasSelection()) {
                                var record = this.taskgrid2.getSelectionModel().getSelected();
                                this.taskdetailPanel.updateDetail(record.data);
                            }else {
                                this.taskdetailPanel.blankDetail();
                            } 
                            this.assPageToolBar.bind(this.completedTaskStore);
                            this.completedTaskStore.load({params:{start :0 ,limit : this.pP.combo.value}});
                            this.quickSearchTF.StorageChanged(this.completedTaskStore);
                        }
                    });
          if(Wtf.roleperms == 1) {
             tbar.push('-');
             tbar.push({
                        text : "New Tasks",
                        enableToggle: true,
                        toggleGroup: 'tasktoggle' + this.id,
                        scope : this,
                        pressed: false,
                        handler : function() {
                            if(this.submitBttn)
                                this.submitBttn.show();
                              this.commentBttn.hide();
                              if(Wtf.roleperms == 1) 
                               this.markasdoneBttn.hide();
                            /*if(this.newTaskWinBttn)
                                this.newTaskWinBttn.show();
                            if(this.editTaskWinBttn)
                                 this.editTaskWinBttn.hide();*/
                            if (this.newTaskStore.getCount()==0)
                                this.addBlankRow(this.newTaskStore);
                            this.taskgrid1.hide();
                            this.taskgrid2.hide();
                            this.layout.activeItem = this.newTaskGrid;
                            this.newTaskGrid.show();
                            this.doLayout();
                            this.innerPanel.doLayout();
                            var sm = this.newTaskGrid.getSelectionModel();
                            if(sm.hasSelection()) {
                                var record = this.newTaskGrid.getSelectionModel().getSelected();
                                this.taskdetailPanel.updateDetail(record.data);
                            } else {
                                this.taskdetailPanel.blankDetail();
                            }    
                            this.assPageToolBar.bind(this.newTaskStore);
                            this.quickSearchTF.StorageChanged(this.newTaskStore);
                        }
                    });
          }
              return tbar;
      },
      
      createTaskCM : function(flag) {
        var columnArry;
        var sm1;
        if(Wtf.roleperms != 1)
            var sm1=new Wtf.grid.RowNumberer();
        else
            var sm1=new Wtf.grid.CheckboxSelectionModel();
        if(flag==0) {
            this.statusCombo.store = Wtf.statusStore;
            var contextCell,priorityCell;
            if((this.userid != loginid) || (Wtf.roleperms == 1)) {
                contextCell   = {
                        header: "Context",
                        sortable: true,
                        dataIndex: 'context',
                        editor: this.newtaskcontextCombo,
                        renderer:Wtf.ux.comboBoxRenderer(this.newtaskcontextCombo)
                };
                priorityCell   = {
                    header: "Priority",
                    sortable: true,
                    dataIndex: 'priority',
                    editor: this.newpriorityCombo,
                    renderer:Wtf.ux.comboBoxRenderer(this.newpriorityCombo)
                };
            } else {
                contextCell   = {
                        header: "Context",
                        sortable: true,
                        dataIndex: 'contextname'
                };
                priorityCell   = {
                    header: "Priority",
                    sortable: true,
                    dataIndex: 'priorityname'
                };
            }
            columnArry  = [sm1,
            {
                dataIndex: 'taskid',
                hidden: true,
                header: 'taskid'
            },{
                header: "Task Name",
                dataIndex: 'taskname',
                editor: new Wtf.form.TextField({
                    validateOnBlur: false,
                    validationDelay: 1000
                }),
                renderer : function(val) {
                    return "<div wtf:qtip=\""+val+"\" wtf:qtitle='Task'>"+val+"</div>";
                }
            },{
                header: "Description",
                dataIndex: 'description',
                editor: new Wtf.form.TextField({
                        validateOnBlur: false,
                        validationDelay: 1000
                }),
                renderer : function(val) {
                    return "<div wtf:qtip=\""+val+"\" wtf:qtitle='Description'>"+val+"</div>";
                }
            },{
                header: "Assigned By",
                sortable: true,
                dataIndex: 'assignbyuser'
            },{
                header: "Project ",
                sortable: true,
                dataIndex: 'projectname'
            },contextCell,priorityCell,{
                header: "Start Date",
                sortable: true,
                dataIndex: 'startdate',
                renderer: this.formatDate,
                editor: new Wtf.form.DateField({
                    format: 'D j-m-Y'
                })
            },{
                header: "Due Date",
                sortable: true,
                dataIndex: 'enddate',
                editor: new Wtf.form.DateField({
                    format: 'D j-m-Y'
                }),
                renderer: this.formatDate
            }];
            
            if((this.userid != loginid) || (Wtf.roleperms == 1)) {
                columnArry.push({
                    header: "Max Credits",
                    sortable: true,
                    dataIndex: 'maxcredits',
                    editor : new Wtf.ux.form.Spinner({
                        value :10,
                        strategy: new Wtf.ux.form.Spinner.NumberStrategy({minValue:'0', maxValue:'10'})
                    })
                });
                columnArry.push({
                    header: "% Completed",
                    sortable: true,
                    dataIndex: 'status',
                    editor: this.statusCombo,
                    renderer: Wtf.ux.comboBoxRenderer(this.statusCombo)
                });
                columnArry.push({
                    header: "Gain Credits",
                    sortable: true,
                    dataIndex: 'gaincredits',
                    editor: new Wtf.ux.form.Spinner({
                        value :10,
                        strategy: new Wtf.ux.form.Spinner.NumberStrategy({minValue:'0', maxValue:'10'})
                    })
                });
                columnArry.push({
                    header: "Mark As Done",
                    dataIndex: 'completestatus',
                    renderer:function(value, css, record, row, column, store){
                        return "<img id='AcceptImg' class='accept' src='web/images/check16.png' style=\"margin-left:5px;vertical-align:middle;height : 13px\" title='Mark As Done'></img>";
                    }
                });
                columnArry.push({
                    header: "Delete",
                    width: 65,
                    renderer:function(value, css, record, row, column, store) {
                        return "<img id='DeleteImg' class='delete' src='web/images/Cancel.gif' style=\"margin-left:5px;vertical-align:middle;height : 13px\" title='Delete task'></img>";
                    }
                });
                columnArry.push({
                    header: "Comments",
                    width: 85,
                    dataIndex: 'commentcount',
                    renderer:function(value){
                        if(value == 0)
                            return ;
                        else
                        return value + "<img id='newcomments' class='accept' src='web/images/comment.gif' style=\"margin-left:5px;vertical-align:middle;height : 16px\" /></img>";
                    }
                });
            } else {
                columnArry.push({
                    header: "Max Credits",
                    sortable: true,
                    dataIndex: 'maxcredits'
                });
                columnArry.push({
                    header: "% Completed",
                    sortable: true,
                    dataIndex: 'status',
                    editor: this.statusCombo,
                    renderer: Wtf.ux.comboBoxRenderer(this.statusCombo)
                });
                columnArry.push({
                    header: "Comments",
                    width: 85,
                    dataIndex: 'commentcount',
                    renderer:function(value){
                        if(value==0)
                            return ;
                        else
                        return value + "<img id='newcomments' class='accept' src='web/images/comment.gif' style=\"margin-left:5px;vertical-align:middle;height : 16px\" /></img>";
                    }
                });
            }
        } else if(flag==1) {
            columnArry = [new Wtf.grid.RowNumberer(),
                {
                    dataIndex: 'taskid',
                    hidden: true,
                    header: 'taskid'
                },{
                    header: "Task Name",
                    dataIndex: 'taskname',
                    renderer : function(val) {
                        return "<div wtf:qtip=\""+val+"\" wtf:qtitle='Task'>"+val+"</div>";
                    }
                },{
                    header: "Description",
                    dataIndex: 'description',
                    renderer : function(val) {
                        return "<div wtf:qtip=\""+val+"\" wtf:qtitle='Description'>"+val+"</div>";
                    }
                },{
                    header: "Assigned By",
                    sortable: true,
                    dataIndex: 'assignbyuser'
                },{
                    header: "Project",
                    sortable: true,
                    dataIndex: 'projectname'
                },{
                    header: "Due Date",
                    sortable: true,
                    dataIndex: 'enddate',
                    renderer: this.formatDate
                },{
                    header: "Completed Date",
                    sortable: true,
                    dataIndex: 'completedate',
                    renderer: this.formatDate
                },{
                    header: "Max Credits",
                    sortable: true,
                    dataIndex: 'maxcredits'
                },{
                    header: "Credits Gained",
                    sortable: true,
                    dataIndex: 'gaincredits'
                }];
              if((this.userid != loginid) || (Wtf.roleperms == 1)) {
                  columnArry.push({
                    header: "Undo Changes",
                    dataIndex :'undochanges',
                    renderer:function(value, css, record, row, column, store){
                        return "<img id='UndoImg' class='undochanges' src='web/images/undo.png' style=\"margin-left:5px;vertical-align:middle;height : 13px;width:14px;\" title='Undo changes'></img>";
                    }
                });
              }    
        } else if(flag==2) {
            columnArry = [new Wtf.grid.RowNumberer(),
                {
                    header: "Task Name",
                    dataIndex: 'taskname',
                    editor: new Wtf.form.TextField({
                        validateOnBlur: false,
                        validationDelay: 1000
                    }),
                    renderer : function(val) {
                        return "<div wtf:qtip=\""+val+"\" wtf:qtitle='Task'>"+val+"</div>";
                    }
                },{
                    header: "Description",
                    dataIndex: 'description',
                    editor: new Wtf.form.TextField({
                        validateOnBlur: false,
                        validationDelay: 1000
                    }),
                    renderer : function(val) {
                        return "<div wtf:qtip=\""+val+"\" wtf:qtitle='Description'>"+val+"</div>";
                    }
                },{
                    header: "Project",
                    dataIndex: 'projectid',
                    editor: this.projectCombo,
                    renderer:Wtf.ux.comboBoxRenderer(this.projectCombo)
                }];
                if((this.userid != loginid) || (Wtf.roleperms == 1)) {
                    columnArry.push({
                        header: "Max Credits",
                        sortable: true,
                        dataIndex: 'maxcredits',
                        editor : new Wtf.ux.form.Spinner({
                            value :10,
                            strategy: new Wtf.ux.form.Spinner.NumberStrategy({minValue:'0', maxValue:'10'})
                        })
                    });
                } else {
                    columnArry.push({
                        header: "Max Credits",
                        sortable: true,
                        dataIndex: 'maxcredits'
                    });
                }
                columnArry.push({
                    header: "Start Date",
                    dataIndex: 'startdate',
                    renderer: this.formatDate,
                    editor: new Wtf.form.DateField({
                        format: 'D j-m-Y'
                    })
                },{
                    header: "Due Date",
                    dataIndex: 'duedate',
                    renderer: this.formatDate,
                    editor: new Wtf.form.DateField({
                        format: 'D j-m-Y'
                    })
                },{
                    header: "Context",
                    dataIndex: 'id',
                    editor: this.currtaskcontextCombo,
                    renderer:Wtf.ux.comboBoxRenderer(this.currtaskcontextCombo)
                },{
                    header: "Priority",
                    dataIndex: 'priority',
                    editor: this.currpriorityCombo,
                    renderer:Wtf.ux.comboBoxRenderer(this.currpriorityCombo)
                },{
                    header: "Delete",
                    width: 65,
                    dataIndex: 'deletetask',
                    renderer:function(value, css, record, row, column, store)
                    {
                        if(store.getCount()-1 != row)
                            return "<img id='DeleteImg' class='delete' src='web/images/Cancel.gif' style=\"margin-left:5px;vertical-align:middle;height : 13px\" title='Delete task'></img>";
                    }
                });
        }    
        return columnArry;
    },
    
    ArrangeNumberer: function(currentRow, Grid) {
        for (var i = currentRow; i < Grid.getStore().getCount(); i++){
            Grid.getView().getCell(i, 0).firstChild.innerHTML = i + 1;
        }
    },
    
    formatDate: function(value) {
        if(typeof value == "string") {
            return value ? Date.parseDate(value,"Y-m-d H:i:s").dateFormat('D j-m-Y') : '';
        } else {
            return value ? value.dateFormat('D j-m-Y') : '';
        }    
    },
    
    timeDifference: function(laterdate, earlierdate) {
        var daysDifference = 0;
        if (typeof laterdate == 'string') {
            laterdate = Date.parseDate(laterdate, 'd/m/Y');
            earlierdate = Date.parseDate(earlierdate, 'd/m/Y');
        } else {
            laterdate = laterdate.clearTime(false);
            earlierdate = earlierdate.clearTime(false);
        }
        var difference = laterdate.getTime() - earlierdate.getTime();
        daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
        return (daysDifference);
    },
    
    displayTaskDetails : function(sm, rowIdx, r) {
        r.data['Comments']=unescape(r.data['Comments']);
        this.taskdetailPanel.updateDetail(r.data);
    },
    updatecommentlog:function(sm, rowIdx, r) {
       if((r.data['commentcount'] > 0)) {
            Wtf.Ajax.requestEx({
               url: 'web/phpfiles/tasks.php',                   
               params : {
                    mode : 22,
                    taskid : r.data.taskid,
                    userid : loginid
               },
               method:'POST'},
               this,
               function(request,response) {
                    var suc = request;
                    if(suc.success == true) {
                        r.data['commentcount']=0;
                        this.taskdetailPanel.updateDetail(r.data);
                    }
               });
       }
    },
    compGrCellClick : function(gd, ri, ci, e) {
        var event = e ;
        if(event.getTarget("img[class='undochanges']")){
            Wtf.Msg.show({
                    title:'Undo Changes',
                    msg: 'Are you sure you want to mark task as incomplete',
                    buttons: Wtf.Msg.YESNO,
                    fn: function(btn, text) {
                        if(btn=="yes"){
                            var record = gd.getStore().getAt(ri);
                            Wtf.Ajax.requestEx({
                               url: 'web/phpfiles/tasks.php',                   
                               params : {
                                    mode : 17,
                                    taskid : record.data.taskid,
                                    userid : this.userid
                               },
                               method:'POST'},
                               this,
                               function(request,response) {
                                    var suc = request;
                                    if(suc.success == true) {
                                       this.completedTaskStore.load({params:{start :0 ,limit : this.pP.combo.value}});
                                       this.currentTaskStore.load({params :{start:0,limit:this.pP.combo.value}});
                                    }
                               },                           
                               function(request,response){
                            });
                        }
                    },
                    shadow : false,
                    scope:this,
                    animEl: 'elId',
                    icon: Wtf.MessageBox.QUESTION
            });
        }
    },
    
    taskgridAfterEdit : function(e) {
        var event = e;
        if (event.field == 'status') {
            if(event.value == "6")   {
                Wtf.Msg.show({
                    title:'Mark As Complete',
                    msg: 'Are you sure you want to set status as completed ? You should not update status after that.',
                    buttons: Wtf.Msg.YESNO,
                    fn: function(btn, text) {
                        if(btn=="yes"){
                            this.updateRecord(event.field,event.record);
                        } else {
                            event.record.set(event.field,event.originalValue);
                            return;
                        }
                    },
                    shadow : false,
                    scope:this,
                    animEl: 'elId',
                    icon: Wtf.MessageBox.QUESTION
                });    
                
            } else {
                this.updateRecord(event.field,event.record);
            }
        } else {
            if (event.field == 'enddate') {
                var stdate = event.record.get("startdate");
                var enddate = event.value;
                var duration = this.timeDifference(enddate, stdate);
                if (duration < 0){
                    event.record.set('startdate',event.value);
                    this.updateRecord('startdate',event.record);
                }
            } else if (event.field == 'startdate') {
                var enddate = event.record.get("enddate");
                var stdate = event.value;
                var duration = this.timeDifference(enddate, stdate);
                if (duration < 0){
                    event.record.set('enddate',event.value);
                    this.updateRecord('enddate',event.record);
                }
            }
            this.updateRecord(event.field,event.record);
        }
    },
    
    assvalidateEdit : function(e) {
        if (e.field == 'gaincredits') {
            if(parseFloat(e.value) > parseFloat(e.record.data.maxcredits)) {
                msgBoxShow(1,"Invalid","You cant't assign credits greater than maxcredits ("+e.record.data.maxcredits+")");   
                e.cancel = true;
                return;
            } 
        }
        else if (e.field == 'context' && e.value == '-1') {
                e.cancel = true;
                return;
            }    
        
    },
    
    onContextmenu: function(g, rindex, cindex, e) {
        g.getSelectionModel().selectRow(rindex);
        var menu = new Wtf.menu.Menu({
            id: 'comment',
            items: [{
                id: 'newComment',
                icon: 'web/images/comment.gif',
                text: 'Add Comment',
                scope: this,
                handler: function insertComment(e) {
                            this.addComment();
                }
            }]
        });
       
        menu.showAt(e.getXY());
        e.preventDefault();
    },
    
    addComment: function(){
        var record = this.taskgrid1.getSelectionModel().getSelected();
        var commentWin= new Wtf.AddComment({
           taskid : record.get('taskid')
        });
        commentWin.show();
        commentWin.on("OnSuccess",function(commenttext,time){
            var loginname = getCookie('loginname');
            record.data['Comments']=unescape(record.data['Comments']);
            record.data['Comments'] = "<div><span style=color:#15428B;font-weight:bold;>"+ loginname +"</span> on <span style=color:gray>"+ time +"</span> : " + commenttext +"</div>" + record.data['Comments'];
            this.taskdetailPanel.updateDetail(record.data);
        },this);
    },

    afterCellClick: function(gd, ri, ci, e) {
        var event = e ;
        if(event.getTarget("img[class='accept']")){
            if(gd.getStore().getAt(ri).data.status == "6")   {
                Wtf.Msg.show({
                    title:'Mark As Complete',
                    msg: parseFloat(gd.getStore().getAt(ri).data.gaincredits) == 0 ?'Are you sure you want to update status as gain credits assigned to task is 0.00 ? <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (Task having gain credits 0 will be assigned there maxcredits)</br>' : 'Are you sure you want to update status ?',
                    buttons: Wtf.Msg.YESNO,
                    fn: function(btn, text) {
                        if(btn=="yes"){
                            var record = gd.getStore().getAt(ri);
                            Wtf.Ajax.requestEx({
                               url: 'web/phpfiles/tasks.php',                   
                               params : {
                                    mode : 7,
                                    taskid : record.data.taskid,
                                    maxcredits : record.data.maxcredits,
                                    userid : this.userid,
                                    field : "completestatus",
                                    value : 1
                               },
                               method:'POST'},
                               this,
                               function(request,response) {
                                    var suc = request;
                                    if(suc.success == true) {
                                       this.currentTaskStore.load({params :{start:0,limit:this.pP.combo.value}});
                                       this.completedTaskStore.load({params:{start :0 ,limit : this.pP.combo.value}});
                                    }
                               },
                               function(request,response){
                               
                            });
                        }
                    },
                    shadow : false,
                    scope:this,
                    animEl: 'elId',
                    icon: Wtf.MessageBox.QUESTION
                });
             }   
        } else if(event.getTarget("img[class='delete']")){
            Wtf.Msg.show({
                    title:'Delete Assigned Task',
                    msg: gd.getStore().getAt(ri).data.status != 1 ?'Are you sure you want to delete assigned task as task was done by user partially' : 'Are you sure you want to delete assigned task?',
                    buttons: Wtf.Msg.YESNO,
                    fn: function(btn, text) {
                        if(btn=="yes"){
                            var record = gd.getStore().getAt(ri);
                            Wtf.Ajax.requestEx({
                               url: 'web/phpfiles/tasks.php',                   
                               params : {
                                    mode : 16,
                                    taskid : record.data.taskid,
                                    userid : this.userid
                               },
                               method:'POST'},
                               this,
                               function(request,response) {
                                    var suc = request;
                                    if(suc.success == true) {
                                       this.currentTaskStore.load({params :{start:0,limit:this.pP.combo.value}});
                                    }
                               },                           
                               function(request,response){
                            });
                        }
                    },
                    shadow : false,
                    scope:this,
                    animEl: 'elId',
                    icon: Wtf.MessageBox.QUESTION
            });
        }
    },
    
    disableCells : function(e) {
        if (e.field == 'status') {
            if(e.value == "6")   {
                e.cancel = true;
                return;
            }
        } else if (e.field == 'gaincredits') {
            if(e.record.data.status != "6")   {
                e.cancel = true;
                return;
            }
        } else if ((e.field == 'enddate' || e.field == 'startdate' || e.field == 'context' || e.field == 'priority' || e.field == 'maxcredits') 
                && e.record.data.status == "6")  {
                e.cancel = true;
                return;
        }
    },
    
    updateRecord: function(field,record) {
        var colValue = "";
        if(field == 'enddate' || field == 'startdate') 
        {
            var edate = new Date(record.data[field]);
            colValue = edate.format("Y-m-j");
        } else {
            colValue = record.data[field];
        } 
        if(field == 'taskname' || field == 'description' || field == 'priority' || field == 'context' || field == 'maxcredits')  {
            Wtf.Ajax.requestEx({
               url: 'web/phpfiles/tasks.php',                   
               params : {
                    mode : 13,
                    taskid : record.data.taskid,
                    field : field,
                    value : colValue
               },
               method:'POST'},
               this,
               function(request,response) {
                    var suc = request
               },                           
               function(request,response){
            }); 
        } else {
            Wtf.Ajax.requestEx({
               url: 'web/phpfiles/tasks.php',                   
               params : {
                    mode : 7,
                    taskid : record.data.taskid,
                    userid : this.userid,
                    field : field,
                    value : colValue
               },
               method:'POST'},
               this,
               function(request,response) {
               },                           
               function(request,response){
            }); 
        }
    },
    
    afternewTaskCellClick : function(gd, ri, ci, e) {
        var event = e ;
        if(event.getTarget("img[class='delete']")){
            if(ri != gd.getStore().getCount()-1) {
                Wtf.Msg.show({
                    title:'Delete Task',
                    msg: 'Are you sure you want to delete task?',
                    buttons: Wtf.Msg.YESNO,
                    fn: function(btn, text) {
                        if(btn=="yes"){
                            var record = gd.getStore().getAt(ri);
                            gd.getStore().remove(record);
                            this.ArrangeNumberer(ri,gd);
                        }
                    },
                    shadow : false,
                    scope:this,
                    animEl: 'elId',
                    icon: Wtf.MessageBox.QUESTION
                });
            }
        }
    },
    
    onProjectChanged : function(combo, record,index) {
        this.taskStore.load({params : {projectid : record.data.projectid,mode : 10}});
    },
    
    onTaskChanged : function(combo, record,indexl) {
        this.startdate.setValue(Date.parseDate(record.data.startdate,"Y-m-d H:i:s"));
        this.duedate.setValue(Date.parseDate(record.data.duedate,"Y-m-d H:i:s"));
    },
    
    newgridAfterEdit : function(e) {
        var event = e;
        var count = event.grid.getStore().getCount();
        if (count == (event.row + 1))
            this.addBlankRow(event.grid.getStore());
        if (e.field == 'duedate') {
            var stdate = new Date(e.record.get("startdate"));
            stdate = new Date(stdate.getFullYear(), stdate.getMonth(), stdate.getDate());
            var enddate = new Date(e.value);
            enddate = new Date(enddate.getFullYear(), enddate.getMonth(), enddate.getDate());
            var duration = this.timeDifference(enddate, stdate);
            if (duration < 0){
                e.record.set('startdate',e.value);
            }
        } else if (e.field == 'startdate') {
            var enddate = new Date(e.record.get("duedate"));
            enddate = new Date(enddate.getFullYear(), enddate.getMonth(), enddate.getDate());
            var stdate = new Date(e.value);
            stdate = new Date(stdate.getFullYear(), stdate.getMonth(), stdate.getDate());
            var duration = this.timeDifference(enddate, stdate);
            if (duration < 0){
                e.record.set('duedate',e.value);
            }
        }
    },
    
    valiNewEditGrid : function(e) {
        if ((e.field == 'startdate' || e.field == 'duedate') && e.value == "") {
            e.cancel = true;
            return;
        }
        else if(e.field == 'taskname' || e.field == 'maxcredits' || e.field == 'description') {
            if (e.field == 'taskname') {
                if(e.record.data['maxcredits'] == "")
                    e.record.data['maxcredits'] = '1';
            } else if (e.field == 'maxcredits') {
                if(e.record.data['taskname'] == "")
                    e.record.data['taskname'] = 'New Task';
            } else if (e.field == 'description') {
                if(e.record.data['taskname'] == "")
                    e.record.data['taskname'] = 'New Task';
                if(e.record.data['maxcredits'] == "")
                    e.record.data['maxcredits'] = '1';
            }
            e.record.data['priority'] = '1';
            var count = Wtf.taskContStore.getCount();
            if(count > 0)
                e.record.data['id'] = '1';
            var dt = new Date();
            e.record.set('startdate',dt);
            e.record.set('duedate', dt);
        }else if (e.field == 'projectid' && e.value == '-2') {
                e.cancel = true;
                return;
        }else if (e.field == 'id' && (e.value == '-1'|| e.value == '')) {
                e.cancel = true;
                return;
        }
    },
    
    submitNewTask : function() {
        var jsonData = "[";
        for(var cnt =0 ;cnt < this.newTaskStore.getCount()-1; cnt++) {
            if(this.newTaskStore.getAt(cnt).data.projectid !='') {
                if(this.newTaskStore.getAt(cnt).data.id !='')
                    jsonData += this.getJsonFromRecord(this.newTaskStore.getAt(cnt)) + ",";
                else {
                    msgBoxShow(2,"Invalid Input","Please select context for task \'"+this.newTaskStore.getAt(cnt).data.taskname+"\'");
                    return;
                }
            }    
            else {
                msgBoxShow(2,"Invalid Input","Please select project for task \'"+this.newTaskStore.getAt(cnt).data.taskname+"\'");
                return;
            }
        }
        jsonData = jsonData.substr(0, jsonData.length - 1) + "]";
        
        Wtf.Ajax.requestEx({
            url:'web/phpfiles/tasks.php',
            params:{
                jsondata : jsonData,
                projectid : this.projectid,
                mode : 1,
                flag : 2
            },
            method:'POST'},
            this,
            function(response,request){
                var retstatus = response;
                if(retstatus.success){
                    msgBoxShow(1,"Success","Task created successfully");
                    this.newTaskStore.removeAll();
                    this.currentTaskStore.load({params :{start:0,limit:this.pP.combo.value}});
                    this.addBlankRow(this.newTaskStore);
                } else {
                    msgBoxShow(2,"Error",retstatus.ErrorCode);
                }    
            },function(rep,req){

        });
    },
    
    getJsonFromRecord : function(record) {
        var sdate = new Date(record.data["startdate"]);
        sdate = sdate.format("Y-m-j");
        var edate = new Date(record.data["duedate"]);
        edate = edate.format("Y-m-j");
        var jsonData = '{"taskname":"'+record.data["taskname"].replace(/\"/g,'\'')+'","description":"'+record.data["description"].replace(/\"/g,'\'')+'","startdate":"'+sdate.toString()+'","duedate":"'+edate.toString()+'","maxcredits":"'+record.data["maxcredits"]+'","priority":"'+record.data["priority"]+'","context":"'+record.data["id"]+'","projectid":"'+record.data["projectid"]+'","userid":"'+this.userid+'"}';
        return(jsonData);
    }
    
    /*getJsonFromAssRecord : function(record) {
        var sdate = new Date(record.data["startdate"]);
        sdate = sdate.format("Y-m-j");
        var edate = new Date(record.data["enddate"]);
        edate = edate.format("Y-m-j");
        var jsonData = '{"taskname":"'+record.data["taskname"]+'","description":"'+record.data["description"]+'","startdate":"'+sdate.toString()+'","enddate":"'+edate.toString()+'","maxcredits":"'+record.data["maxcredits"]+'","priority":"'+record.data["priority"]+'","context":"'+record.data["context"]+'","projectid":"'+record.data["projectid"]+'","userid":"'+this.userid+'"}';
        return(jsonData);
    },*/
   
    
/*,
    
    openNewTaskWin : function(flag){
        var record;
        if(!flag) {
            record = this.taskgrid1.getSelectionModel().getSelected();
        }
        this.newTaskWin=new Wtf.NewTaskWind({                    
            id:'newtaskwin' + this.userid,
            width:700,
            height:400,
            layout:'fit',
            resizable:false,
            priorityStore :this.priorityStore,
            taskContStore : this.taskContStore,
            assignTo : this.projectStore,
            assignLabel : 'Project',
            valueField : 'projectid',
            displayField : 'projectname',
            record : record,
            flag : flag
        });
        this.newTaskWin.show();
        this.newTaskWin.on("add",function(columnArray,valueArray,assVal){
            this.addBlankRow(this.newTaskStore);
            var record = this.newTaskStore.getAt(this.newTaskStore.getCount()-2);
            for(var cnt =0 ;cnt<columnArray.length;cnt++) {
                record.set(columnArray[cnt],valueArray[cnt]);
            }
            record.set('projectid',assVal);
        },this);
        
        this.newTaskWin.on("submit",function(columnArray,valueArray){
            var record = this.taskgrid1.getSelectionModel().getSelected();
            for(var cnt =0 ;cnt<columnArray.length;cnt++) {
                record.set(columnArray[cnt],valueArray[cnt]);
            }
            
            Wtf.Ajax.requestEx({
               url: 'web/phpfiles/tasks.php',                   
               params : {
                    mode : 19,
                    taskid : record.data.taskid,
                    userid : this.userid,
                    jsondata : "["+this.getJsonFromAssRecord(record)+"]"
               },
               method:'POST'},
               this,
               function(request,response) {
                    var suc = request
               },                           
               function(request,response){
            }); 
            
        },this);
    }*/
    
});    



Wtf.PersonCreditsReport = function(config) {
    Wtf.apply(this, config);
    Wtf.PersonCreditsReport.superclass.constructor.call(this, config);
};

Wtf.extend(Wtf.PersonCreditsReport, Wtf.Panel, {    
    initComponent: function() {        
        Wtf.PersonCreditsReport.superclass.initComponent.call(this);
        
        this.monthStore = new Wtf.data.SimpleStore({
            fields: ['id', 'name'],
            data :
             [['1', 'January'],['2', 'February'],['3', 'March'],['4', 'April'],
              ['5', 'May'],['6', 'June'],['7', 'July'],['8', 'August'],
              ['9', 'September'],['10', 'October'],['11', 'November'],['12', 'December']
            ]
        });
        this.monthCombo = new Wtf.form.ComboBox({
                        mode:'local',
                        triggerAction:'all',
                        typeAhead:true,
                        editable:false,
                        width : 120,                                
                        store:this.monthStore,
                        displayField:'name',
                        valueField:'id',
                        allowBlank : false,
                        value : (new Date()).format("n")
                    });
        this.yearStore = new Wtf.data.SimpleStore({
            fields: ['id', 'name'],
            data :
             [['2007', '2007'],['2008', '2008'],['2009', '2009'],['2010', '2010']
            ]
        });
        this.yearCombo = new Wtf.form.ComboBox({
                        mode:'local',
                        triggerAction:'all',
                        typeAhead:true,
                        editable:false,
                        width : 120,                                
                        store:this.yearStore,
                        displayField:'name',
                        valueField:'id',
                        allowBlank : false,
                        emptyText : 'Select year---',
                        value : (new Date()).format("Y")
                    });
                        
        this.submitBttn=new Wtf.Toolbar.Button({
                text:'Submit',
                tooltip :'Search according to criteria',
                id: 'btnNew1' + this.id,
                scope: this,
                minWidth:30
        });
        this.submitBttn.on('click',this.onValueChange,this);
        
        
        this.completeTask = Wtf.data.Record.create([
            {name: 'taskid'},
            {name: 'taskname',type: 'string'},
            {name: 'projectname'},
            {name: 'enddate',type: 'date',dateFormat: 'Y-m-d H:i:s'}, 
            {name: 'completedate',type: 'date',dateFormat: 'Y-m-d H:i:s'}, 
            {name: 'gaincredits',type: 'float'}
        ]);

        this.completeTaskJReader = new Wtf.data.KwlJsonReader({
            root: "data",
            totalProperty: 'count'
        }, this.completeTask);

        this.completedTaskStore = new Wtf.data.GroupingStore({
            /*url: "web/phpfiles/tasks.php",
            baseParams: {
                userid : this.userid,
                mode : 10
            },*/
            reader: this.completeTaskJReader,
            sortInfo: {
                field: 'projectname',
                direction: "ASC"
            },
            groupField:'projectname'
        });
        
        this.taskCM =  new Wtf.grid.ColumnModel([new Wtf.grid.RowNumberer(),
                {
                    dataIndex: 'taskid',
                    hidden: true,
                    header: 'taskid'
                },{
                    header: "Task Name",
                    dataIndex: 'taskname'
                },{
                    header: "Project",
                    dataIndex: 'projectname'
                },{
                    header: "Due Date",
                    dataIndex: 'enddate',
                    renderer: this.formatDate
                },{
                    header: "Completed Date",
                    dataIndex: 'completedate',
                    renderer: this.formatDate
                },{
                    header: "Gain Credits",
                    dataIndex: 'gaincredits',
                    align : 'right',
                    summaryType: 'sum',
                    summaryRenderer: function(val) {
                        val = val + "";
                        if(val != null && val != "")
                            return 'Total: ' + val;   
                        else 
                            return 'Total: ' + val;
                    }
                }])
        this.groupingView = new Wtf.grid.GroupingView({
            forceFit: true,
            showGroupName: false,
            enableGroupingMenu: false,
            hideGroupedColumn: true
        });
        this.summary = new Wtf.grid.GroupSummary({});
        this.reportGrid = new Wtf.grid.GridPanel({
                ds: this.completedTaskStore,
                cm: this.taskCM,
                layout : 'fit',
                plugins: this.summary,
                view: this.groupingView,
                loadMask: {
                    msg: 'Loading...'
                },
                viewConfig: {
                    forceFit: true,
                    autoFill: true
                }
          });
    },

   onRender: function(config) {
        Wtf.PersonCreditsReport.superclass.onRender.call(this, config); 
        this.panel = {
            border: false,
            layout : 'border',
            items :[{
                    title : this.combofieldLabel,
                    region : "north",
                    height:0,
                    border : false,
                    layout : "fit",
                    bodyStyle : "background:#f1f1f1;",
                    tbar:[ 'Select Year :',this.yearCombo,'-','Select Month :',this.monthCombo,'-',this.submitBttn]
                },{
                region: 'center',
                autoScroll: true,
                bodyStyle : 'background:#f1f1f1;font-size:10px;',
                border:false,
                layout:'fit',
                items: this.reportGrid
            }]}
        this.add(this.panel); 
        this.onValueChange();
    },
    
    onValueChange : function() {
        this.yearCombo.validate();
        if(this.yearCombo.isValid()) {
            var dateVal = Date.parseDate(this.yearCombo.getValue()+"-"+this.monthCombo.getValue(), "Y-n");
            Wtf.Ajax.requestEx({
                   url: 'web/phpfiles/tasks.php',                   
                   params : {
                        mode : 14,
                        userid:this.userid,
                        startdate : dateVal.getFirstDateOfMonth().format("Y-m-j"),
                        enddate  : dateVal.getLastDateOfMonth().format("Y-m-j")
                   },
                   method:'POST'},
                   this,
                   function(request,response){
                        var suc = request;
                        this.completedTaskStore.loadData(suc);
                   },                           
                   function(request,response){
            });
        }
    }
});

/*
    
    //------------------------------------  Code for richrext for task descriptions  -------------------------------------------//

*/
/*
Wtf.NewTaskWind = function(config) {
    Wtf.apply(this, config);
    Wtf.NewTaskWind.superclass.constructor.call(this, config);
};

Wtf.extend(Wtf.NewTaskWind, Wtf.Window, {    
    initComponent: function() {        
        programId = null;        
        type = null;
        selectedclass=null;
        Wtf.NewTaskWind.superclass.initComponent.call(this);
        this.addEvents({
             "add": true,
             "submit": true
        });
    },

   onRender: function(config) {
        Wtf.NewTaskWind.superclass.onRender.call(this, config); 
        this.loadMask = new Wtf.LoadMask(this.el.dom, Wtf.apply(this.loadMask));
        
        this.taskcontextCombo = new Wtf.form.ComboBox({
            fieldLabel: 'Context',
            name: 'context',
            store: this.taskContStore,
            emptyText: 'Select context----',
            displayField: 'name',
            valueField: 'id',
            typeAhead: true,
            mode: 'local',
            width: 110,
            forceSelection: true,
            editable: false,
            triggerAction: 'all',
            selectOnFocus: true
        });
        this.taskcontextCombo.setValue(this.flag ? this.taskContStore.getAt(0).data.id : this.record.data.context );
        this.priorityCombo = new Wtf.form.ComboBox({
            fieldLabel: 'Priority',
            name: 'Priority',
            store: this.priorityStore,
            emptyText: 'Select priority----',
            displayField: 'name',
            valueField: 'id',
            typeAhead: true,
            mode: 'local',
            width: 110,
            forceSelection: true,
            editable: false,
            triggerAction: 'all',
            selectOnFocus: true
        });
        this.priorityCombo.setValue(this.flag ? this.priorityStore.getAt(0).data.id : this.record.data.priority);
        this.assignToCombo = new Wtf.form.ComboBox({
            fieldLabel: this.assignLabel,
            name: 'projectid',
            store: this.assignTo,
            emptyText: 'Select '+this.assignLabel+'----',
            displayField: this.displayField,
            valueField: this.valueField,
            typeAhead: true,
            mode: 'local',
            width: 260,
            forceSelection: true,
            editable: false,
            triggerAction: 'all',
            selectOnFocus: true,
            disabled : this.flag ? false : true,
            value : this.flag ? null : this.record.data[this.displayField]
        });
        Wtf.ux.comboBoxRenderer = function(combo) {
            return function(value) {
                var idx = combo.store.find(combo.valueField, value);
                if(idx == -1)
                    return "";
                var rec = combo.store.getAt(idx);
                return rec.get(combo.displayField);
            };
        }
        this.newapplyTasks= new Wtf.Panel({
                border:false,
                layout:"border",
                items:[{
                    region : 'north',
                    height : 75,
                    border : false,
                    bodyStyle : 'background:white;border-bottom:1px solid #bfbfbf;',
                    html : getHeader('web/images/ack40.gif',this.flag ? "New Task" : "Edit Task",this.flag ? "Enter new task's info" : "Edit selected task") 
                },{
                border:false,
                region:'center',
                bodyStyle : 'background:#f1f1f1;font-size:10px;',
                layout:"fit",
                items: [new Wtf.Panel({
                                bodyStyle : "background:transparent;",
                                layout:"border",
                                items: [{
                                        region:"north",
                                        border:false,
                                        height:200,
                                        bodyStyle:'padding:13px 13px 0px 13px',
                                        layout:"form",
                                        items : [this.assignToCombo,this.taskname = new Wtf.form.TextField({
                                                fieldLabel: 'Task Title',
                                                width : 333,
                                                name: 'taskname',
                                                value : this.flag ? null : this.record.data.taskname
                                            }),this.description =new Wtf.form.HtmlEditor ({
                                                //xtype: 'textarea',
                                                width : 540,
                                                height : 130,
                                                fieldLabel: 'Description',
                                                name: 'description',
                                                value : this.flag ? null : this.record.data.description
                                            })]
                                     },{
                                        region:"center",
                                        border:false,
                                        layout:'column',
                                        bodyStyle:'padding:13px 13px 0px 13px',
                                        items:[{
                                            columnWidth:0.33,
                                            layout:'form',
                                            border:false,
                                            items:[
                                                this.sdate = new Wtf.form.DateField({
                                                    fieldLabel: 'Start Date',
                                                    width : 110,
                                                    format: 'D j-m-Y'
                                                }),
                                                this.maxcredits = new Wtf.ux.form.Spinner({
                                                    value :1,
                                                    width : 110,
                                                    fieldLabel: 'Credits',
                                                    strategy: new Wtf.ux.form.Spinner.NumberStrategy({minValue:'0', maxValue:'10'})
                                                })
                                            ]
                                         },{
                                            columnWidth:0.33,
                                            layout:'form',
                                            border:false,
                                            //labelWidth:84,
                                            items:[                      
                                               this.edate = new Wtf.form.DateField({
                                                    fieldLabel: 'End Date',
                                                    width : 110,
                                                    format: 'D j-m-Y'
                                               }),
                                               this.priorityCombo
                                            ]
                                        },{
                                            columnWidth:0.33,
                                            layout:'form',
                                            border:false,
                                            items:[                      
                                               this.taskcontextCombo
                                            ]
                                        }]
                                }]
                            })]
             }],
          buttonAlign :'right',
            buttons: [{
                anchor : '90%',
                text: this.flag ? 'Add' : "Submit",                
                scope:this,
                handler: this.addToGrid
            },{
                anchor : '90%',
                id : 'close',
                text: 'Close',
                handler: function(){
                    this.close();                
                },
                scope:this
            }]          
        });
        this.sdate.on('change',function(){
            var duration = this.timeDifference(this.edate.getValue(), this.sdate.getValue());
            if (duration < 0){
                this.edate.setValue(this.sdate.getValue());
            }
        },this);
        this.edate.on('change',function(){
            var duration = this.timeDifference(this.edate.getValue(), this.sdate.getValue());
            if (duration < 0){
                this.sdate.setValue(this.edate.getValue());
            }
        },this);
        if(this.flag) {
            this.sdate.setValue(new Date());
            this.edate.setValue(new Date());
        } else {
            this.sdate.setValue(this.record.data.startdate);
            this.edate.setValue(this.record.data.enddate);
        }
        this.add(this.newapplyTasks);        
    },
    
    addToGrid : function() {
        if(this.flag) {
            if(this.assignToCombo.getValue() != '') {
                 var valueArray = new Array(this.taskname.getValue(),this.description.getValue().replace(/\"/g,'\''),this.maxcredits.getValue(),this.sdate.getValue(),this.edate.getValue(),this.taskcontextCombo.getValue(),this.priorityCombo.getValue());
                 var columnArray = new Array("taskname", "description","maxcredits","startdate","duedate","context","priority");
                 this.fireEvent("add",columnArray,valueArray,this.assignToCombo.getValue());
                 this.taskname.setValue('');
                 this.description.setValue('');
                 this.maxcredits.setValue(1);
                 this.sdate.setValue(new Date());
                 this.edate.setValue(new Date());
            } else {
                msgBoxShow(1,"Invalid Input","Please select "+this.assignLabel);   
            } 
        } else {
            var valueArray = new Array(this.taskname.getValue(),this.description.getValue().replace(/\"/g,'\''),this.maxcredits.getValue(),this.sdate.getValue(),this.edate.getValue(),this.taskcontextCombo.getValue(),this.priorityCombo.getValue());
            var columnArray = new Array("taskname", "description","maxcredits","startdate","enddate","context","priority");
            this.fireEvent("submit",columnArray,valueArray);
            this.close();
        }
    },
    
    timeDifference: function(laterdate, earlierdate) {
        var type = typeof laterdate;
        var daysDifference = 0;
        if (type == 'string') {
            var ld = new Date();
            ld = Date.parseDate(laterdate, 'd/m/Y');
            var ed = new Date();
            ed = Date.parseDate(earlierdate, 'd/m/Y');
            var difference = ld.getTime() - ed.getTime();
            daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
        } else {
            laterdate = laterdate.clearTime(false);
            earlierdate = earlierdate.clearTime(false);
            var difference = laterdate.getTime() - earlierdate.getTime();
            daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
        }
        return (daysDifference);
    }
});*/