 var cordovaInAppBrowser;

 function cordovaBrowser(content, style) {
   var url = '';
   if (style == 'invoice') {
     url = url_site + '/' + 'invoice.html?invoice_id=' + content;
   } else {
     if (content.indexOf('s3.amazonaws.com') < 0) {
       content = content.replace('./', '');
       url = url_site + '/' + content;
     } else {
       url = content;
     }
   }
   var options = { location: 'no', clearcache: 'no', toolbar: 'yes', enableViewportScale: 'yes' };
   if (isiOs) {
     cordovaInAppBrowser.open(url, '_blank', options);
   } else {
     cordovaInAppBrowser.open(url, '_system', options);
   }
 }
 taskApp.controller('taskCtrl', function($cordovaInAppBrowser, $ionicSlideBoxDelegate, $ionicScrollDelegate, $cordovaToast, $cordovaFileTransfer,
     $cordovaImagePicker, $ionicPopup, $ionicLoading, $cordovaToast, $interval, $scope, $sce, Login, taskView, $timeout, //
     dataHtml, $cordovaActionSheet, $cordovaFileTransfer, $cordovaFile, $cordovaImagePicker, $cordovaCamera, $http, Taskfilters) {
   cordovaInAppBrowser = $cordovaInAppBrowser;
   searchChatHandle();

   function searchChatHandle() {
     toggleDelegateHandle('#task_page', '.link-task-search', '.task-search');
     toggleDelegateHandle('#task_page', '.task-search .search-type .btn-close', '.task-search');
     toggleDelegateHandle('#task_page', '.task-search .search-content .btn-close', '.task-search');
   }
   filterChangeAssigneeHandle();

   function filterChangeAssigneeHandle() {
     toggleDelegateHandle('#task_page', '.link-task-change-assignee', '.task-change-assignee');
   }
   filterAddFollowerHandle();

   function filterAddFollowerHandle() {
     toggleDelegateHandle('#task_page', '.link-add-follower', '.task-add-follower');
   }
     // Tab Task Handle
     $scope.tabTaskActive = 'Incomplete';
     $scope.setTabTask = function(tab, index) {
       $scope.tabTaskActive = tab;
       $scope.currentItemTab = $scope.tabs[index];
     }
         // template tab type
         $scope.tabs = [{
           label: 'Incomplete',
           url: conFig.url + 'incomplete.tpl',
           attr: 'incomplete'
         }, {
           label: 'Upcoming',
           url: conFig.url + 'upcoming.tpl',
           attr: 'upcoming'
         }, {
           label: 'Following',
           url: conFig.url + 'following.tpl',
           attr: 'following'
         }, {
           label: 'Downtime',
           url: conFig.url + 'downtime.tpl',
           attr: 'downtime'
         }, {
           label: 'Complete',
           url: conFig.url + 'complete.tpl',
           attr: 'complete'
         }];


         loadMore = $scope;
         $scope.incompletepaging = 30;
         $scope.upcomingpaging = 30;
         $scope.followingpaging = 30;
         $scope.downtimepaging = 30;
         $scope.completepaging = 30;
     // $scope.checkincompletepaging = false;
     // $scope.checkupcomingpaging = false;
     // $scope.checkfollowingpaging = false;
     // $scope.checkdowntimepaging = false;
     // $scope.checkcompletepaging = false;
     $scope.loadingState = false;
     // tab type
     $scope.typeTask = [];
     /*for variable*/
     $scope.dataTask = [];

     // for user
     $scope.currentUser = {};
     $scope.allUser = [];
     $scope.userMessage = [];
     $scope.userFollow = [];
     $scope.onTaskFollow = [];
     $scope.onTaskAssign = {};
     $scope.holdTaskAssign = '';
     // for  my task
     $scope.oTask = [];
     $scope.checkedTask = false;
     $scope.currentTask = {};
     $scope.currentoTask = [];
     $scope.sumAttached = [];
     $scope.mainTask = {};
     $scope.parentTask = {};
     $scope.storeParent = [];
     // for data my following
     $scope.tabFollow = [];
     $scope.followComplete = [];
     // for date
     $scope.fdate = conFig.formatDate;
     $scope.fldate = conFig.fLongDate;
     // for obj create task
     $scope.formData = {};
     // subtask
     $scope.listSubTask = [];
     $scope.dataSubTask = [];
     $scope.subComplete = [];
     $scope.checkSubComplete = false;
     // for task detail data
     $scope.detailTask = [];
     $scope.currentItemTab = {};
     $scope.selectedSubTask = false;
     // for udpate input description
     $scope.coundown = 20;
     $scope.myTime = null;
     $scope.switchMainToSub = false;
     $scope.historyTask = [];
     $scope.delayHistory = true;
     $scope.scrollBottom = [];
     //role
     $scope.roleName = role;
     $scope.isAdmin = isAdmin;
     $scope.isManager = isManager;
     $scope.isReporter = isReporter;
     $scope.isScheduler = isScheduler;
     $scope.isFieldinstaller = isFieldinstaller;
     $scope.isSalesman = isSalesman;
     $scope.isWarehouse = isWarehouse;
     $scope.isStrategicDevelopment = isStrategicDevelopment;
     $scope.isSupportAssistant = isSupportAssistant;
     $scope.isOutsideSales = isOutsideSales;
     $scope.isInFieldSupervisor = isInFieldSupervisor;
     $scope.maxResult = 0;
     $scope.group_id = '';
     // show more
     $scope.toHistory = 0;
     $scope.strActivityHistory = "";
     $scope.toAttached = 0;
     $scope.strActivityAttched = "";
     $scope.toComment = 0;
     $scope.strActivityComment = "";
     $scope.onUpLoading = [];
     $scope.strActivitySubTasks = "";
     $scope.countSubTasks = 0;
     $scope.onMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(andRoid)|(Linux)|(webOS)/i) != null;
     $scope.Input_value = {};
     $scope.autocompleteList = {};
     $scope.autocompleteList.refferedAssignUser = [];
     $scope.autocompleteList.refferedFollower = [];
     $scope.files = [];
     $scope.uploadType = "";
     $scope.pushFollowFromChangeGroup = false;
     $scope.taskDesLen = 270;
     $scope.followerLabel = '';

     /*end variable*/
     var tasks = new taskView();
     $scope.dataTaskHtml = {};
     $scope.renderTemplateData = function() {
       dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskMenuHeadermodal.tpl').success(function(results) {
         $scope.dataTaskHtml.menuHeader = results;
         dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskMenuSwitchTabmodal.tpl').success(function(results) {
           $scope.dataTaskHtml.switchTab = results;
           dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskTabIncompletemodal.tpl').success(function(results) {
             $scope.dataTaskHtml.tabIncomplete = results;
             dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskTabUpcomingmodal.tpl').success(function(results) {
               $scope.dataTaskHtml.tabUpcoming = results;
               dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskTabFollowingmodal.tpl').success(function(results) {
                 $scope.dataTaskHtml.tabFollowing = results;
                 dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskTabDowntimemodal.tpl').success(function(results) {
                   $scope.dataTaskHtml.tabDowntime = results;
                   dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskTabCompletemodal.tpl').success(function(results) {
                     $scope.dataTaskHtml.tabComplete = results;
                     dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskPopupSearchmodal.tpl').success(function(results) {
                       $scope.dataTaskHtml.searchTask = results;
                       $scope.startpage();
                       $timeout(function() {
                         setHeight("#main-content");
                       }, 1)
                     });
                   })
                 })
               })
             })
           })
         });
       });
     }
     $scope.openByGetTemplate = function(style) {
       $ionicLoading.show({ template: templateLoading });
       $timeout(function() {
         switch (style) {
           case 'appointmentToSchedule':
           dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupAppointmentToSchedulemodal.tpl').success(function(results) {
             $scope.dataTaskHtml.appointmentToSchedule = results;
             $scope.showTarget('#appointmentToSchedule');
             $ionicLoading.hide();
           });
           break;
           case 'popupAddTask':
           $scope.followerLabel = '';
           dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskPopupAddmodal.tpl').success(function(results) {
             $scope.dataTaskHtml.popupAddTask = results;
             $scope.showTarget('#popupAddTask');
             $scope.resetForm();
             $ionicLoading.hide();
           });
           break;
           case 'popupEditTask':
           dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskPopupEditmodal.tpl').success(function(results) {
             $scope.dataTaskHtml.popupEditTask = results;
             $scope.showTarget('#popupEditTask');
             $ionicLoading.hide();
           });
           break;
           case 'popupTaskContent':
           dataHtml.getTemplate('templates/dashboard/tasks/task-content/task-content.tpl').success(function(results) {
             $scope.dataTaskHtml.popupTaskContent = results;
             dataHtml.getTemplate('templates/dashboard/tasks/task-content/task-contentMenuHeadermodal.tpl').success(function(results) {
               $scope.dataTaskHtml.taskContentMenuHeader = results;
               dataHtml.getTemplate('templates/dashboard/tasks/task-content/task-contentDetailmodal.tpl').success(function(results) {
                 $scope.dataTaskHtml.taskContentDetail = results;
                 dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskPopupChangeAssigneemodal.tpl').success(function(results) {
                   $scope.dataTaskHtml.taskChangeAssignee = results;
                   startpage = false;
                   $ionicLoading.hide();
                 })
               });
             });
           });
           break;
           case 'popupTaskSubtask':
           dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskPopupTaskSubtaskmodal.tpl').success(function(results) {
             $scope.dataTaskHtml.popupTaskSubtask = results;
             $scope.showTarget('#popupTaskSubtask');
             $ionicLoading.hide();
           });
           break;
           case 'popupTaskSubtaskAdd':
           dataHtml.getTemplate('templates/dashboard/tasks/tasks/taskPopupTaskSubtaskAddmodal.tpl').success(function(results) {
             $scope.dataTaskHtml.popupTaskSubtaskAdd = results;
             $scope.showTarget('#popupTaskSubtaskAdd');
             $ionicLoading.hide();
           });
           break;
           case 'popupTaskFilter':
           dataHtml.getTemplate('templates/dashboard/tasks/task-filter/task-filterContent.tpl').success(function(results) {
             $scope.dataTaskHtml.popupTaskFilter = results;
             $scope.showTarget('#popupTaskFilter');
             $ionicLoading.hide();
           });
           break;
           case 'optionTaskFilter':
           dataHtml.getTemplate('templates/dashboard/tasks/task-filter/task-filterOptions.tpl').success(function(results) {
             $scope.dataTaskHtml.optionTaskFilter = results;
             $scope.showTarget('#optionTaskFilter');
             $ionicLoading.hide();
           });
           break;
           case 'popupEditTaskFilter':
           dataHtml.getTemplate('templates/dashboard/tasks/task-filter/task-filterEditFilter.tpl').success(function(results) {
             $scope.dataTaskHtml.popupEditTaskFilter = results;
             $scope.showTarget('#popupEditTaskFilter');
             $ionicLoading.hide();
           });
           break;
           case 'popupTaskFilterQuery':
           dataHtml.getTemplate('templates/dashboard/tasks/task-filter/task-filterFilterQuery.tpl').success(function(results) {
             $scope.dataTaskHtml.popupTaskFilterQuery = results;
             $scope.showTarget('#popupTaskFilterQuery');
             $ionicLoading.hide();
           });
           break;
           case 'popupAddTaskFilterQuery':
           dataHtml.getTemplate('templates/dashboard/tasks/task-filter/task-filterFilterQueryAdd.tpl').success(function(results) {
             $scope.dataTaskHtml.popupAddTaskFilterQuery = results;
             $scope.showTarget('#popupAddTaskFilterQuery');
             $ionicLoading.hide();
           });
           break;
           case 'popupEditTaskFilterQuery':
           dataHtml.getTemplate('templates/dashboard/tasks/task-filter/task-filterFilterQueryEdit.tpl').success(function(results) {
             $scope.dataTaskHtml.popupEditTaskFilterQuery = results;
             $scope.showTarget('#popupEditTaskFilterQuery');
             $ionicLoading.hide();
           });
           break;
           case 'confirmDeleteTaskFilterQuery':
           dataHtml.getTemplate('templates/dashboard/tasks/task-filter/task-filterFilterQueryDelete.tpl').success(function(results) {
             $scope.dataTaskHtml.confirmDeleteTaskFilterQuery = results;
             $scope.showTarget('#confirmDeleteTaskFilterQuery');
             $ionicLoading.hide();
           });
           break;
         }
       }, 500);
}
     $scope.onClickTab = function(tab) { // for tab event
       $scope.checkloadmove = 1;
       $scope.currentItemTab = tab;
       $scope.currentTab = tab.url;
       $scope.convertTypeByDate();
       $scope.renderData();
       $scope.getFollow();
         // active current first task exits
         // if (tab.attr != 'following') {
         //     $scope.autoClick($scope.oTask, tab.attr);
         // } else {
         //     $scope.autoClick($scope.tabFollow, tab.attr);
         // }
         // setTimeout(function() {
         //     // $('.scrollbar').perfectScrollbar('update');
         //     $scope.checkloadmove = 1;
         // }, 1000);
       }
     $scope.isActiveTab = function(tabUrl) { // for active tab
       return tabUrl == $scope.currentTab;
     }
     $scope.autoClick = function(task, type) { // for init autoclick init highlight
       if (task.length <= 0) {
         return
       };
       if (type != 'following') {
         if (_.filter(task, function(val) {
           return val.type == type;
         }).length > 0) {
           var taskByType = _.filter(task, function(val) {
             return val.type == type;
           });
           type == 'complete' ? taskByType = _.sortBy(taskByType, 'modified_date') : taskByType = _.sortBy(taskByType, 'id');
           type == 'complete' ? $scope.getCurrentTask(_.last(taskByType), task) : $scope.getCurrentTask(_.first(taskByType), task);
         }
       } else {
         $scope.getCurrentTask(_.first(_.sortBy(task, 'id')), task);
       }
     }
     $scope.isHighLight = function(id) { // for HighLight input task
       return id == $scope.highlightTask;
     }
     $scope.isActiveTab = function(tabUrl) { // check uncheck task
       return tabUrl == $scope.currentTab;
     }
     $scope.uncheckAll = function() {
       $scope.checkedTask.splice(0, $scope.checkedTask.length);
     }
     $scope.clickOnCLick = function(value, checked) {
       $scope.checkOnClick(value, checked);
     }
     $scope.checkOnClick = function(value, checked) {
         // $('input[name="changeType"]').attr('checked', false);
         $ionicLoading.show({
           template: templateLoading
         });
         $scope.switchMainToSub = false;
         $scope.delayHistory = false;
         var idx = _.indexOf($scope.oTask, value);
         switch (value.type) {
           case 'upcoming':
           $scope.oTask[idx].beforetype = 2; //'upcoming';
           $scope.oTask[idx].type = 'complete';
           break;
           case 'downtime':
           $scope.oTask[idx].beforetype = 4; //'downtime';
           $scope.oTask[idx].type = 'complete';
           break;
           case 'incomplete':
           $scope.oTask[idx].beforetype = 1; //'incomplete';
           $scope.oTask[idx].type = 'complete';
           break;
           default:
           if ($scope.oTask[idx].beforetype == 4) {
             $scope.oTask[idx].type = 'downtime';
           } else if ($scope.oTask[idx].beforetype == 1) {
             $scope.oTask[idx].type = 'incomplete';
           } else {
             var tStart = globalParseDate(Date.parseDate($scope.oTask[idx].starttime));
             var tNow = globalParseDate(new Date(_.now()));
             tStart.getTime() <= tNow.getTime() ? $scope.oTask[idx].type = 'incomplete' : $scope.oTask[idx].type = 'upcoming';
           }
           $scope.oTask[idx].beforetype = 0;
         }
         var type_id = _.where($scope.typeTask, {
           name: $scope.oTask[idx].type
         })[0].id;
         var changetype = _.extend($scope.oTask[idx], {
           type_id: type_id,
           before_id: $scope.oTask[idx].beforetype
         });
         tasks.changeType(changetype).then(function() {
           tasks.getdataTask($scope.incompletepaging, $scope.upcomingpaging, $scope.followingpaging, $scope.downtimepaging, $scope.completepaging).then(function() {
             $scope.dataTask = tasks.dataTask;
             $scope.closeTarget('#popupTaskContent');

             $scope.convertTypeByDate();
             $scope.renderData();
             $scope.getFollow();

             var lengthTaskType = _.where($scope.dataTask, {
               type: $scope.currentItemTab.attr
           }); //.length == 0 ? $('#contentTasks').hide() : '';
             if ($scope.currentItemTab.attr == 'complete' || $scope.currentItemTab.attr == 'incomplete') {
               if (lengthTaskType.length == 0) {
                 $scope.parentTask = {};
               }
               $scope.sendMail($scope.oTask[idx].id, 'incomplete');
             } else {
               $scope.delayHistory = true;
             }
             if (lengthTaskType.length == 0) {
               $scope.delayHistory = true;
             } else {
               if ($scope.currentItemTab.attr != 'following') {
                 $scope.autoClick($scope.oTask, $scope.currentItemTab.attr);
               } else {
                 $scope.autoClick($scope.tabFollow, $scope.currentItemTab.attr);
               }
             }
           });
         });
       };
       $scope.setTime = false;
       $scope.$watch('currentTask.duedate[0]', function(value) {
         $timeout(function() {
          if (value && $scope.setTime) {
            $('#startdate').val(moment(value).format('MM/DD/YYYY'));
            $scope.dueTimeTask($('#startdate').val(), $('#enddate').val(), $scope.currentTask.id);
          }
        }, 1000)

       })
       $scope.$watch('currentTask.duedate[1]', function(value) {
         $timeout(function() {
           if (value && $scope.setTime) {
            $('#enddate').val(moment(value).format('MM/DD/YYYY'));
            $scope.dueTimeTask($('#startdate').val(), $('#enddate').val(), $scope.currentTask.id);
          }
        }, 1000)
       })
     $scope.getCurrentTask = function(Task, oTask, style, whatfor, back) { // for click get current taskgetcur
      // $timeout(function() {
      //   $scope.checkedTask = false;
      // }, 100)
      $('#chechBoxDiff').prop('checked', false);
      $scope.checkedTask = false;

      // $ionicScrollDelegate.$getByHandle('scrollTaskContentDetail').resize();
      // $ionicScrollDelegate.$getByHandle('scrollTaskContentDetail').scrollTop(true);
      
      document.activeElement.blur();
     //  $timeout(function() {
     //   angular.element(document.querySelector('#taskDescription')).focus();
     //   angular.element(document.querySelector('#taskDescription')).blur();
     // }, 1)
     $scope.setTime = false;
     if (style == 'open') {
       $scope.showTarget('#popupTaskContent');
     }
     if (whatfor == undefined) {
       var oTask = $scope.oTask;
       if (Task.type == "following") oTask = $scope.tabFollow;
     }
     var idx = _.indexOf(oTask, Task);
     if (idx == -1) {
       idx = _.findLastIndex(oTask, {
         id: Task.id
       });
     }
     $scope.currentoTask = Task;
     $scope.currentTask = {
       id: '',
       duedate: '',
       name: '',
       taskname: '',
       taskdes: '',
       type: '',
     }
     $scope.currentTask.id = oTask[idx].id;
     $scope.currentTask.duedate = [oTask[idx].starttime, oTask[idx].endtime];
     $scope.currentTask.taskname = oTask[idx].name;
     $scope.currentTask.taskname = oTask[idx].taskname;
     $scope.currentTask.taskdes = oTask[idx].taskdes;
     $scope.currentTask.type = oTask[idx].type;
     $scope.currentTask.ownerId = oTask[idx].ownerId;
     $scope.onTaskAssign = {};
     if (_.where($scope.allUser, {
       id: oTask[idx].assignerId
     }).length > 0) {
       $scope.onTaskAssign = (_.where($scope.allUser, {
         id: oTask[idx].assignerId
       })[0]);
     }
     $scope.holdTaskAssign = $scope.onTaskAssign.screen_name;
     var array = [];
     array.push($scope.onTaskAssign.id);
     $scope.initialChangeAssignUser = array;
     $scope.onTaskFollow = [];
     oTask[idx].listFollowingId = oTask[idx].listFollowingId.getUnique();
     $scope.initialAddFollower = oTask[idx].listFollowingId;
     _.each(oTask[idx].listFollowingId, function(val) {
       if (_.where($scope.allUser, {
         id: val
       }).length > 0) {
         if (parseInt($scope.onTaskAssign.id) != parseInt(val)) {
           $scope.onTaskFollow.push(_.where($scope.allUser, {
             id: val
           })[0]);
         }

       }
     });
     $scope.parentTask = {
       object: oTask,
       item: Task
     }
             // get list subtask
             if (whatfor == undefined) {
               $scope.selectedSubTask = false;
               $scope.mainTask = {
                 object: oTask,
                 item: Task
               }
               $scope.storeParent = [];
               $scope.storeParent.push($scope.mainTask);
               $scope.parentTask = $scope.mainTask;
               $scope.highlightTask = $scope.mainTask.item.id;
               $('.breadcum').addClass('hidden');
               $('.icon-subtask-1').removeClass('hidden');
             } else {
               if (back == undefined) {
                 $scope.storeParent.push($scope.parentTask);
               } else {
                 $scope.storeParent.splice($scope.storeParent.length - 1);
               }
               Task.type == 'complete' ? $scope.checkSubComplete = true : $scope.checkSubComplete = false;
               $scope.selectedSubTask = true;
               $('.breadcum').removeClass('hidden');
             }
             tasks.getListSubTask(Task).then(function() {
               $scope.dataSubTask = tasks.dataSubTask;
               $scope.listSubTask = tasks.listSubTask;
               $scope.subComplete = tasks.subComplete;
               $scope.group_id = tasks.group_id;
               $scope.grouptaskReassign = angular.copy(tasks.group_id);
               tasks.getMessage($scope.currentTask.id).then(function() {
                 $scope.delayHistory ? $scope.getHistory($scope.currentTask.id) : '';
                 $scope.delayHistory = true;
                 $ionicScrollDelegate.$getByHandle('scrollTaskContentDetail').resize();
                 $ionicScrollDelegate.$getByHandle('scrollTaskContentDetail').scrollBottom(true);
               });
             });
         // edit by haudao
         $('#startdate').val(moment($scope.currentTask.duedate[0]).format('MM/DD/YYYY'));
         $('#enddate').val(moment($scope.currentTask.duedate[1]).format('MM/DD/YYYY'));
         $timeout(function() {
           $scope.setTime = true;
         }, 2000);
         // end edit
         // console.log($scope.subComplete);
       }
     $scope.isActiveComment = function() { // active more Comment
       return tasks.toComment > 0 ? false : true;
     }
     $scope.moreComment = function() {
       $scope.toComment > 0 ? $scope.toComment = 0 : $scope.toComment = tasks.toComment;
       $scope.commentActivity();
     }
     $scope.commentActivity = function() {
       $scope.toComment > 0 ? $scope.strActivityComment = ($scope.toComment + " more comment") : $scope.strActivityComment = "Hide comment activity";
     }
     $scope.renderData = function() { // for status task
       var userOwnerTask1 = _.where($scope.dataTask, {
         ownerId: $scope.currentUser.id,
         type: 'complete'
       });
       var userOwnerTask2 = _.where($scope.dataTask, {
         ownerId: $scope.currentUser.id,
         type: 'downtime'
       });
       var userAssignTask = _.where($scope.dataTask, {
         assignerId: $scope.currentUser.id
       });
       $scope.oTask = _.union(userOwnerTask1, userOwnerTask2, userAssignTask);
         // console.log($scope.oTask);
         // edit by haudao
         // $scope.totalDisplay();
         // end edit
       }
     $scope.getFollow = function() { // for follow
       var _follow = [];
       var _fcomplete = [];
       _.each($scope.dataTask, function(val, index) {
         var item = val.listFollowingId;
         if (_.indexOf(item, $scope.currentUser.id) > -1) {
           if (val.type == 'complete') {
             val.f_disiable = 'oComplete';
             _fcomplete.push(val);
           } else {
             val.type = 'following';
             val.f_disiable = 'oFollow';
             _follow.push(val);
           }
         }
       });
       $scope.tabFollow = _follow;
         // console.log($scope.tabFollow.length);
         $scope.oTask = _.union($scope.oTask, _fcomplete);
         // edit by haudao
         $timeout(function() {
           $scope.totalDisplay();
         }, 2000);
         // end edit
         //$scope.followComplete = _fcomplete;
       }
     $scope.statisticalAttached = function() { // for statistical attached file
       var attachedFile = _.where($scope.detailTask, {
         type: "file"
       });
       var attachedImage = _.where($scope.detailTask, {
         type: "img"
       });
       var attached = _.union(attachedFile, attachedImage);
       $scope.sumAttached = [];
       $scope.sumAttached = _.each(attached, function(val) {
         var fname = val.content.substring(val.content.lastIndexOf('/') + 1);
         return _.extend(val, {
           filename: fname,
         });
       });

       _.each(_.difference($scope.detailTask, attached), function(val) {
         return _.extend(val, {
           filename: '',
         });
       });
       $scope.sumAttached.length - tasks.limitTo > 0 ? tasks.toAttached = $scope.sumAttached.length - tasks.limitTo : tasks.toAttached = 0;
       $scope.toAttached = tasks.toAttached;
       $scope.attachedActivity();
         // $scope.scrollMessage();

         if($scope.tabTaskActive=='Following'){
          if(_.where($scope.tabFollow,{id: $scope.currentTask.id}).length){
            _.where($scope.tabFollow, {id: $scope.currentTask.id})[0].filesCount = $scope.sumAttached.length;
          }else{
           _.where($scope.listSubTaskOnPopup, {id: $scope.currentTask.id})[0].filesCount = $scope.sumAttached.length;
         }
       }
       else{
        if(_.where($scope.oTask, {id: $scope.currentTask.id}).length){
          _.where($scope.oTask, {id: $scope.currentTask.id})[0].filesCount = $scope.sumAttached.length;
        }
        else{
          _.where($scope.listSubTaskOnPopup, {id: $scope.currentTask.id})[0].filesCount = $scope.sumAttached.length;
        }
      }
      
    }
     $scope.isActiveAttached = function() { // active more Attached
       return tasks.toAttached > 0 ? false : true;
     }
     $scope.moreAttached = function() {
       $scope.toAttached > 0 ? $scope.toAttached = 0 : $scope.toAttached = tasks.toAttached;
       $scope.attachedActivity();
     }
     $scope.attachedActivity = function() {
       $scope.toAttached > 0 ? $scope.strActivityAttched = ($scope.toAttached + " more attached") : $scope.strActivityAttched = "Hide attached activity";
     }
     $scope.setdefaultAssign = function() {
       $scope.formData.assign = '';
       return $scope.formData.assign = {
         id: null
       };
     }
         // edit by haudao
         $scope.resetForm = function() {
           $timeout(function() {
             try {
               document.getElementById('formAddTask').reset();
               document.getElementById('formEditTask').reset();
             } catch (e) {
               console.log(e);
             }
           }, 500);
           $scope.files = [];
           $scope.formData = {};
           $scope.Input_value = {};
           $scope.formData.usersfollow = {};
           $scope.formData.assign = {};
           $scope.initialAssignUser = [];
           $scope.initialFollower = [];
           $scope.userFollow = [];
           $scope.fromDate = moment().format(conFig.formatDate.toUpperCase());
           $scope.toDate = moment().add(1, 'days').format(conFig.formatDate.toUpperCase());
           $scope.formData.type = 'Incomplete';
           $scope.setValueType('Incomplete');
           $scope.formData.Group = '';
         }
         $scope.uploadAmazon = function(dataFiles) {
           countDataFiles = dataFiles.length;
           angular.forEach(dataFiles, function(item) {
             $scope.fileUploadData = {};
             $scope.fileUploadData.type = item.type;
             $scope.fileUploadData.name = item.name;
             $scope.fileUploadData.bucket = bucketName;
             $scope.fileUploadData.acl = aclConfig;
             $scope.fileUploadData.for = 'tasks';
             Login.getConfigFileUpload($scope.fileUploadData).success(function(data) {
               var Uoptions = {};
               Uoptions.fileKey = "file";
               Uoptions.fileName = data.folder + '/' + data.microtime + item.name;
               Uoptions.mimeType = item.type;
               Uoptions.chunkedMode = false;
               Uoptions.headers = {
                 connection: "close"
               };
               Uoptions.params = {
                 "Key": data.folder + '/' + data.microtime + item.name,
                 "AWSAccessKeyId": data.awsAccessKeyId,
                 "acl": data.acl,
                 "Policy": data.policy,
                 "Signature": data.signature,
                 "success_action_status": data.successActionStatus,
                 "Content-Type": item.type
               };
               $cordovaFileTransfer.upload('http://' + bucketName + '.s3.amazonaws.com/', item.localURL, Uoptions).then(function(return_data) {
                 try {
                   var fileLocation = return_data.headers.Location;
                 } catch (e) {
                   $scope.jsonObject = xml2json.parser(return_data.response);
                   var fileLocation = $scope.jsonObject.postresponse.location;
                 }
                 console.log(fileLocation, 'success');
                 var type = 'file';
                 var ext = fileLocation.substring(fileLocation.lastIndexOf('.') + 1);
                 if (ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "png" || ext == "PNG") {
                   var type = 'img';
                 }
                 if ($scope.uploadType == "addTask") {
                   $scope.formData.fileUploadded.push({
                     path: fileLocation,
                     type: type
                   });
                   console.log($scope.uploadType, $scope.formData.fileUploadded.length, dataFiles.length)
                   if ($scope.formData.fileUploadded.length == countDataFiles) {
                     $scope.formData.files = undefined;
                     console.log('create task');
                     $scope.createTask();
                   }
                 } else if ($scope.uploadType == "addComment") {
                   console.log('add comment')
                   $scope.MessageTask(type, fileLocation);
                 }
               }, function(err) {
                 countDataFiles--;
                 $ionicLoading.hide();

                 $ionicScrollDelegate.$getByHandle('scrollTaskContentDetail').resize();
                 $ionicScrollDelegate.$getByHandle('scrollTaskContentDetail').scrollBottom(true);
                 
                 $cordovaToast.showLongTop('Can\'t upload ' + item.name);
                 console.log(err.body);
               });
             });
           });

         }
         // end edit
         $scope.beforeCreateTask = function() {
           $ionicLoading.show({
             template: templateLoading
           });
           $scope.formData.fileUploadded = [];
           if ($scope.files != undefined && $scope.files.length) {
             $scope.uploadAmazon($scope.files);
           } else {
             $scope.createTask();
           }
         }
     $scope.createTask = function() { // for create task
       var objParam = {};
       var objParam = _.extend($scope.formData, {
         usersfollow: $scope.userFollow,
         starttime: $('input[name="starttime"]').val(),
         endtime: $('input[name="endtime"]').val(),
         fdate: conFig.fDatetoServer
       });
       $scope.formData.type == 'Downtime' ? objParam.usersfollow = _.filter(objParam.usersfollow, function(val) {
         return val.id != parseInt(tasks.currentIdLogin);
       }) : '';
       if ($scope.formData.assign != undefined) {
         objParam.usersfollow = _.filter(objParam.usersfollow, function(val) {
           return val.id != parseInt($scope.formData.assign.id);
         })
         if ($scope.formData.assign.id == undefined) {
           $scope.setdefaultAssign();
         }
       } else {
         $scope.setdefaultAssign();
       }
         // $timeout(function(){console.log($scope.formData.assign)},5000);
         // return;
         // auto owner follow
         var ownerFollowing = _.where($scope.allUser, {
           id: parseInt(tasks.currentIdLogin)
         });
         if (($scope.formData.type == 'Incomplete' && ($scope.formData.assign == undefined || $scope.formData.assign == '')) || $scope.formData.type == 'Incomplete' && $scope.formData.assign != undefined && parseInt(tasks.currentIdLogin) != parseInt($scope.formData.assign.id)) {
           objParam.usersfollow = _.union(objParam.usersfollow, ownerFollowing);
         }
         tasks.createTask(objParam).then(function() {
           tasks.getdataTask($scope.incompletepaging, $scope.upcomingpaging, $scope.followingpaging, $scope.downtimepaging, $scope.completepaging).then(function() {
             $scope.dataTask = tasks.dataTask;
             $scope.convertTypeByDate();
             $scope.renderData();
             $scope.getFollow();
             if ($scope.mainTask.item != undefined) {
               $scope.highlightTask = $scope.mainTask.item.id;
             }
             var lengthTaskObj = _.where($scope.dataTask, {
               type: $scope.currentItemTab.attr,
               id: tasks.createId
             });
             var lengthTaskType = _.where($scope.dataTask, {
               type: $scope.currentItemTab.attr
             });
             if (lengthTaskObj.length > 0 && lengthTaskType.length == 1) {
               $scope.sendMail(tasks.createId, 'createTask');
               $scope.delayHistory = false;
               if ($scope.currentItemTab.attr != 'following') {
                 $scope.autoClick($scope.oTask, $scope.currentItemTab.attr);
               } else {
                 $scope.autoClick($scope.tabFollow, $scope.currentItemTab.attr);
               }
             } else {
               $scope.sendMail(tasks.createId, 'createTask');
             }
             $ionicLoading.hide();
             $scope.closeTarget('#popupAddTask');
             $scope.resetForm();
             $cordovaToast.showLongTop('Task has been created successfully!!!');
           })
         })
       }
     $scope.realAssign = function() { // hold current item selecting
       $scope.holdTaskAssign = $scope.onTaskAssign.screen_name;
     }
     $scope.onSelect = function($item, $model, $label) { // change assign
       if ($item.id != $scope.currentIdLogin) {
         var diff = _.difference($scope.dataTask, [$scope.currentoTask]);
         $scope.dataTask = diff;
       }
       var oldAssignee = $scope.onTaskAssign;
       $scope.onTaskAssign = $item;
       tasks.updateAssign($item, $scope.currentoTask).then(function() {
         if (tasks.tasktype == 1) {
           tasks.getdataTask($scope.incompletepaging, $scope.upcomingpaging, $scope.followingpaging, $scope.downtimepaging, $scope.completepaging).then(function() {
             $scope.dataTask = tasks.dataTask;
             $scope.convertTypeByDate();
             $scope.renderData();
             $scope.getFollow();
             $scope.highlightTask = $scope.mainTask.item.id;
                     // $scope.includeJs();
                     $scope.sendMail($scope.currentTask.id, 'assign');
                     $scope.onTaskFollow.push(oldAssignee);
                     $scope.arrayDataFollower = $scope.onTaskFollow;
                     $scope.updateFollow();
                     // $scope.refreshTask();
                   });
         } else {
           $scope.convertTypeByDate();
           $scope.renderData();
           $scope.getFollow();
           $scope.highlightTask = $scope.mainTask.item.id;
                 // $scope.includeJs();
                 $scope.sendMail($scope.currentTask.id, 'assign');
                 $scope.onTaskFollow.push(oldAssignee);
                 $scope.arrayDataFollower = $scope.onTaskFollow;
                 $scope.updateFollow();
               }
             });
     }
     $scope.deadlineTask = function(val_time, task_id) { // change deadline
       tasks.deadlineTask(val_time, task_id).then(function() {
         $scope.convertTypeByDate();
         $scope.renderData();
         $scope.getFollow();
         $scope.highlightTask = $scope.mainTask.item.id;
             // $scope.includeJs();
             $scope.sendMail(task_id, 'deadline');
           });
     }
     $scope.dueTimeTask = function(start_time, end_time, task_id) { // change dueTime
      $ionicLoading.show({
       template: templateLoading
     });
      tasks.dueTimeTask(start_time, end_time, task_id).then(function() {
        $ionicLoading.hide();
        $scope.setTime = false;
        var s = Date.parseDate(start_time);
        var tStart = globalParseDate(s);
        var e = Date.parseDate(end_time);
        $scope.currentTask.duedate = [new Date(s), new Date(e)];
        if($scope.tabTaskActive == 'Following'){
          _.where($scope.tabFollow, {
           id: task_id
         })[0].starttime = new Date(s);
          _.where($scope.tabFollow, {
           id: task_id
         })[0].endtime = new Date(e);
        }
        else{
          _.where($scope.oTask, {
           id: task_id
         })[0].starttime = new Date(s);
          _.where($scope.oTask, {
           id: task_id
         })[0].endtime = new Date(e);
        }


        if (($scope.currentoTask.type == 'incomplete' || $scope.currentoTask.type == 'upcoming') && !$scope.selectedSubTask) {
         $scope.switchTabByTime(tStart, e, task_id);
       } else {
         $scope.dataTask = tasks.dataTask;
         (_.where(tasks.dataTask, {
           id: task_id
         })[0]).endtime = (new Date(e));
         (_.where(tasks.dataTask, {
           id: task_id
         })[0]).starttime = (new Date(s));
         $scope.convertTypeByDate();
         $scope.renderData();
         $scope.getFollow();
         $scope.highlightTask = $scope.mainTask.item.id;
         $timeout(function() {
          $scope.setTime = true;
        }, 2000)

                 // $scope.includeJs();
                 // $scope.sendMail(task_id, 'dueTime');
               }
             });
    }
     $scope.switchTabByTime = function(tStart, end_time, task_id) { // switch after change duetime if there exits
       var tNow = globalParseDate(new Date(_.now()));
       if ((tStart.getTime() <= tNow.getTime() && $scope.currentoTask.type == 'upcoming') || (tStart.getTime() > tNow.getTime() && $scope.currentoTask.type == 'incomplete')) {
         tasks.getdataTask($scope.incompletepaging, $scope.upcomingpaging, $scope.followingpaging, $scope.downtimepaging, $scope.completepaging).then(function() {
           $scope.dataTask = tasks.dataTask;
           $scope.convertTypeByDate();
           _.where($scope.dataTask, {
             type: $scope.currentItemTab.attr
           }).length == 0 ? $('#contentTasks').hide() : '';
           $scope.renderData();
           $scope.getFollow();
           $scope.autoClick($scope.oTask, $scope.currentItemTab.attr);
           $scope.sendMail(task_id, 'dueTime');
         });
       } else {
         $scope.dataTask = tasks.dataTask;
         (_.where(tasks.dataTask, {
           id: task_id
         })[0]).endtime = (new Date(end_time));
         $scope.convertTypeByDate();
         $scope.renderData();
         $scope.getFollow();
         $scope.highlightTask = $scope.mainTask.item.id;
             // $scope.includeJs();
             $scope.sendMail(task_id, 'dueTime');
           }
         }
     $scope.MessageTask = function(type, link) { // message
      if (this.formData.msg == '') return;
      if (!type) {
       type = 'msg';
     } else {
       this.formData.msg = link;
     }
     $ionicLoading.show({
       template: templateLoading
     });
     tasks.messageTask($scope.currentTask.id, this.formData.msg, type).then(function() {
       $ionicLoading.hide();
       tasks.getMessage($scope.currentTask.id).then(function() {
        if($scope.tabTaskActive=='Following'){
          if(_.where($scope.tabFollow, {id: $scope.currentTask.id}).length){
            _.where($scope.tabFollow, {id: $scope.currentTask.id})[0].commentsCount = tasks.detailTask.length;
          }
          else{
            _.where($scope.listSubTaskOnPopup, {id: $scope.currentTask.id})[0].commentsCount = tasks.detailTask.length;
          }
        }
        else{
          if(_.where($scope.oTask, {id: $scope.currentTask.id}).length){
            _.where($scope.oTask, {id: $scope.currentTask.id})[0].commentsCount = tasks.detailTask.length;
          }
          else{
            _.where($scope.listSubTaskOnPopup, {id: $scope.currentTask.id})[0].commentsCount = tasks.detailTask.length;
          } 
        }
        $scope.fileName = '';
        $scope.detailTask = tasks.detailTask;
        $scope.statisticalAttached();
        $scope.toComment = tasks.toComment;
        $scope.commentActivity();
        $scope.sendMail(tasks.createId, 'MessageTask');
                     // $scope.includeJs();
                     $ionicScrollDelegate.$getByHandle('scrollTaskContentDetail').resize();
                     $ionicScrollDelegate.$getByHandle('scrollTaskContentDetail').scrollBottom(true);
                   });
     });
     this.formData.msg = '';
   }


     // $scope.scrollMessage = function() { // scroll message
     //     setTimeout(function() {
     //         $scope.$apply(function(val) {
     //             $scope.scrollBottom = _.union($scope.detailTask, $scope.sumAttached, $scope.listSubTask);
     //         });
     //     }, 100);
     // }
     $scope.updateFollow = function($item, $model, $label) { // update Follow
       if (!$scope.formData.assign || $scope.formData.assign.length < 1) {
         $cordovaToast.showLongTop('The assignee is required, so your action will been reverted');
         return;
       }else{
        var ownerFollowing = _.where($scope.allUser, {
          id: parseInt(tasks.currentIdLogin)
        });
        $scope.userFollow = _.union($scope.userFollow, ownerFollowing);
        $scope.userFollow = _.filter($scope.userFollow, function(val) {
          return parseInt(val.id) != parseInt($scope.formData.assign.id);
        });   
      }
       // if (!$scope.userFollow || $scope.userFollow.length < 1) {
       //   $cordovaToast.showLongTop('The assignee is required, so your action will been reverted');
       //   return;
       // }
       tasks.updateFollow($scope.userFollow, $scope.currentTask.id, $scope.currentItemTab.attr).then(function() {
         if ($scope.formData.assign.id != $scope.currentIdLogin) {
           var diff = _.difference($scope.dataTask, [$scope.currentoTask]);
           $scope.dataTask = diff;
         }
         var oldAssignee = $scope.onTaskAssign;
         $scope.onTaskAssign = $scope.formData.assign;
         tasks.updateAssign($scope.formData.assign, $scope.currentoTask).then(function() {
           $scope.closeTarget("#popupEditTask");
           tasks.getdataTask($scope.incompletepaging, $scope.upcomingpaging, $scope.followingpaging, $scope.downtimepaging, $scope.completepaging).then(function() {
             $scope.onTaskFollow = $scope.userFollow;
             $scope.dataTask = tasks.dataTask;
             $scope.convertTypeByDate();
             $scope.renderData();
             $scope.getFollow();
             $scope.highlightTask = $scope.mainTask.item.id;
             $scope.sendMail($scope.currentTask.id, 'updateFollow');
             $scope.resetForm();
                     // $scope.closeTarget('.task-add-follower');
                     // $scope.refreshTask();
                   })
         })
       })
     }
     $scope.removeFollow = function(_id, changeAssign) { // remove follow
       if (_id == $scope.currentUser.id && !changeAssign) {
         $ionicPopup.alert({
           template: "You can't remove yourself!"
         });
         return;
       }
       var index = _.findLastIndex($scope.onTaskFollow, {
         id: _id
       });
       tasks.removeFollow(_id, $scope.currentTask.id).then(function() {
         tasks.getdataTask($scope.incompletepaging, $scope.upcomingpaging, $scope.followingpaging, $scope.downtimepaging, $scope.completepaging).then(function() {
           $scope.onTaskFollow.splice(index, 1);
           $scope.dataTask = tasks.dataTask;
           $scope.convertTypeByDate();
           $scope.renderData();
           $scope.getFollow();
           $scope.highlightTask = $scope.mainTask.item.id;
                 // $scope.includeJs();
                 $scope.sendMail($scope.currentTask.id, 'updateFollow');
                 // $scope.refreshTask();
               });
       });
     }
     $scope.checkOnFollow = function(value, checked) { // disiable user follow
       var idx = $scope.followComplete.indexOf(value);
       if (idx >= 0 && !checked) {
         $scope.followComplete.push(value);
       }
       if (idx < 0 && checked) {
         setTimeout(function() {
           $scope.$apply(function(val) {
             idx = $scope.followComplete.indexOf(value);
             if (idx >= 0) $scope.followComplete.splice(idx, 1);
           });
         }, 1);
       }
     }
     $scope.createSubTask = function() { // create subtask
         // before $scope.parentTask.item.id
         tasks.createSubTask($scope.currentTask.id).then(function(data) {
           tasks.getListSubTask($scope.currentTask).then(function() {
             $scope.dataSubTask = tasks.dataSubTask;
             $scope.listSubTask = tasks.listSubTask;
             $scope.listSubTaskOnPopup = $scope.listSubTask;

             if($scope.tabTaskActive=='Following'){
              _.where($scope.tabFollow, {
                id: $scope.currentTask.id
              })[0].subTaskCount = $scope.listSubTaskOnPopup.length;
            }else{
              _.where($scope.oTask, {
                id: $scope.currentTask.id
              })[0].subTaskCount = $scope.listSubTaskOnPopup.length;
            }

            $scope.subComplete = tasks.subComplete;
            tasks.getMessage($scope.currentTask.id).then(function() {
             $scope.detailTask = tasks.detailTask;
             $scope.statisticalAttached();
             $scope.toComment = tasks.toComment;
             $scope.commentActivity();
                     // $scope.includeJs();
                     $scope.sendMail($scope.currentTask.id, 'createSubTask');
                   });
          });
         });
       }
       $scope.getSubTask = function(data) {
         $scope.openByGetTemplate('popupTaskSubtask');
         $scope.listSubTaskOnPopup = $scope.listSubTask;
         // console.log($scope.listSubTask);

       }
     $scope.updateTypeSubTask = function(sTask, checked, inList) { // update type
       var tType = 'incomplete';
       if (sTask.type == 'incomplete') {
         tType = 'complete';
       }
       var type_id = _.where($scope.typeTask, {
         name: tType
       })[0].id;
       var changetype = _.extend(sTask, {
         type_id: type_id,
         before_id: 0
       });
       tasks.changeType(changetype).then(function() {
         !$scope.selectedSubTask ? $scope.switchMainToSub = true : $scope.switchMainToSub = false;
         tasks.getListSubTask($scope.parentTask.item).then(function() {
                 //tasks.makeSubComplete(sTask, checked);
                 if (inList == undefined) {
                   $scope.dataSubTask = tasks.dataSubTask;
                   $scope.listSubTask = tasks.listSubTask;
                   $scope.selectedSubTask ? '' : $scope.subComplete = tasks.subComplete;
                 } else {
                   tType == 'complete' ? $scope.checkSubComplete = true : $scope.checkSubComplete = false;
                 }
                 // $scope.includeJs();
                 $scope.sendMail(sTask.id, 'incomplete');
               });
       });
     }
     $scope.getGroup = function() { // get Group
         // $scope.includeJs();
         $scope.formData = {};
         $scope.formData.type = 'Incomplete';
         $scope.grouptask = [];
         $scope.userFollow = [];
         $scope.fromDate = moment().format(conFig.formatDate.toUpperCase());
         $scope.toDate = moment().add(1, 'days').format(conFig.formatDate.toUpperCase());
         // $('input[name="starttime"]').val(moment().format(conFig.formatDate.toUpperCase()));
         // $('input[name="endtime"]').val(moment().add(1, 'days').format(conFig.formatDate.toUpperCase()));
         $ionicLoading.show({ template: templateLoading });
         tasks.getGroup().then(function() {
           if (!startpage) $ionicLoading.hide();
           $scope.grouptask = tasks.groupTask;
           $scope.openByGetTemplate('popupTaskContent');
         });
       }
       $scope.getDataGroup = function(group_id) {
        $scope.followerLabel = '';
         // $scope.formData.assign = '';
         $scope.userFollow = [];

         if (group_id == '') return;
         tasks.getDataGroup(group_id).then(function() {
           $scope.initialAssignUser = [];
           $scope.initialAssignUser.push(parseInt(tasks.userAssign.id));
           var idsFollower = [];
           tasks.userFollow.forEach(function(item) {
             idsFollower.push(parseInt(item.id));
           })
           $scope.initialFollower = idsFollower;
             // console.log($scope.initialFollower);    
             // console.log($scope.initialAssignUser);
             // $scope.formData.assign = tasks.userAssign;
             // $scope.userFollow = tasks.userFollow;
           });
         $scope.setValueGroup(group_id);
       }
       $scope.convertTypeByDate = function() {
         _.each($scope.dataTask, function(val, index) {
           var s = Date.parseDate(val.starttime);
           var e = Date.parseDate(val.endtime);
           var m = Date.parseDate(val.modified_date);
           val.type = String(val.type).toLowerCase();
           var tStart = globalParseDate(s);
           var tEnd = globalParseDate(e);
           var tNow = globalParseDate(new Date(_.now()));
           if (tStart.getTime() > tNow.getTime() && val.type == 'incomplete') {
             val.type = 'upcoming';
             console.log('call update task here');
           }
           if (tStart.getTime() <= tNow.getTime() && val.type == 'upcoming') {
             val.type = 'incomplete';
             console.log('call update task here');
           }
           val.starttime = tStart;
           val.endtime = tEnd;
           val.modified_date = m;
         });
       }

       $scope.cordovaBrowser = function(content, style) {
         cordovaBrowser(content, style);
       }

     $scope.replaceURLWithHTMLLinks = function(detail) { // return content with html
       var content = detail.content;
       var type = detail.type;
       if (type == 'file') {
         var filename = content.substring(content.lastIndexOf('/') + 1);
         return '<div class="mgB2">Attached File: <a class="link-2"  onclick="cordovaBrowser(\'' + content + '\',\'file\')">' + filename + '</a></div>';
       }
       if (type == 'img') {
         var filename = content.substring(content.lastIndexOf('/') + 1);

         var imageUrl = (content.indexOf('s3.amazonaws.com') < 0) ? url_site + '/' + content.substring(content.indexOf('upload')) : content;

         return '<div class="mgB2">Attached Image: <a class="link-2"  onclick="cordovaBrowser(\'' + content + '\',\'img\')">' + filename + '</a></div><img class="box-img-1 w200px" src="' + imageUrl + '">';
       }
       var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&@#\/%?=~_()|!:,.;]*[-a-z0-9+&@#\/%=~_()|])/ig;
       var string = content.replace(re, function(match, lParens, url) {
         var rParens = '';
         lParens = lParens || '';
         var lParenCounter = /\(/g;
         while (lParenCounter.exec(lParens)) {
           var m;
           if (m = /(.*)(\.\).*)/.exec(url) || /(.*)(\).*)/.exec(url)) {
             url = m[1];
             rParens = m[2] + rParens;
           }
         }
         return lParens + "<a  target='_blank' class='link-2' href='" + url + "'>" + url + "</a>" + rParens;
       });
         // edit by haudao
         var matches = string.match(/href="customer-detail\.html\?customerId=(\d*)"/i);
         if (matches != null) {
           var strReplace = 'onclick="redirectTo(\'customers.html#/board/customers/' + matches[1] + '\')"';
           string = string.replace(/href="customer-detail\.html\?customerId=\d*"/i, strReplace);
         }

         matches = string.match(/href="appointments\.html\?appointment_id=(\d*)"/i);
         if (matches != null) {
           var strReplace = 'onclick="redirectTo(\'scheduleapp.html?appointment_id=' + matches[1] + '\')"';
           if ($scope.roleName == isFieldinstaller || $scope.roleName == isSalesman)
             strReplace = 'onclick="redirectTo(\'myschedule.html?appointment_id=' + matches[1] + '\')"';
           string = string.replace(/href="appointments\.html\?appointment_id=\d*"/i, strReplace);
         }

         matches = string.match(/href="invoice\.html\?invoice_id=(\d*)"/i);
         if (matches != null) {
           var strReplace = 'onclick="cordovaBrowser(\'' + matches[1] + '\',\'invoice\')"';
           string = string.replace(/target="_blank" href="invoice\.html\?invoice_id=\d*"/i, strReplace);
         }

         matches = string.match(/href="(.*)"/i);
         if (matches != null) {
           var strReplace = 'onclick="cordovaBrowser(\'' + matches[1] + '\',\'msg\')"';
           string = string.replace(/href="(.*)"/i, strReplace);
         }


         // end edit
         return string;
       }
     $scope.deliberatelyTrustDangerousSnippet = function(detail) { // trust html in angular
       return $sce.trustAsHtml($scope.replaceURLWithHTMLLinks(detail));
     };
     $scope.getFollowCreateTask = function() {
       var qStringUser = [];
       ($scope.formData.assign == undefined || $scope.formData.assign == '') ? qStringUser = $scope.allUser: qStringUser = _.filter($scope.allUser, function(val) {
         return val.id != parseInt($scope.formData.assign.id);
       });
       return qStringUser;
     }
     $scope.delAttached = function(task) {
       tasks.delAttached(task).then(function(data) {
         tasks.getMessage($scope.currentTask.id).then(function() {
           $scope.detailTask = tasks.detailTask;
           $scope.statisticalAttached();
           $scope.toComment = tasks.toComment;
           $scope.commentActivity();
           $('.t.tblloader').hide();
           $('#contentTasks').show();
           $scope.sendMail($scope.currentTask.id, 'delete');
                 // $scope.includeJs();
               });
       });
     }
     $scope.createHistory = function(task_id, action) { // create history
       tasks.createHistory(task_id, action).then(function(data) {
         if ($scope.switchMainToSub) {
           $scope.switchMainToSub = false;
           return;
         }
         $scope.parentTask.item != undefined ? $scope.getHistory($scope.parentTask.item.id) : '';
       });
     }
     $scope.getHistory = function(task_id) { // get history
       $ionicLoading.show({ template: templateLoading });
       tasks.getHistory(task_id).then(function(data) {
         $scope.detailTask = tasks.detailTask;
         $scope.statisticalAttached();
         $scope.toComment = tasks.toComment;
         $scope.commentActivity();
         $scope.historyTask = tasks.historyTask;
         $scope.toHistory = tasks.toHistory;
         $scope.historyActivity();
         $scope.renderDataHistory();
             // $scope.includeJs();
             $scope.uncheckAll;
             setTimeout(function() {
               $scope.$apply(function(val) {
                 $scope.checkloadmove = 1;
               });
               $ionicLoading.hide();
             }, 100);
           });
     }
     $scope.renderDataHistory = function() {
       _.each($scope.historyTask, function(val, index) {
         if (val.descriptions.substring(0, val.descriptions.indexOf("Sub Task:") > 0)) {
           $scope.historyTask[index].descriptions = val.descriptions.substring(0, val.descriptions.indexOf("Sub Task:"));
         }
         if (val.descriptions.substring(0, val.descriptions.indexOf("Task:") > 0)) {
           $scope.historyTask[index].descriptions = val.descriptions.substring(0, val.descriptions.indexOf("Task:"));
         }
         $scope.historyTask[index].modified_date = Date.parseDate(val.modified_date);
       })
     }
     $scope.isActiveHistory = function() { // active more history
       return tasks.toHistory > 0 ? false : true;
     }
     $scope.moreHistory = function() {
       $scope.toHistory > 0 ? $scope.toHistory = 0 : $scope.toHistory = tasks.toHistory;
       $scope.historyActivity();
     }
     $scope.historyActivity = function() {
       $scope.toHistory > 0 ? $scope.strActivityHistory = ($scope.toHistory + " more history") : $scope.strActivityHistory = "Hide history activity";
     }
     $scope.sendMail = function(task_id, action) { // send mail
       tasks.sendMail(task_id, action).then(function(data) {
         switch (action) {
           case 'createTask':
           $scope.createHistory(tasks.task_id, tasks.comments);
           break;
           case 'createSubTask':
           $scope.createHistory(tasks.task_id, tasks.comments);
           break;
           case 'delete':
           $scope.createHistory(tasks.task_id, tasks.comments);
           break;
           case 'updateFollow':
           $scope.createHistory(tasks.task_id, tasks.comments);
           break;
           case 'MessageTask':
           $scope.createHistory(tasks.task_id, tasks.comments);
           break;
           case 'incomplete':
           $scope.createHistory(tasks.task_id, tasks.comments);
           break;
           case 'assign':
           $scope.createHistory(tasks.task_id, tasks.comments);
           break;
           case 'Reassign':
           $scope.createHistory(tasks.task_id, tasks.comments);
           break;
           case 'dueTime':
           $timeout(function() {
             $scope.setTime = true;
           }, 2000);
           break;


           default:
                     //
                   }
                 })
     }
     $scope.search = {};
     $scope.clearSearch = function() {
       $scope.search.Text = '';
     }
     $scope.keypressForSearchTask = function() {
       var keysByCode = [9, 16, 17, 18, 20, 27, 32, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 144];
       if ($scope.search.Text.keyCode >= 112 && $scope.search.Text.keyCode <= 123) return;
       if (keysByCode.indexOf($scope.search.Text.keyCode) > -1) return;
       $scope.coundown = 10;
       if ($scope.myTime != null) clearInterval($scope.myTime);
       $scope.downTimerForSearchTask();
     };
     $scope.downTimerForSearchTask = function() {
       $scope.myTime = setInterval(function() {
         $scope.coundown--;
         if ($scope.coundown <= 0) {
           var search = $scope.search.Text;
           clearInterval($scope.myTime);
           tasks.getdataTask($scope.incompletepaging, $scope.upcomingpaging, $scope.followingpaging, $scope.downtimepaging, $scope.completepaging, search).then(function() {
             $scope.dataTaskSearch = tasks.dataTaskSearch;
             $ionicScrollDelegate.$getByHandle('scrollTaskSearch').scrollTop(true);
           });
         }
       }, 100);
     }
     $scope.keypress = function($event, task, is_subtask) { // change input
       if (!$scope.selectedSubTask && !is_subtask) {
         $scope.currentTask.taskname = task.taskname;
         $scope.parentTask.item.taskname = task.taskname;
         $scope.parentTask.item.taskdes = task.taskdes;
       }
       $scope.coundown = 20;
       if ($scope.myTime != null) clearInterval($scope.myTime);
       $scope.downTimer(task);
     };
     $scope.downTimer = function(task) {
       $scope.myTime = setInterval(function() {
         $scope.coundown--;
         if ($scope.coundown <= 0) {
           clearInterval($scope.myTime);
           $scope.updateInputTask(task);
         }
       }, 10);
     }
     $scope.editTask = function() {
       $scope.openByGetTemplate("popupEditTask");
       $scope.formData = {};
       $scope.formData.files = [];
       $scope.formData.type = 'Incomplete';
       $scope.grouptask = [];
       $scope.userFollow = [];
       $scope.initialFollower = [];
       $scope.initialAssignUser = [];
       tasks.getGroup().then(function() {
         $scope.grouptask = tasks.groupTask;
         $scope.initialFollower = _.pluck($scope.onTaskFollow, "id");
         $scope.initialAssignUser = [$scope.onTaskAssign.id];
             // $scope.innerTaskAssign = $scope.onTaskAssign;
             // $scope.innerTaskFollow = $scope.onTaskFollow;
             // $scope.holdTaskAssign = $scope.onTaskAssign.screen_name;
             // $(".innerClose").click(function() {
             //     closePopupById("popupAddFollower");
             //     var restoreTask = _.where($scope.dataTask, {
             //         id: $scope.currentTask.id
             //     });
             //     if (restoreTask.length > 0) {
             //         $scope.onTaskAssign.screen_name = (_.where($scope.allUser, {
             //             id: (restoreTask)[0].assignerId
             //         }))[0].screen_name;
             //         $scope.holdTaskAssign = $scope.onTaskAssign.screen_name;
             //         $('.holdTAssign').val($scope.onTaskAssign.screen_name);
             //     } else {
             //         $scope.onTaskAssign = $scope.innerTaskAssign;
             //         $scope.onTaskFollow = $scope.innerTaskFollow;
             //         $scope.holdTaskAssign = $scope.onTaskAssign.screen_name;
             //     }
             // })
           });
     }
     $scope.updateInputTask = function(_task) {
       tasks.updateInputTask(_task).then(function() {
         $scope.convertTypeByDate();
         $scope.renderData();
         $scope.getFollow();
         $scope.highlightTask = $scope.mainTask.item.id;
       });
     }
     $scope.logout = function() { // logout
       tasks.logOut().then(function(data) {});
     }
     $scope.checkloadmove = 1;


     $scope.checkScroll = function(id) {
       var height = parseInt($("#" + id + ">.scroll").css("height"));
       var scroll = $ionicScrollDelegate.$getByHandle(id).getScrollPosition().top;
       var checkScroll = parseInt(height - scroll);
         // console.log(height,checkScroll);
         setTimeout(function() {
          if (checkScroll < 1000 && height > 1000) {
            $scope.loadMoreTask();
          }
        }, 500);
       };
       $scope.loadMoreTask = function() {
         var action = $scope.currentItemTab.label ? $scope.currentItemTab.label : 'Incomplete';
         switch (action) {
           case 'Incomplete':
           paing = $scope.incompletepaging;
           action = 1;
           $scope.checkdata = $scope.checkincompletepaging;
           break;
           case 'Upcoming':
           paing = $scope.upcomingpaging;
           action = 2;
           $scope.checkdata = $scope.checkupcomingpaging;
           break;
           case 'Following':
           paing = $scope.followingpaging;
           action = 3;
           $scope.checkdata = $scope.checkfollowingpaging;
           break;
           case 'Downtime':
           paing = $scope.downtimepaging;
           action = 4;
           $scope.checkdata = $scope.checkdowntimepaging;
           break;
           case 'Complete':
           paing = $scope.completepaging;
           action = 5;
           $scope.checkdata = $scope.checkcompletepaging;
           break;
         }

         // if ($scope.checkloadmove == 1 && $scope.checkdata) {
         // $ionicLoading.show({
         //     template: templateLoading
         // });
         if ($scope.checkdata) {
           switch (action) {
             case 1:
             $scope.checkincompletepaging = false;
             break;
             case 2:
             $scope.checkupcomingpaging = false;
             break;
             case 3:
             $scope.checkfollowingpaging = false;
             break;
             case 4:
             $scope.checkdowntimepaging = false;
             break;
             case 5:
             $scope.checkcompletepaging = false;
             break;
           }

           $('.iconSpinner').show();
           tasks.loadMoreTask(action, paing).then(function() {
             $('.iconSpinner').hide();
             $scope.dataTask = arrayUnion($scope.dataTask, tasks.dataTask, function(item1, item2) {
               return item1.id == item2.id;
             });
             $scope.convertTypeByDate();
             $scope.renderData();
             $scope.getFollow();
             switch (tasks.tasktype_id) {
               case 1:
               $scope.incompletepaging = tasks.row;
               $scope.checkincompletepaging = tasks.checkloadmore;
               break;
               case 2:
               $scope.upcomingpaging = tasks.row;
               $scope.checkupcomingpaging = tasks.checkloadmore;
               break;
               case 3:
               $scope.followingpaging = tasks.row;
               $scope.checkfollowingpaging = tasks.checkloadmore;
               break;
               case 4:
               $scope.downtimepaging = tasks.row;
               $scope.checkdowntimepaging = tasks.checkloadmore;
               break;
               case 5:
               $scope.completepaging = tasks.row;
               $scope.checkcompletepaging = tasks.checkloadmore;
               break;
             }
             // setTimeout(function() {
             //     $scope.checkloadmove = 1;
             // }, 1000);
           });
         }
         $timeout(function() {
           $scope.$broadcast('scroll.infiniteScrollComplete', {
             action: action
           });
         }, 2000)
       }
         // $scope.$on('$stateChangeSuccess', function() {
         //     $scope.loadMoreTask();
         // });

         $scope.refreshTaskPage = function() {
          $scope.incompletepaging = 30;
          $scope.upcomingpaging = 30;
          $scope.followingpaging = 30;
          $scope.downtimepaging = 30;
          $scope.completepaging = 30;
          tasks.getdataTask($scope.incompletepaging, $scope.upcomingpaging, $scope.followingpaging, $scope.downtimepaging, $scope.completepaging).then(function() {
            $scope.tabFollow = [];
            $scope.dataTask = tasks.dataTask;
            $scope.convertTypeByDate();
            $scope.renderData();
            $scope.getFollow();
            $scope.$broadcast('scroll.refreshComplete'); 
          });    
        }

        $scope.includeJs = function() { /*include jquery*/
         setTimeout(function() {
           $scope.$apply(function(val) {
             if ($scope.currentTask.duedate != undefined) {
                     // edit by haudao
                     $('#taskDueDate').unbind();
                     $('#taskDueDate').daterangepicker({
                       startDate: globalParseDate($scope.currentTask.duedate[0]),
                       endDate: globalParseDate($scope.currentTask.duedate[1]),
                       showDropdowns: true
                     }, function(start, end) {
                       var time = {
                         start: start.format(conFig.formatDate.toUpperCase()),
                         end: end.format(conFig.formatDate.toUpperCase())
                       }
                       $scope.dueTimeTask(time.start, time.end, $scope.currentTask.id);
                     });
                   }
                 // end edit
               });
         }, 100);
       }

     // $(window).resize(function() {
     //     setLayout();
     // })
     // function setLayout() {
     //     var minHW = 650;
     //     var hW = $(window).outerHeight();
     //     var hAndFH = $('#header').outerHeight() + $('#footer').outerHeight() + 44;
     //     var hL1 = $('.task-list .task-title').outerHeight();
     //     var hL2 = $('.task-list .all-task > .tab-nav > .tab-link').outerHeight();
     //     var hR1 = $('.task-detail .main-assign-name').outerHeight();
     //     var hR2 = $('.task-detail .duetask-file').outerHeight();
     //     var hR3 = $('.task-detail .task-content .task-name').outerHeight();
     //     var hR5 = $('.task-detail .task-content .task-comment').outerHeight();
     //     //        console.log(hR5);
     //     var hAll, hL3, hR4;
     //     if (hW > minHW) {
     //         hAll = hW - hAndFH;
     //         hL3 = hW - hAndFH - hL1 - hL2 - 5;
     //         hR4 = hW - hAndFH - hR1 - hR2 - hR3 - hR5;
     //     } else {
     //         hAll = 500;
     //         hL3 = 500 - hL1 - hL2 - 5;
     //         hR4 = 500 - hR1 - hR2 - hR3 - hR5;
     //     }
     //     $('.task-list, .task-detail').css({
     //         height: hAll
     //     });
     //     $('.task-list .all-task > .tab-nav > .tab-content').css({
     //         height: hL3
     //     });
     //     $('.task-detail .task-content .task-data').css({
     //         height: hR4
     //     });
     // }
     $scope.fieldWorkerRemoveFollwer = function() {
       if ($scope.roleName == $scope.isSalesman || $scope.roleName == $scope.isFieldinstaller) {
         return false;
       }
     }
     $scope.numberResult = function() {
       return 2;
       if ($scope.roleName == $scope.isSalesman || $scope.roleName == $scope.isFieldinstaller) {
         return 0;
       } else {
         return 10;
       }
     }
     $scope.Reassign_task_group = function(group_id) {
       tasks.Reassign_task_group($scope.currentoTask.id, group_id).then(function() {
         $scope.onTaskFollow = tasks.Reassign_follow;
         $scope.dataTask = tasks.dataTask;
         $scope.convertTypeByDate();
         $scope.renderData();
         $scope.getFollow();
         $scope.highlightTask = $scope.mainTask.item.id;
             // $scope.includeJs();
             $scope.sendMail($scope.currentTask.id, 'Reassign');
             $scope.holdTaskAssign = tasks.Reassign_assign.screen_name;
             $('#holdTAssign').val(tasks.Reassign_assign.screen_name);
           });
     }
     $scope.changeradio = function(group_id) {
       $scope.grouptaskReassign = group_id;
     }
     $scope.$on('$includeContentLoaded', function() { // for angular binding ready
         // $scope.includeJs();
       });
     // edit by haudao


     $scope.lengthOfArray = function(arrData, value) {
       var count = 0;
       for (var i = 0; i < arrData.length; i++) {
         if (arrData[i].type == value) count++;
       }
       return count;
     }
     $scope.totalDisplay = function() {
       // $scope.incompleteLength = $scope.lengthOfArray($scope.oTask, 'incomplete');
       // $scope.upcomingLength = $scope.lengthOfArray($scope.oTask, 'upcoming');
       // $scope.downtimeLength = $scope.lengthOfArray($scope.oTask, 'downtime');
       // $scope.completeLength = $scope.lengthOfArray($scope.oTask, 'complete');
       $scope.incompleteLength = tasks.countTaskOfTask.incomplete;
       $scope.upcomingLength = tasks.countTaskOfTask.upcoming;
       $scope.followingLength = tasks.countTaskOfTask.following;
       $scope.downtimeLength = tasks.countTaskOfTask.downtime;
       $scope.completeLength = tasks.countTaskOfTask.complete;
     }
     $timeout(function() {
       $scope.checkincompletepaging = $scope.incompleteLength > 20 ? true : false;
       $scope.checkupcomingpaging = $scope.upcomingLength > 20 ? true : false;
       $scope.checkfollowingpaging = $scope.tabFollow.length > 20 ? true : false;
       $scope.checkdowntimepaging = $scope.downtimeLength > 20 ? true : false;
       $scope.checkcompletepaging = $scope.completeLength > 20 ? true : false;
       $scope.deviceStyle = isiOs ? 'ios' : 'android';
         // console.log('device',isiOs);
       }, 20000);
     $scope.setValueGroup = function(group_id) {
       $scope.Input_value.group = "";
       var group_index;
       _.each($scope.grouptask, function(val,index) {
        if(val.id == group_id){
          group_index = index
        }
      });
       if (group_index >= 0) {
         $scope.Input_value.group = $scope.grouptask[group_index].name
       };
     }
     $scope.Input_value.type = "Standard";
     $scope.setValueType = function(value) {
       if (value == 'Downtime') {
         $scope.Input_value.type = "Downtime Task";
       } else {
         $scope.Input_value.type = "Standard";
       }
     }
     $scope.filterAssignUser = function(query, isInitializing) {
       var returnValue = {
         items: []
       };
       var id = $scope.autocompleteList.refferedAssignUser;
       $scope.allUser.forEach(function(item) {
         if (id != item.id) {
           if (item.screen_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
             returnValue.items.push(item);
           } else if (item.id.toString().indexOf(query) > -1) {
             returnValue.items.push(item);
           }
         }
       });
       return returnValue;
     };
     $scope.initialAssignUser = [];
     $scope.setValueForAssignUser = function(modelValue) {

       for (var i = 0; i < $scope.allUser.length; i++) {
        if ($scope.allUser[i].id == modelValue) {
          $scope.assigneeLabel = $scope.allUser[i].screen_name;
          return $scope.allUser[i];
        }
      }
      return {};
    };
    $scope.idAssignUser = "";
     $scope.onSelectAssginUser = function(callback) { // change assign
       $scope.idAssignUser = callback.item.id;
       if (_.filter($scope.userFollow, function(val) {
         return parseInt(val.id) == parseInt($scope.idAssignUser);
       }).length > 0) {
         setTimeout(function() {
           $scope.$apply(function(val) {
             $scope.initialAssignUser = [];
             $cordovaToast.showLongTop('User exits in Follower');
           });
         }, 1);
         return;
       } else {
         $scope.formData.assign = callback.item;
         if(!(parseInt($scope.currentIdLogin) == parseInt(callback.item.id))){
          if(_.filter($scope.userFollow, function(val) {
            return parseInt(val.id) == parseInt($scope.currentIdLogin);
          }).length == 0){
            $scope.userFollow.push(_.where($scope.allUser, { id: $scope.currentIdLogin })[0]);
          }
        }
      }
    }
    $scope.onRemoveAssginUser = function(callback) {
     $scope.formData.assign = [];
         // console.log($scope.formData.assign)
       }
       $scope.filterFollow = function(query) {
         var returnValue = {
           items: []
         };
         var listIdArray = $scope.autocompleteList.refferedFollower;
         $scope.allUser.forEach(function(item) {
           if (listIdArray.indexOf(item.id) < 0) {
             if (parseInt(item.id) != parseInt($scope.idAssignUser)) {
               if (item.screen_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                 returnValue.items.push(item);
               } else if (item.id.toString().indexOf(query) > -1) {
                 returnValue.items.push(item);
               }
             }
           }
         });
         return returnValue;
       };
       $scope.initialFollower = [];
       $scope.setValueForFollower = function(modelValue) {
         for (var i = 0; i < $scope.allUser.length; i++) {
           if ($scope.allUser[i].id == modelValue) {
            if($scope.allUser[i].screen_name != undefined){
              if($scope.followerLabel != ''){
                $scope.followerLabel += ',';
              }
              $scope.followerLabel += $scope.allUser[i].screen_name;
            }
            return $scope.allUser[i];
          }
        }
      };
      $scope.onSelectFollower = function(callback) {
            //if ($scope.userFollow.indexOf(callback.item) < 0) $scope.userFollow.push(callback.item);
            if(!$scope.checkObjItemInArray(callback.item,$scope.userFollow)){
              $scope.userFollow.push(callback.item);
            }
          }
          $scope.onRemoveFollower = function(callback) {
           var index = $scope.userFollow.indexOf(callback.item);
           $scope.userFollow.splice(index, 1);
         // console.log($scope.userFollow);
       }
       $scope.initialChangeAssignUser = [];
       $scope.setValueForChangeAssignUser = function(modelValue) {
         for (var i = 0; i < $scope.allUser.length; i++) {
           if ($scope.allUser[i].id == modelValue) {
                 // console.log($scope.allUser[i].id, modelValue)
                 return $scope.allUser[i];
               }
             }
             return {};
           };
     $scope.onSelectChangeAssginUser = function(callback) { // change assign
       $scope.idAssignUser = callback.item.id;
       if (_.filter($scope.onTaskFollow, function(val) {
         return parseInt(val.id) == parseInt($scope.idAssignUser);
       }).length > 0) {

         if (parseInt($scope.currentTask.ownerId) == parseInt(callback.item.id)) {
           $scope.onSelect(callback.item);
           $scope.removeFollow(callback.item.id, true);
           $scope.closeTarget('.task-change-assignee');
         } else {
           setTimeout(function() {
             $scope.$apply(function(val) {
               var array = [];
               array.push($scope.onTaskAssign.id);
               $scope.initialChangeAssignUser = array;
               $cordovaToast.showLongTop('User exits in Follower');
             });
           }, 1);
           return;
         }
       } else {
         if (callback.item.id != $scope.onTaskAssign.id && callback.item.id) {
           $scope.onSelect(callback.item);
           $scope.closeTarget('.task-change-assignee');
         }
       }
     }
     $scope.onRemoveChangeAssginUser = function(callback) {
       var array = [];
       array.push($scope.onTaskAssign.id);
       $scope.initialChangeAssignUser = array;
     }
         // $scope.initialAddFollower = [];
         // $scope.setValueForAddFolower = function(modelValue) {
         //     for (var i = 0; i < $scope.allUser.length; i++) {
         //         if ($scope.allUser[i].id == modelValue) {
         //             // console.log($scope.allUser[i].id, modelValue)
         //             return $scope.allUser[i];
         //         }
         //     }
         //     return {};
         // };
         // $scope.onSelectAddFollower = function(callback) { // change assign
         //     if ($scope.onTaskFollow.indexOf(callback.item) < 0) $scope.onTaskFollow.push(callback.item);
         //     // console.log($scope.onTaskFollow);
         // }
         // $scope.onRemoveAddFollower = function(callback) {
         //     var index = $scope.onTaskFollow.indexOf(callback.item);
         //     $scope.onTaskFollow.splice(index, 1);
         //     // console.log($scope.onTaskFollow);
         // }
         $scope.moreAndHideAttached = function() {
           if ($scope.countSubTasks == 3) {
             $scope.countSubTasks = $scope.listSubTask.length;
             $scope.strActivitySubTasks = "Hide sub tasks";
           } else {
             $scope.countSubTasks = 3;
             $scope.strActivitySubTasks = "";
             $scope.strActivitySubTasks = $scope.listSubTask.length - 3 + " more subtasks";
           }
         }
         $scope.openPopupHistoryActivity = function() {
           $ionicPopup.show({
             templateUrl: 'templates/dashboard/tasks/tasks/taskPopupHistoryActivitymodal.tpl',
             title: 'History',
             scope: $scope,
             buttons: [{
               text: 'Done'
             }]
           });
         }
         $scope.confirmRemoveFollower = function(item) {
         // console.log(item);
         if (parseInt($scope.currentTask.ownerId) == parseInt(item.id)) {
           $ionicPopup.show({
             template: "You aren't allowed to remove the task creator. To change the task creator to assigne, click Yes, or click Cancel to close this popup.",
             scope: $scope,
             buttons: [{
               text: '<b>Yes</b>',
               onTap: function(e) {
                 $scope.initialChangeAssignUser = [item.id];
                         // $scope.onSelect(item);
                         // $scope.removeFollow(item.id, true);
                       }
                     }, { text: 'Cancel' }]
                   });
         } else {
           var confirmPopup = $ionicPopup.confirm({
             title: 'Remove Follower',
             template: 'Are you sure you want to remove ' + item.screen_name + '?'
           });
           confirmPopup.then(function(res) {
             if (res) {
               $scope.removeFollow(item.id);
             }
           });
         }
       }
       $scope.slideHasChanged = function(index) {
         // console.log(index);
         // var $activeTab = $('.link-task-type-tab > div > div > a:eq(' + index + ')');
         // $('.link-task-type-tab > div > div > a').removeClass('slideboxActive');
         // $activeTab.addClass('slideboxActive');
         $scope.currentItemTab = $scope.tabs[index];
         // $ionicSlideBoxDelegate.$getByHandle('tasksSlideBox').slide(index);
         // $scope.checkdata = true;
         // console.log($scope.currentItemTab);
       }
       $scope.closePopup = function() {
         $scope.closeTarget('.task-change-assignee');
         // $scope.closeTarget('.task-add-follower');
       }
       $scope.closePopupTaskContent = function() {
         $scope.closeTarget('#popupTaskContent');
         $scope.initialAssignUser = [];
         $scope.initialFollower = [];
       }
         // $scope.arrayDataFollower = [];
         $scope.openPopupAddFollower = function() {
           $scope.arrayDataFollower = [];
           angular.forEach($scope.onTaskFollow, function(item) {
             $scope.arrayDataFollower.push(item);
           })
           var index = _.findIndex($scope.arrayDataFollower, {
             id: $scope.currentUser.id
           });
           $scope.userFollower = _.filter($scope.allUser, function(item) {
             if (index > -1) return item.id != $scope.onTaskAssign.id && item.id != $scope.currentUser.id;
             return item.id != $scope.onTaskAssign.id;
           });
         // $scope.userFollower = _.sortBy($scope.userFollower, function(item) {
         //     return item.sreen_name
         // }).reverse();
         $scope.search.userFollower = "";
         $ionicPopup.show({
           templateUrl: 'templates/dashboard/tasks/tasks/taskPopupAddFollowermodal.tpl',
           title: 'Add Follower',
           scope: $scope,
           buttons: [{
             text: 'Cancel'
           }, {
             text: 'Done',
             onTap: function() {
               $scope.updateFollow();
             }
           }]
         });
       }
       $scope.orderByFollower = function(item) {
         var checkArray = [];
         angular.forEach($scope.arrayDataFollower, function(value) {
           checkArray.push(value.id);
         })
         return checkArray.indexOf(item.id);
       }
     $scope.getCurrentTaskById = function(id) { // for click get current task
       tasks.show(id, true).then(function() {
         var currentTask = tasks.TaskById;
         currentTask.taskname = currentTask.name;
         var item = currentTask.listFollowingId;
         if (_.indexOf(item, $scope.currentUser.id) > -1) {
           if (currentTask.type == 'complete') {
             currentTask.f_disiable = 'oComplete';
           } else {
             currentTask.type = 'following';
             currentTask.f_disiable = 'oFollow';
           }
         }
         var s = Date.parseDate(currentTask.starttime);
         var e = Date.parseDate(currentTask.endtime);
         var m = Date.parseDate(currentTask.modified_date);
         currentTask.type = String(currentTask.type).toLowerCase();
         var tStart = globalParseDate(s);
         var tEnd = globalParseDate(e);
         var tNow = globalParseDate(new Date(_.now()));
         if (tStart.getTime() > tNow.getTime() && currentTask.type == 'incomplete') {
           currentTask.type = 'upcoming';
         }
         if (tStart.getTime() <= tNow.getTime() && currentTask.type == 'upcoming') {
           currentTask.type = 'incomplete';
         }
         currentTask.starttime = tStart;
         currentTask.endtime = tEnd;
         currentTask.modified_date = m;
         var oTask = $scope.oTask;
         if (currentTask.type == "following") oTask = $scope.tabFollow;
         $scope.closeTarget('.task-search');
         $scope.getCurrentTask(currentTask, oTask, 'open');
       })
     }
     $scope.startpage = function() {
       tasks.init().then(function() {
         var waitting = setInterval(function() {
           if (tasks.ready) {
             $scope.typeTask = tasks.typeTask;
             $scope.dataTask = tasks.dataTask;
                     // $scope.loadMoreTask();
                     // console.log($scope.dataTask);
                     $scope.currentIdLogin = tasks.currentIdLogin;
                     $scope.imagePath = pathToPublic + tasks.currentUser.imgprofile;
                     $scope.currentUser = tasks.currentUser;
                     $scope.allUser = tasks.allUser;
                     $scope.userMessage = tasks.userMessage;
                     // setLayout();
                     $scope.onClickTab($scope.tabs[0]);
                     // setInterval(function() {
                     //     tasks.realLogin();
                     // }, time_refresh);
                     $scope.getGroup();
                     clearInterval(waitting);
                     request_notify_get_chat = true;
                   }
                 }, 1);
       });
     }
     $scope.showImageFollower = function(id) {
       var imgUrl = "";
       var item = _.where($scope.allUser, { id: id });
       if (item[0]) imgUrl = item[0].imgprofile;
       return imgUrl;
     }
     $scope.openActionSheet = function(type) {
       $scope.uploadType = type;
       var options = {
             // title: 'What do you want with this image?',
             buttonLabels: ['Video', 'Camera', 'Photo', 'File'],
             addCancelButtonWithLabel: 'Cancel',
             androidEnableCancelButton: true,
           };
           $cordovaActionSheet.show(options).then(function(index) {
             if (index == 2) {
               $scope.takePicture();
             } else if (index == 3) {
               $scope.openPicker();
             } else if (index == 4) {
               $scope.filePicker();
             } else if (index == 1) {
               $scope.recordVideo();
             }
           });
         }
         $scope.recordVideo = function() {
         // capture callback
         var captureSuccess = function(mediaFiles) {
          if ($scope.uploadType == "addComment") {
           $ionicLoading.show({
             template: templateLoading
           });
           $scope.uploadAmazon(mediaFiles);
           return;
         }
         mediaFiles.forEach(function(itm) {
           $scope.files.push(itm);
         });
       };
         // capture error callback
         var captureError = function(error) {
           navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
         };

         // start video capture
         navigator.device.capture.captureVideo(captureSuccess, captureError, { limit: 1 });
       }
       $scope.openPicker = function() {
         var options = {
           maximumImagesCount: 50,
           width: 0,
           height: 0,
           quality: 100
         };
         var data = [];
         $cordovaImagePicker.getPictures(options).then(function(results) {
           results.forEach(function(itm) {
             var filename = itm.substr(itm.lastIndexOf('/') + 1);
             data.push({ name: filename, type: 'image/jpeg', localURL: itm });
             if ($scope.uploadType == "addComment") {
               if (data.length == results.length) {
                 $ionicLoading.show({
                   template: templateLoading
                 });
                 $scope.uploadAmazon(data);
               }
             } else {
               $scope.files.push({ name: filename, type: 'image/jpeg', localURL: itm });
                     // window.plugins.Base64.encodeFile(itm, function(base64) {
                     // $scope.files.push({ name: filename, type: 'image/jpeg', localURL: itm, base64: base64 });
                     // });
                   }
                 })
         });
       }
       $scope.takePicture = function() {
         var options = {
           quality: 100,
           destinationType: Camera.DestinationType.FILE_URI,
           sourceType: Camera.PictureSourceType.CAMERA,
             // allowEdit: true,
             // targetWidth: 500,
             // targetHeight: 500,
             encodingType: Camera.EncodingType.JPEG,
             popoverOptions: CameraPopoverOptions,
             saveToPhotoAlbum: true
           };
         // $timeout(function() {
           $cordovaCamera.getPicture(options).then(function(imageData) {
             console.log(imageData);
             var filename = imageData.substr(imageData.lastIndexOf('/') + 1);
             if ($scope.uploadType == "addComment") {
               $ionicLoading.show({
                 template: templateLoading
               });
               $scope.uploadAmazon([{ name: filename, type: 'image/jpeg', localURL: imageData }]);
             } else {
               $scope.files.push({ name: filename, type: 'image/jpeg', localURL: imageData });
                 // window.plugins.Base64.encodeFile(itm, function(base64) {
                 // $scope.files.push({ name: filename, type: 'image/jpeg', localURL: itm, base64: base64 });
                 // });
               }
             }, function(err) {
               $cordovaToast.showLongTop(err);
               console.log(err);
             });
         // }, 500)

       }
       $scope.filePicker = function() {
         // for IOS
         // $timeout(function() {
           FilePicker.pickFile(function(path) {
             var arrFileSplit = path.split(".");
             var type = getFileType(arrFileSplit[arrFileSplit.length - 1].toLowerCase());
             var filename = path.substr(path.lastIndexOf('/') + 1);

             if ($scope.uploadType == "addComment") {
               $ionicLoading.show({
                 template: templateLoading
               });
               $scope.uploadAmazon([{ name: filename, type: type, localURL: path }]);
             } else {
                 // if (type == 'image/jpeg') {
                 //     window.plugins.Base64.encodeFile(path, function(base64) {
                 //         $ionicLoading.hide();
                 //         $scope.files.push({ name: filename, type: type, localURL: path, base64: base64 });
                 //     });
                 // } else {
                   $scope.files.push({ name: filename, type: type, localURL: path });
                 // }
               }
             //if error change picker for android
           }, function(err) {
             fileChooser.open(function(uri) {
                 // convert uri include extension
                 window.FilePath.resolveNativePath(uri, function(path) {
                   var arrFileSplit = path.split(".");
                   var type = getFileType(arrFileSplit[arrFileSplit.length - 1].toLowerCase());
                   var filename = path.substr(path.lastIndexOf('/') + 1);
                   if ($scope.uploadType == "addComment") {
                     $ionicLoading.show({
                       template: templateLoading
                     });
                     $scope.uploadAmazon([{ name: filename, type: type, localURL: path }]);
                   } else {
                         // if (type == 'image/jpeg') {
                         //     window.plugins.Base64.encodeFile(path, function(base64) {
                         //         $ionicLoading.hide();
                         //         $scope.files.push({ name: filename, type: type, localURL: path, base64: base64 });
                         //     });
                         // } else {
                           $scope.files.push({ name: filename, type: type, localURL: path });
                         // }
                       }
                     }, function(errer) {
                       $cordovaToast.showLongTop(errer);
                     });
               }, function(err) {
                 $cordovaToast.showLongTop(err);
               });
           });
         // }, 500)

       }
       $scope.removeFile = function(idx) {
         $scope.files.splice(idx, 1);
       }

     // Task-Filter
     var paging={rows: 200, current_page: 1};
     $scope.dataTaskFilter = {};
     $scope.dataTaskFilter.assignee = [];
     $scope.dataTaskFilter.creactor = [];
     $scope.dataTaskFilter.follower = [];
     $scope.dataTaskFilter.taskStatus = 'All';
     $scope.dataTaskFilter.taskType = 'Standard';
     $scope.dataTaskFilter.sortBy = 'duedate';
     $scope.dataTaskFilter.sortType_ = 'true';
     $scope.dataTaskFilter.seachMode_ = 'Exact search';

     $scope.dataTaskFilterAddQuery = {};
     $scope.dataTaskFilterAddQuery.assignee = [];
     $scope.dataTaskFilterAddQuery.creactor = [];
     $scope.dataTaskFilterAddQuery.follower = [];
     $scope.dataTaskFilterAddQuery.taskStatus = 'All';
     $scope.dataTaskFilterAddQuery.taskType = 'Standard';
     $scope.dataTaskFilterAddQuery.sortBy = 'duedate';
     $scope.dataTaskFilterAddQuery.sortType_ = 'true';
     $scope.dataTaskFilterAddQuery.seachMode_ = 'Exact search';


     $scope.showFilter = false;
     $scope.dataTaskFilterEditQuery = {};
     $scope.taskQuery = {};
     $scope.dueend = moment().format(conFig.formatDate.toUpperCase());
     $scope.duestart = moment().add(-365, 'days').format(conFig.formatDate.toUpperCase());
     $scope.createdend = moment().format(conFig.formatDate.toUpperCase());
     $scope.createdstart = moment().add(-365, 'days').format(conFig.formatDate.toUpperCase());

     $scope.dueendAdd = moment().format(conFig.formatDate.toUpperCase());
     $scope.duestartAdd = moment().add(-365, 'days').format(conFig.formatDate.toUpperCase());
     $scope.createdendAdd = moment().format(conFig.formatDate.toUpperCase());
     $scope.createdstartAdd = moment().add(-365, 'days').format(conFig.formatDate.toUpperCase());

     $scope.dueendEdit = '';
     $scope.duestartEdit = '';
     $scope.createdendEdit = '';
     $scope.createdstartEdit = '';
     $scope.getTaskQuery = function() {
       $scope.openByGetTemplate('popupTaskFilterQuery');
       Taskfilters.getAllTaskQuery($scope.dataTaskFilterAddQuery).success(function(data) {
        if(data.status==false){
          $cordovaToast.showLongCenter(data.msg);
        }
        else{
          $scope.allTaskQuery = data;
          $scope.taskQuery.idx = 0;
        }

      });
     };
     $scope.queryName = "";
     $scope.queryChange = function(query) {
       $scope.listviewId = query.id;
       $scope.queryName = query.name;
       $scope.taskfilters('function', query.id);
     }
     $scope.taskfilters = function(from, id) {
       $scope.showFilter = false;
       $ionicLoading.show({
         template: templateLoading
       });
       if (from == 'form') {
         $scope.dataTaskFilter.duestart = $('#due_start_filter').val();
         $scope.dataTaskFilter.dueend = $('#due_end_filter').val();
         $scope.dataTaskFilter.createdstart = $('#created_start_filter').val();
         $scope.dataTaskFilter.createdend = $('#created_end_filter').val();
         if ($scope.dataTaskFilter.duestart != '') {
           $scope.dataTaskFilter.duestartFomat = moment($scope.dataTaskFilter.duestart, 'MM/DD/YYYY').format('YYYY-MM-DD');
         }
         if ($scope.dataTaskFilter.dueend != '') {
           $scope.dataTaskFilter.dueendFomat = moment($scope.dataTaskFilter.dueend, 'MM/DD/YYYY').format('YYYY-MM-DD');
         }
         if ($scope.dataTaskFilter.createdstart != '') {
           $scope.dataTaskFilter.createdstartFomat = moment($scope.dataTaskFilter.createdstart, 'MM/DD/YYYY').format('YYYY-MM-DD');
         }
         if ($scope.dataTaskFilter.createdend != '') {
           $scope.dataTaskFilter.createdendFomat = moment($scope.dataTaskFilter.createdend, 'MM/DD/YYYY').format('YYYY-MM-DD');
         }
         $scope.dataTaskFilter.seachMode = ($scope.dataTaskFilter.seachMode_ == 'Exact search') ? true : false;
         $scope.dataTaskFilter.sortType = ($scope.dataTaskFilter.sortType_ == 'false') ? false : true;
       } else {
         $scope.dataTemp = _.where($scope.allTaskQuery, { id: id });
         $scope.datatofilter = JSON.parse($scope.dataTemp[0].content);
         $scope.dataTaskFilter = $scope.datatofilter;
       }
       $scope.dataViewQuery = $scope.dataTaskFilter;
       $scope.dataTaskFilter.forPaging=paging;
       Taskfilters.filter($scope.dataTaskFilter).success(function(data) {
        if(data.status == false){
          $cordovaToast.showLongCenter(data.msg);
        }
        else{
          $ionicLoading.hide();
          $scope.showFilter = true;
          $scope.afterFilter = data.data;
          _.each($scope.afterFilter, function(val) {
           val.type = val.statusName.toLowerCase();
           if (val.description) {
             if (val.description.length > 160) {
               val.descriptionShow = val.description.substring(0, 160) + '...';
               val.seeMore = true;
             } else {
               val.descriptionShow = val.description;
               val.seeMore = false;
             }
           }
         });
          if (from == 'form') {
           $scope.queryName = "";
         }
         $scope.closeTarget('#popupTaskFilterQuery');
         $scope.closeTarget('#popupEditTaskFilter');
       }
     }).error(function(data, status, headers, config) {
       $ionicLoading.hide();
       console.log('error status: ' + status);
       $cordovaToast.showLongTop('Connection Error!!!');
     });
   };
   $scope.clearFormFilter = function() {
     $scope.dataTaskFilter = {};
     $scope.dataTaskFilter.assignee = [];
     $scope.dataTaskFilter.creactor = [];
     $scope.dataTaskFilter.follower = [];
     $scope.initialTaskFilterAssignee = [];
     $scope.initialTaskFilterCreator = [];
     $scope.initialTaskFilterFollower = [];
     $scope.dataTaskFilter.taskStatus = 'All';
     $scope.dataTaskFilter.seachMode = false;
     $scope.dataTaskFilter.taskType = 'Standard';
     $scope.dataTaskFilter.sortBy = 'duedate';
     $scope.dataTaskFilter.sortType = false;
     $('#due_start_filter').val(moment().format(conFig.formatDate.toUpperCase()));
     $('#created_start_filter').val(moment().format(conFig.formatDate.toUpperCase()));
     $('#due_end_filter').val(moment().add(1, 'days').format(conFig.formatDate.toUpperCase()));
     $('#created_end_filter').val(moment().add(1, 'days').format(conFig.formatDate.toUpperCase()));
     $scope.afterFilter = {};
     $scope.queryName = "";
   }
   $scope.clearFormFilterAdd = function() {
     $scope.dataTaskFilterAddQuery = {};
     $scope.dataTaskFilterAddQuery.assignee = [];
     $scope.dataTaskFilterAddQuery.creactor = [];
     $scope.dataTaskFilterAddQuery.follower = [];
     $scope.initialTaskFilterAssigneeAdd = [];
     $scope.initialTaskFilterCreatorAdd = [];
     $scope.initialTaskFilterFollowerAdd = [];
     $scope.dataTaskFilterAddQuery.taskStatus = 'All';
     $scope.dataTaskFilterAddQuery.seachMode = false;
     $scope.dataTaskFilterAddQuery.taskType = 'Standard';
     $scope.dataTaskFilterAddQuery.sortBy = 'duedate';
     $scope.dataTaskFilterAddQuery.sortType_ = 'true';
     $('#due_start_filter_add').val(moment().format(conFig.formatDate.toUpperCase()));
     $('#created_start_filter_add').val(moment().format(conFig.formatDate.toUpperCase()));
     $('#due_end_filter_add').val(moment().add(1, 'days').format(conFig.formatDate.toUpperCase()));
     $('#created_end_filter_add').val(moment().add(1, 'days').format(conFig.formatDate.toUpperCase()));
     $scope.afterFilter = {};
     $scope.queryName = "";
   }

   $scope.filterTaskFilterUser = function(query, type) {
     var returnValue = { items: [] };
     var exceptID = [];
     switch (type) {
       case 'assign':
       exceptID = $scope.autocompleteList.TaskFilterAssignee;
       break;
       case 'creator':
       exceptID = $scope.autocompleteList.TaskFilterCreator;
       break;
       case 'follower':
       exceptID = $scope.autocompleteList.TaskFilterFollower;
       break;
       case 'assignAdd':
       exceptID = $scope.autocompleteList.TaskFilterAssigneeAdd;
       break;
       case 'creatorAdd':
       exceptID = $scope.autocompleteList.TaskFilterCreatorAdd;
       break;
       case 'followerAdd':
       exceptID = $scope.autocompleteList.TaskFilterFollowerAdd;
       break;
       case 'assignEdit':
       exceptID = $scope.autocompleteList.TaskFilterAssigneeEdit;
       break;
       case 'creatorEdit':
       exceptID = $scope.autocompleteList.TaskFilterCreatorEdit;
       break;
       case 'followerEdit':
       exceptID = $scope.autocompleteList.TaskFilterFollowerEdit;
       break;
     }
     if (!exceptID) exceptID = [];
     $scope.allUser.forEach(function(item) {
       if (exceptID.indexOf(item.id) < 0) {
         if (item.screen_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
           returnValue.items.push(item);
         }
       }
     })
     return returnValue;
   }



   $scope.onSelectTaskFilterUser = function(callback, type) {
     switch (type) {
       case 'assign':
       $scope.dataTaskFilter.assignee.push(callback.item);
       break;
       case 'creator':
       $scope.dataTaskFilter.creactor.push(callback.item);
       break;
       case 'follower':
       $scope.dataTaskFilter.follower.push(callback.item);
       break;
       case 'assignAdd':
       $scope.dataTaskFilterAddQuery.assignee.push(callback.item);
       break;
       case 'creatorAdd':
       $scope.dataTaskFilterAddQuery.creactor.push(callback.item);
       break;
       case 'followerAdd':
       $scope.dataTaskFilterAddQuery.follower.push(callback.item);
       break;
       case 'assignEdit':
       $scope.dataTaskFilterEditQuery.assignee.push(callback.item);
       break;
       case 'creatorEdit':
       $scope.dataTaskFilterEditQuery.creactor.push(callback.item);
       break;
       case 'followerEdit':
       $scope.dataTaskFilterEditQuery.follower.push(callback.item);
       break;
     }

   }
   $scope.onRemoveTaskFilterUser = function(callback, type) {
     switch (type) {
       case 'assign':
       var index = $scope.dataTaskFilter.assignee.indexOf(callback.item);
       $scope.dataTaskFilter.assignee.splice(index, 1);
       break;
       case 'creator':
       var index = $scope.dataTaskFilter.creactor.indexOf(callback.item);
       $scope.dataTaskFilter.creactor.splice(index, 1);
       break;
       case 'follower':
       var index = $scope.dataTaskFilter.follower.indexOf(callback.item);
       $scope.dataTaskFilter.follower.splice(index, 1);
       break;
       case 'assignAdd':
       var index = $scope.dataTaskFilterAddQuery.assignee.indexOf(callback.item);
       $scope.dataTaskFilterAddQuery.assignee.splice(index, 1);
       break;
       case 'creatorAdd':
       var index = $scope.dataTaskFilterAddQuery.creactor.indexOf(callback.item);
       $scope.dataTaskFilterAddQuery.creactor.splice(index, 1);
       break;
       case 'followerAdd':
       var index = $scope.dataTaskFilterAddQuery.follower.indexOf(callback.item);
       $scope.dataTaskFilterAddQuery.follower.splice(index, 1);
       break;
       case 'assignEdit':
       var index = $scope.dataTaskFilterEditQuery.assignee.indexOf(callback.item);
       $scope.dataTaskFilterEditQuery.assignee.splice(index, 1);
       break;
       case 'creatorEdit':
       var index = $scope.dataTaskFilterEditQuery.creactor.indexOf(callback.item);
       $scope.dataTaskFilterEditQuery.creactor.splice(index, 1);
       break;
       case 'followerEdit':
       var index = $scope.dataTaskFilterEditQuery.follower.indexOf(callback.item);
       $scope.dataTaskFilterEditQuery.follower.splice(index, 1);
       break;
     }

   }
   $scope.setValueTaskFilter = function(modelValue) {
     return [];
   };
   $scope.setValueTaskFilterEdit = function(modelValue) {
     for (var i = 0; i < $scope.allUser.length; i++) {
       if ($scope.allUser[i].id == modelValue) {
         return $scope.allUser[i];
       }
     }
     return {};
   };
   $scope.addtaskquery = function(formValidate) {
     if (formValidate.$invalid)
       $cordovaToast.showLongTop('Please fill all the required information.!!!');
     $scope.dataTaskFilterAddQuery.duestart = $('#due_start_filter_add').val();
     $scope.dataTaskFilterAddQuery.dueend = $('#due_end_filter_add').val();
     $scope.dataTaskFilterAddQuery.createdstart = $('#created_start_filter_add').val();
     $scope.dataTaskFilterAddQuery.createdend = $('#created_end_filter_add').val();
     if ($scope.dataTaskFilterAddQuery.duestart != '') {
       $scope.dataTaskFilterAddQuery.duestartFomat = moment($scope.dataTaskFilterAddQuery.duestart, 'MM/DD/YYYY').format('YYYY-MM-DD');
     }
     if ($scope.dataTaskFilterAddQuery.dueend != '') {
       $scope.dataTaskFilterAddQuery.dueendFomat = moment($scope.dataTaskFilterAddQuery.dueend, 'MM/DD/YYYY').format('YYYY-MM-DD');
     }
     if ($scope.dataTaskFilterAddQuery.createdstart != '') {
       $scope.dataTaskFilterAddQuery.createdstartFomat = moment($scope.dataTaskFilterAddQuery.createdstart, 'MM/DD/YYYY').format('YYYY-MM-DD');
     }
     if ($scope.dataTaskFilterAddQuery.createdend != '') {
       $scope.dataTaskFilterAddQuery.createdendFomat = moment($scope.dataTaskFilterAddQuery.createdend, 'MM/DD/YYYY').format('YYYY-MM-DD');
     }
     $scope.dataTaskFilterAddQuery.seachMode = ($scope.dataTaskFilterAddQuery.seachMode_ == 'Exact search') ? true : false;
     $scope.dataTaskFilterAddQuery.sortType = ($scope.dataTaskFilterAddQuery.sortType_ == 'false') ? false : true;
     Taskfilters.savefilter($scope.dataTaskFilterAddQuery).success(function(data) {
       if (data.status) {
         closeTarget('#popupAddTaskFilterQuery');
         $scope.getTaskQuery();
         $scope.clearFormFilterAdd();
         $cordovaToast.showLongTop(data.msg);
       }
       else{
        $cordovaToast.showLongCenter(data.msg);
      }
    }).error(function(data, status, headers, config) {
     $ionicLoading.hide();
     console.log('error status: ' + status);
     $cordovaToast.showLongTop('Connection Error!!!');
   });
  };
  $scope.editquery = function(id) {
   $scope.openByGetTemplate('popupEditTaskFilterQuery');
   $timeout(function() {
     $scope.dataEditQuery = _.where($scope.allTaskQuery, { id: id });
     $scope.dataTaskFilterEditQuery = JSON.parse($scope.dataEditQuery[0].content);
     $scope.dataTaskFilterEditQuery.id = id;
     $scope.dataTaskFilterEditQuery.seachMode_ = $scope.dataTaskFilterEditQuery.seachMode ? 'Exact search' : 'Fuzzy search';
     $scope.dataTaskFilterEditQuery.sortType_ = $scope.dataTaskFilterEditQuery.sortType ? 'true' : 'false';
     $scope.initialTaskFilterAssigneeEdit = _.pluck($scope.dataTaskFilterEditQuery.assignee, "id");
     $scope.initialTaskFilterCreatorEdit = _.pluck($scope.dataTaskFilterEditQuery.creactor, "id");
     $scope.initialTaskFilterFollowerEdit = _.pluck($scope.dataTaskFilterEditQuery.follower, "id");
     $scope.dueendEdit = $scope.dataTaskFilterEditQuery.dueend;
     $scope.duestartEdit = $scope.dataTaskFilterEditQuery.duestart;
     $scope.createdendEdit = $scope.dataTaskFilterEditQuery.createdend;
     $scope.createdstartEdit = $scope.dataTaskFilterEditQuery.createdstart;
             // $('#due_start_filter_edit').val($scope.dataTaskFilterEditQuery.duestart);
             // $('#due_end_filter_edit').val($scope.dataTaskFilterEditQuery.dueend);
             // $('#created_start_filter_edit').val($scope.dataTaskFilterEditQuery.createdstart);
             // $('#created_end_filter_edit').val($scope.dataTaskFilterEditQuery.createdend);
           }, 1000)

 }
 $scope.updateTaskQuery = function(formValidate) {
   if (formValidate.$invalid)
     $cordovaToast.showLongTop('Please fill all the required information.!!!');
   $scope.dataTaskFilterEditQuery.duestart = $('#due_start_filter_edit').val();
   $scope.dataTaskFilterEditQuery.dueend = $('#due_end_filter_edit').val();
   $scope.dataTaskFilterEditQuery.createdstart = $('#created_start_filter_edit').val();
   $scope.dataTaskFilterEditQuery.createdend = $('#created_end_filter_edit').val();

   if ($scope.dataTaskFilterEditQuery.duestart != '') {
     $scope.dataTaskFilterEditQuery.duestartFomat = moment($scope.dataTaskFilterEditQuery.duestart, 'MM/DD/YYYY').format('YYYY-MM-DD');
   }
   if ($scope.dataTaskFilterEditQuery.dueend != '') {
     $scope.dataTaskFilterEditQuery.dueendFomat = moment($scope.dataTaskFilterEditQuery.dueend, 'MM/DD/YYYY').format('YYYY-MM-DD');
   }
   if ($scope.dataTaskFilterEditQuery.createdstart != '') {
     $scope.dataTaskFilterEditQuery.createdstartFomat = moment($scope.dataTaskFilterEditQuery.createdstart, 'MM/DD/YYYY').format('YYYY-MM-DD');
   }
   if ($scope.dataTaskFilterEditQuery.createdend != '') {
     $scope.dataTaskFilterEditQuery.createdendFomat = moment($scope.dataTaskFilterEditQuery.createdend, 'MM/DD/YYYY').format('YYYY-MM-DD');
   }
   $scope.dataTaskFilterEditQuery.seachMode = ($scope.dataTaskFilterEditQuery.seachMode_ == 'Exact search') ? true : false;
   $scope.dataTaskFilterEditQuery.sortType = ($scope.dataTaskFilterEditQuery.sortType_ == 'false') ? false : true;
   var taskFilterId = $scope.dataTaskFilterEditQuery.id;
   delete $scope.dataTaskFilterEditQuery.id;
   delete $scope.dataTaskFilterEditQuery.action;
   $ionicLoading.show({
     template: templateLoading
   });
   Taskfilters.updateTaskQuery(taskFilterId, $scope.dataTaskFilterEditQuery).success(function(data) {
    if(data.status == false){
      $cordovaToast.showLongCenter(data.msg);
    }
    else{
      $ionicLoading.hide();
      if (data.status) {
       $scope.closeTarget('#popupEditTaskFilterQuery');
       $scope.getTaskQuery();
       $cordovaToast.showLongTop(data.msg);
     }
     else{
      $cordovaToast.showLongCenter(data.msg);
    }
  }
}).error(function(data, status, headers, config) {
 $ionicLoading.hide();
 console.log('error status: ' + status);
 $cordovaToast.showLongTop('Connection Error!!!');
});
};
$scope.confrimtaskquery = function(id) {
 $scope.openByGetTemplate('confirmDeleteTaskFilterQuery');
 $scope.deleteListviewusersData = {
   id: id
 };
}
$scope.deletetaskquery = function() {
 $ionicLoading.show({
   template: templateLoading
 });
 Taskfilters.destroy($scope.deleteListviewusersData.id).success(function(data) {
  if(data.status == false){
    $cordovaToast.showLongCenter(data.msg)
  }
  else{
    $ionicLoading.hide();
    if (data.status) {
     $scope.closeTarget("#confirmDeleteTaskFilterQuery");
     $scope.getTaskQuery();
     $cordovaToast.showLongTop(data.msg);
   } else {
     $cordovaToast.showLongTop(data.msg);
   }
 }
});
}
$scope.getTaskDetail = function(id) {
 $scope.arrTaskId = _.pluck($scope.afterFilter, 'id');
 $scope.getDefaultDataTask($scope.arrTaskId, id);
}

$scope.getDefaultDataTask = function(arrTaskId, taskId) {
 $scope.dataDefaultTaskSearch = {};
 $scope.dataDefaultTaskSearch.arrTaskId = [];
 $scope.dataDefaultTaskSearch.arrTaskId = arrTaskId;
 Taskfilters.getDefaultTask($scope.dataDefaultTaskSearch).success(function(data) {
   $scope.dataTaskDefault = data;
   $scope.selectedTask = _.where($scope.dataTaskDefault, { id: parseInt(taskId) });
   $scope.dataSent = {};
   $scope.dataSent.allTask = $scope.dataTaskDefault;
   $scope.dataSent.selectedTask = $scope.selectedTask[0];
   $scope.dataSent.selectedTask.type = $scope.dataSent.selectedTask.type.toLowerCase();
   $scope.dataSent.notification_task_id = $scope.dataSent.selectedTask.id;

   $scope.dataSent.selectedTask.starttime = globalParseDate($scope.dataSent.selectedTask.starttime);
   $scope.dataSent.selectedTask.endtime = globalParseDate($scope.dataSent.selectedTask.endtime);

   _.each($scope.dataSent.allTask, function(val) {
     val.starttime = globalParseDate(val.starttime);
     val.endtime = globalParseDate(val.endtime);
   });
   tasks.dataTask = $scope.dataSent.allTask;
   $scope.oTask = _.union($scope.oTask, $scope.dataSent.allTask);
   $scope.getCurrentTask($scope.dataSent.selectedTask, $scope.oTask, 'open');

 });
};

$scope.switchSortByValue = function(value) {
  var textSortBy = '';
  switch (value) {
   case 'duedate':
   textSortBy = 'Due date';
   break;
   case 'createdate':
   textSortBy = 'Create date';
   break;
   case 'creator':
   textSortBy = 'Creator';
   break;
   case 'assignee':
   textSortBy = 'Assignee';
   break;
 }
 return textSortBy;
};

$scope.checkObjItemInArray = function(obj,arr) {
  var val = false;
  if(obj!=undefined){
    arr.forEach(function(item) {
      if(parseInt(obj.id) == parseInt(item.id)){
        val = true;
      }
    })
  }else{
    val = true;
  }
  return val;
};

$scope.seemore = function(id,val,arrTask){
  if(val){
    _.where(arrTask, {
     id: id
   })[0].seeMore = false;
  }
  else{
    _.where(arrTask, {
     id: id
   })[0].seeMore = true;
  }
}

$scope.showImagePhone = function (url) {
  if (url) {
    if (url.indexOf('s3.amazonaws.com') > -1) {
      return url;
    } else {
      return url_site + '/' + url;
    }
  } else {
    return 'resources/images/thumnails/profile-default.png';
  }
}
      // $scope.downloadFile = function (url) {
      //   var urlFile = decodeURIComponent($scope.showImagePhone(url)); //check showImagePhone if error
      //   var arrData = urlFile.split("/");
      //   var fileName = arrData[arrData.length - 1];
      //   var trustHosts = true;
      //   var options = {};
      //   $ionicLoading.show({
      //     template: templateLoading
      //   });
      //   if (isiOs) {
      //     var targetPath = cordova.file.syncedDataDirectory + 'RGD/' + fileName;
      //     $cordovaFile.createDir(cordova.file.syncedDataDirectory, "RGD", false).then(function (success) {
      //       console.log(success);
      //       $ionicLoading.hide();
      //       $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
      //     }, function (error) {
      //       console.log(error);
      //       $ionicLoading.hide();
      //       $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
      //     });
      //   } else {
      //     var targetPath = cordova.file.externalRootDirectory + 'RGD/' + fileName;
      //     $cordovaFile.createDir(cordova.file.externalRootDirectory, "RGD", false).then(function (success) {
      //       $ionicLoading.hide();
      //       $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
      //     }, function (error) {
      //       $ionicLoading.hide();
      //       $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
      //     });
      //   }
      // }
      $scope.downloadFile = function (url) {
        $ionicLoading.show({
          template: templateLoading
        });
        var urlFile = decodeURIComponent($scope.showImagePhone(url)); //check showImagePhone if error
        var arrData = urlFile.split("/");
        var fileName = arrData[arrData.length - 1];
        var trustHosts = true;
        var options = {};
        if (isiOs) {
          $scope.cordovaBrowser(url);
        } else {
          var targetPath = cordova.file.externalRootDirectory + 'RGD/' + fileName;
          $cordovaFile.createDir(cordova.file.externalRootDirectory, "RGD", false).then(function (success) {
            $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
          }, function (error) {
            $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
          });
        }
      }
      $scope.cordovaDownload = function (urlFile, targetPath, options, trustHosts) {
        $cordovaFileTransfer.download(urlFile, targetPath, options, trustHosts).then(function (result) {
          $ionicLoading.hide();
          console.log(result);
          $cordovaToast.showLongTop('Download Successful!!! Target: ' + result.fullPath);
        }, function (err) {
          $ionicLoading.hide();
          console.log(err);
        }, function (progress) {
          $ionicLoading.show({
            template: templateLoading
          });
        });
      }
      $scope.checkedTaskChange = function(test) {
        $scope.checkOnClick($scope.currentoTask, test);
      }

      $scope.trustDangerousSnippet = function(content) { // trust html in angular
        return $sce.trustAsHtml($scope.replaceURLWithHTMLLinksNew(content));
      };
      $scope.replaceURLWithHTMLLinksNew = function(content) {
        var href_index = content.indexOf("href=");
        if(href_index > -1){
          return content;
        }else{
          var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&@#\/%?=~_()|!:,.;]*[-a-z0-9+&@#\/%=~_()|])/ig;
          var string = content.replace(re, function(match, lParens, url) {
            var rParens = '';
            lParens = lParens || '';
            var lParenCounter = /\(/g;
            while (lParenCounter.exec(lParens)) {
              var m;
              if (m = /(.*)(\.\).*)/.exec(url) || /(.*)(\).*)/.exec(url)) {
                url = m[1];
                rParens = m[2] + rParens;
              }
            }
            return lParens + "<a  target='_blank' class='link-2' href='" + url + "'>" + url + "</a>" + rParens;
          });
          var matches = string.match(/href="customer-detail\.html\?customerId=(\d*)"/i);
          var customerId = '';
          if (matches != null) {
            customerId = matches[1];
            var strReplace = 'onclick="redirectTo(\'customers.html?customer_id=' + matches[1] + '\')"';
            string = string.replace(/href="customer-detail\.html\?customerId=\d*"/i, strReplace);
          }

          matches = string.match(/href="appointments\.html\?appointment_id=(\d*)"/i);
          if (matches != null) {
            var strReplace = 'onclick="redirectTo(\'scheduleapp.html?appointment_id=' + matches[1] + '\')"';
            if ($scope.roleName == isFieldinstaller || $scope.roleName == isSalesman)
              strReplace = 'onclick="redirectTo(\'myschedule.html?appointment_id=' + matches[1] + '\')"';
            string = string.replace(/href="appointments\.html\?appointment_id=\d*"/i, strReplace);
          }

          matches = string.match(/href="invoice\.html\?invoice_id=(\d*)"/i);
          if (matches != null && customerId !='') {
            var strReplace = 'onclick="redirectTo(\'' + matches[1] + '\',\'invoice\')"';
            var strReplace = 'onclick="redirectTo(\'order.html#/board/order/'+ customerId + '/' + matches[1] + '/invoice/null/0' +'\')"';
            string = string.replace(/target="_blank" href="invoice\.html\?invoice_id=\d*"/i, strReplace);
          }
          return string;
        }
      }

      $scope.$on('getJsonData', function (event, data) {
        var jsondata = data.data;
        var index = _.findIndex(jsondata,{roletree_id:'78'});
        if (getParameterByName('action')=='filter'){
          if(jsondata[index].child[1].check){
            $scope.showFilterButton = jsondata[index].child[1].child[2].check;
            $scope.showAddEditRemoveQuery = jsondata[index].child[1].child[1].check;
            $scope.addComment = jsondata[index].child[1].child[3].child[0].check;
            $scope.showCreateSubTask = jsondata[index].child[1].child[3].child[1].check;
            $scope.showAttachFile = jsondata[index].child[1].child[3].child[2].check;
            $scope.showUpdateAsignFollow = jsondata[index].child[1].child[3].child[3].check;
            $scope.showChangeDate = jsondata[index].child[1].child[3].child[4].check;
            $scope.showAddTask = jsondata[index].child[1].child[1].check;
            $scope.openByGetTemplate('popupTaskFilter');
          }else{
            localStorage.setItem("login_status", "0");
            redirectTo('index.html');
          }

        }else{
          if(jsondata[index].child[0].check){
            $scope.showAddTask = jsondata[index].child[0].child[0].check;
            $scope.showAsignToGroup = jsondata[index].child[0].child[0].child[0].check;
            $scope.showAsignManual = jsondata[index].child[0].child[0].child[1].check;
            $scope.showFilter = jsondata[index].child[1].check;
            $scope.addComment = jsondata[index].child[0].child[1].child[0].check;
            $scope.showCreateSubTask = jsondata[index].child[0].child[1].child[1].check;
            $scope.showAttachFile = jsondata[index].child[0].child[1].child[2].check;
            $scope.showUpdateAsignFollow = jsondata[index].child[0].child[1].child[3].check;
            $scope.showChangeDate = jsondata[index].child[0].child[1].child[4].check;
          }else{
            localStorage.setItem("login_status", "0");
            redirectTo('index.html');
          }
          
        }
        $scope.renderTemplateData();
      })


      
     // end edit
   })
