var cusFlag = null;
var cusLeadSource = null;
var appGroup = null;
var appDetail = null;
var oppService = null;
var appScope = null;
var noteTaskScope = null;
var ionicLoading = null;
var ionicScrollDelegate = null;
var location_ = null;
var cordovaToast = null;
var appScopeMobile;
var appointments_pagesize = $('#appointments_pagesize');
var customer_type_new_customer_id = 1;
angular.module('monospaced.elastic', []).constant('msdElasticConfig', {
  append: ''
}).directive('msdElastic', ['$timeout', '$window', 'msdElasticConfig',
function($timeout, $window, config) {
  'use strict';
  return {
    require: 'ngModel',
    restrict: 'A, C',
    link: function(scope, element, attrs, ngModel) {
        // cache a reference to the DOM element
        var ta = element[0],
        $ta = element;
        // ensure the element is a textarea, and browser is capable
        if (ta.nodeName !== 'TEXTAREA' || !$window.getComputedStyle) {
          return;
        }
        // set these properties before measuring dimensions
        $ta.css({
          'overflow': 'hidden',
          'overflow-y': 'hidden',
          'word-wrap': 'break-word'
        });
        // force text reflow
        var text = ta.value;
        ta.value = '';
        ta.value = text;
        var append = attrs.msdElastic ? attrs.msdElastic.replace(/\\n/g, '\n') : config.append,
        $win = angular.element($window),
        mirrorInitStyle = 'position: absolute; top: -999px; right: auto; bottom: auto;' + 'left: 0; overflow: hidden; -webkit-box-sizing: content-box;' + '-moz-box-sizing: content-box; box-sizing: content-box;' + 'min-height: 0 !important; height: 0 !important; padding: 0;' + 'word-wrap: break-word; border: 0;',
        $mirror = angular.element('<textarea aria-hidden="true" tabindex="-1" ' + 'style="' + mirrorInitStyle + '"/>').data('elastic', true),
        mirror = $mirror[0],
        taStyle = getComputedStyle(ta),
        resize = taStyle.getPropertyValue('resize'),
        borderBox = taStyle.getPropertyValue('box-sizing') === 'border-box' || taStyle.getPropertyValue('-moz-box-sizing') === 'border-box' || taStyle.getPropertyValue('-webkit-box-sizing') === 'border-box',
        boxOuter = !borderBox ? {
          width: 0,
          height: 0
        } : {
          width: parseInt(taStyle.getPropertyValue('border-right-width'), 10) + parseInt(taStyle.getPropertyValue('padding-right'), 10) + parseInt(taStyle.getPropertyValue('padding-left'), 10) + parseInt(taStyle.getPropertyValue('border-left-width'), 10),
          height: parseInt(taStyle.getPropertyValue('border-top-width'), 10) + parseInt(taStyle.getPropertyValue('padding-top'), 10) + parseInt(taStyle.getPropertyValue('padding-bottom'), 10) + parseInt(taStyle.getPropertyValue('border-bottom-width'), 10)
        },
        minHeightValue = parseInt(taStyle.getPropertyValue('min-height'), 10),
        heightValue = parseInt(taStyle.getPropertyValue('height'), 10),
        minHeight = Math.max(minHeightValue, heightValue) - boxOuter.height,
        maxHeight = parseInt(taStyle.getPropertyValue('max-height'), 10),
        mirrored,
        active,
        copyStyle = ['font-family', 'font-size', 'font-weight', 'font-style', 'letter-spacing', 'line-height', 'text-transform', 'word-spacing', 'text-indent'];
        // exit if elastic already applied (or is the mirror element)
        if ($ta.data('elastic')) {
          return;
        }
        // Opera returns max-height of -1 if not set
        maxHeight = maxHeight && maxHeight > 0 ? maxHeight : 9e4;
        // append mirror to the DOM
        if (mirror.parentNode !== document.body) {
          angular.element(document.body).append(mirror);
        }
        // set resize and apply elastic
        $ta.css({
          'resize': (resize === 'none' || resize === 'vertical') ? 'none' : 'horizontal'
        }).data('elastic', true);
        /*
         * methods
         */
         function initMirror() {
          var mirrorStyle = mirrorInitStyle;
          mirrored = ta;
          // copy the essential styles from the textarea to the mirror
          taStyle = getComputedStyle(ta);
          angular.forEach(copyStyle, function(val) {
            mirrorStyle += val + ':' + taStyle.getPropertyValue(val) + ';';
          });
          mirror.setAttribute('style', mirrorStyle);
        }

        function adjust() {
          var taHeight,
          taComputedStyleWidth,
          mirrorHeight,
          width,
          overflow;
          if (mirrored !== ta) {
            initMirror();
          }
          // active flag prevents actions in function from calling adjust again
          if (!active) {
            active = true;
            mirror.value = ta.value + append; // optional whitespace to improve animation
            mirror.style.overflowY = ta.style.overflowY;
            taHeight = ta.style.height === '' ? 'auto' : parseInt(ta.style.height, 10);
            taComputedStyleWidth = getComputedStyle(ta).getPropertyValue('width');
            // ensure getComputedStyle has returned a readable 'used value' pixel width
            if (taComputedStyleWidth.substr(taComputedStyleWidth.length - 2, 2) === 'px') {
              // update mirror width in case the textarea width has changed
              width = parseInt(taComputedStyleWidth, 10) - boxOuter.width;
              mirror.style.width = width + 'px';
            }
            mirrorHeight = mirror.scrollHeight;
            if (mirrorHeight > maxHeight) {
              mirrorHeight = maxHeight;
              overflow = 'scroll';
            } else if (mirrorHeight < minHeight) {
              mirrorHeight = minHeight;
            }
            mirrorHeight += boxOuter.height;
            ta.style.overflowY = overflow || 'hidden';
            if (taHeight !== mirrorHeight) {
              scope.$emit('elastic:resize', $ta, taHeight, mirrorHeight);
              ta.style.height = mirrorHeight + 'px';
            }
            // small delay to prevent an infinite loop
            $timeout(function() {
              active = false;
            }, 1, false);
          }
        }

        function forceAdjust() {
          active = false;
          adjust();
        }
        /*
         * initialise
         */
        // listen
        if ('onpropertychange' in ta && 'oninput' in ta) {
          // IE9
          ta['oninput'] = ta.onkeyup = adjust;
        } else {
          ta['oninput'] = adjust;
        }
        $win.bind('resize', forceAdjust);
        scope.$watch(function() {
          forceAdjust();
          return ngModel.$modelValue;
        }, function(newValue) {
          forceAdjust();
        });
        scope.$on('elastic:adjust', function() {
          initMirror();
          forceAdjust();
        });
        $timeout(adjust, 0, false);
        /*
         * destroy
         */
         scope.$on('$destroy', function() {
          $mirror.remove();
          $win.unbind('resize', forceAdjust);
        });
       }
     };
   }
   ]);
angular.module('AppointmentsController', ['monospaced.elastic']).controller('scheduleCtrl', function($cordovaInAppBrowser, $ionicActionSheet, $ionicHistory, $cordovaFile, $cordovaActionSheet, $cordovaCamera, //
  $cordovaFileTransfer, $cordovaImagePicker, $ionicScrollDelegate, $location, $timeout, $cordovaToast, $ionicLoading, $ionicPopup, $scope, //
  $sce, $compile, $http, $window, $interval, Login, Appointments, Appointmentstatuses, Appointmentgroups, Customers, Callaheads, //
  Customertypes, Flexiblecustomers, Users, Jobsites, Listviews, Listviewusers, Flags, Leadsources, Opportunities, Groups, Tasks, //
  Orders, Ordertypes, Orderstatuses, ivhTreeviewMgr, ivhTreeviewOptions, $rootScope, $stateParams, dataHtml, $stateParams, Customerfiles, $ionicSlideBoxDelegate, LocationService, $ionicPosition) {
  appScope = $scope;
  $scope.tier = tier;
  $scope.NoCaText = 'No CA';
  $scope.switchNotetasksCtrl = 'app';
  $scope.currentPage = 1;
  var pager = localStorage.getItem('appointments_pagesize');
  $scope.appointment_id = getParameterByName('appointment_id');
  $scope.org_page = getParameterByName('org_page');
  $scope.appointment_id == '' ? $scope.defaultlistview = 1 : $scope.defaultlistview = 0;
  $scope.itemsPerPage = pager ? pager : 5;
  $scope.entryLimit = $scope.itemsPerPage;
  $scope.searchAppointments = {
    rows: $scope.itemsPerPage,
    current_page: $scope.currentPage,
    search: ""
  };
  $scope.appStatusColor = appStatusColor;
  $scope.loadone = false;
  $scope.loadListAppointment = false;
  $scope.scheduleloaded = false;
  $scope.listviewloaded = false;
  $scope.currentuserId = currentIdLogin;
  $scope.listviewId = {};
  $scope.listviewId.value = 0;
  $scope.searchResult = [];
  $scope.viewUnavailableValue = false;
  $scope.firstLoadCalendar = true;
  $scope.dataTreeLoad = false;
  $scope.arrDepart = [];
  $scope.currentIdLogin = currentIdLogin;
  var isShowAreaToSchedule = false;
  var today = moment().format('YYYY-MM-DD');
  $scope.selectedDay = today;
  $scope.listToSchedule = {};
  $scope.listToScheduleCount = 0;
  $scope.dataAppCellHover = [];
  $scope.addListviewusersData = {};
  $scope.addListviewusersData.arrUserIdAddlistView = [];
  $scope.address = {};
  $scope.jobsites = [];
  $scope.arrSeach = [];
  $scope.addAppointmentsData = {};
  $scope.addAppointmentsData.jobsites = [];
  $scope.editAppointmentsData = {};
  $scope.editAppointmentsData.dataJobsite = [];
  $scope.deleteAppointmentsData = {};
  $scope.searchData = {};
  $scope.dataConvertApp = {};
  $scope.searchData.data = [];
  $scope.holdFieldWorkerOnApp = {};
  $scope.tempData = {};
  $scope.onMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(andRoid)|(Linux)|(webOS)/i) != null;
  // 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.dispathroom = '';
  ionicLoading = $ionicLoading;
  ionicScrollDelegate = $ionicScrollDelegate;
  location_ = $location;
  cordovaToast = $cordovaToast;
  cusFlag = Flags;
  cusLeadSource = Leadsources;
  appGroup = Appointmentgroups;
  appDetail = Appointments;
  oppService = Opportunities;
  $scope.switchNotetasksCtrl = 'app';
  $scope.filetypeAppointment = 'All';
  $scope.puchInTime = '';
  $scope.puchOutTime = '';
  $scope.addressToMapValue = 'appointmentMap.html?Sydney, NSW';
  $scope.tier = tier;
  if ($scope.tier.t1) {
    $scope.userSerectId = userSerectId;
  }
  $scope.numOfCol = 2;
  $scope.hideChangeApp = false;
  $scope.dataNewConfirm = {};
  $scope.disableSubmit = false;
  $scope.appIsCancel = '';
  $scope.check_init_schedule = false;
  $scope.NoCAIdString = NoCAId.toString();
  $scope.NoCaText = 'No CA';
  $scope.differentNoCaAndRouteColor = differentNoCaAndRouteColor;
  $scope.order_idapp = {};
  if (!$scope.dataViewAppNote) {
    $scope.dataViewAppNote = {};
  }
  if ($scope.tier.t1) {
    $scope.NoCAIdString = NoCAId.toString();
    $scope.NoCaText = 'No CA';
    $scope.differentNoCaAndRouteColor = differentNoCaAndRouteColor;
  }
  if ($scope.tier.t2) {
    var intervalDrawTimeLine = "";
  }
  var opts = ivhTreeviewOptions();
  opts.expandToDepth = 1;
  $scope.countFile = {};
  $scope.sortAppointmentFile = {};
  $scope.sortAppointmentFile.type = 0;
  appScopeMobile = $scope
  $scope.search = {};
  $scope.dataAppHtml = {};
  $scope.dataAppHtml.scheduleDay = moment().format('YYYY-MM-DD');
  $scope.setTime = false;
  $scope.dataViewAppNote = {};
  $scope.files = [];
  $scope.dataUpdateFlagNote = {};
  $scope.dataSendMail = {};
  $scope.sendToPushMsg = '';
  $scope.dataSendToPushRoom = {};
  $scope.dataSendToPushRoom.msg = '';
  $scope.tempDataNote = {};
  $scope.dataSaveOfficeNote = {};
  $scope.dataSaveFieldWorkerNote = {};
  $scope.dataAppointmentInfor = {};
  $scope.viewEstimateCounter = true;
  $scope.viewInvoiceCounter = true;
  $scope.viewPhotoCounter = true;
  $scope.viewPdfCounter = true;
  $scope.viewOtherfileCounter = true;
  $scope.viewAudioCounter = true;
  $scope.viewStatusLogCounter = true;
  $scope.viewDispathLogCounter = true;
  $scope.viewOfficeNoteAppHistory = false;
  $scope.viewFieldWorkerNotesAppHistory = false;
  $scope.estimateCounterAppDetail = 0;
  $scope.invoiceCounterAppDetail = 0;
  $scope.dataCounterForAppDetail = {};
  $scope.officeNoteAppHistory = '';
  $scope.fieldWorkerNotesAppHistory = '';
  $scope.selectJobIdArr = [];
  $scope.showNoAttacRecored = true;
  $scope.modePhotoView = 'hd';
  $scope.url_site = url_site;
  $scope.noAttackClicked = false;
  $scope.dataTypeFile = false;
  $scope.dataSlider = {};
  $scope.accessChangeJobStatus = true;
  $scope.loadAppByListView = false;
  $scope.beginScopeWatch = false;
  $scope.autocompleteEstimate = {};
  $scope.autocompleteEstimate.jobsiteFilter = [];
  $scope.arrFilterJobsite = [];
  $scope.initialJobsiteOrder = ['All'];
  $scope.holdValueAddress = {};
  $scope.holdValueAddress.addAppointment = [];
  $scope.holdValueAddress.editAppointment = [];
  $scope.dataPrintPdf = {};
  $scope.addUrlData = {};
  $scope.addUrlFrom = '';
  $scope.detailAppointmentData = {};
  $scope.create_status_from_order = false;
  $scope.data_from_order_check_list = {};
  $scope.renderTemplateData = function() {
    dataHtml.getTemplate('templates/dashboard/schedules/shedulesMenuHeadermodal.tpl').success(function(results) {
      $scope.dataAppHtml.menuHeader = results;
      dataHtml.getTemplate('templates/dashboard/schedules/shedulesContentmodal.tpl').success(function(results) {
        $scope.dataAppHtml.schedulesMainContent = results;
        dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupFiltermodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleFilter = results;
          dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupChildsmodal.tpl').success(function(results) {
            $scope.dataAppHtml.shedulesPopupChilds = results;
            setHeight("#main-content");
            $("#scheduleDay .day").html(moment().format('DD'));
            $("#scheduleDay .month").html(moment().format('MMMM'));
            $scope.getUsers();
          });
        });
      });
    });
  }
  $scope.openByGetTemplate = function(style, $callback = null) {
    $ionicLoading.show({
      template: templateLoading
    });
    $timeout(function() {
      switch (style) {
        case 'popupScheduleListView':
        dataHtml.getTemplate('templates/dashboard/schedules/schedulePopupListViewmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleListView = results;
          $scope.showTarget('#popupScheduleListView');
          $ionicLoading.hide();
        });
        break;
        case 'popupAddScheduleListView':
        dataHtml.getTemplate('templates/dashboard/schedules/schedulePopupListViewAddmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupAddScheduleListView = results;
          $scope.showTarget('#popupAddScheduleListView');
          $ionicLoading.hide();
        });
        break;
        case 'popupEditScheduleListView':
        dataHtml.getTemplate('templates/dashboard/schedules/schedulePopupListViewUpdatemodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupEditScheduleListView = results;
          $scope.showTarget('#popupEditScheduleListView');
        });
        break;
        case 'confirmDeleteScheduleListView':
        dataHtml.getTemplate('templates/dashboard/schedules/schedulePopupListViewDeletemodal.tpl').success(function(results) {
          $scope.dataAppHtml.confirmDeleteScheduleListView = results;
          $scope.showTarget('#confirmDeleteScheduleListView');
          $ionicLoading.hide();
        });
        break;
        case 'popupScheduleToSchedule':
        dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupAppointmentToSchedulemodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleToSchedule = results;
          $scope.showTarget('#popupScheduleToSchedule');
          $ionicLoading.hide();
        });
        break;
        case 'scheduleEditModal':
        dataHtml.getTemplate('templates/dashboard/schedules/scheduleEditmodal.tpl').success(function(results) {
          $scope.dataAppHtml.scheduleEditModal = results;
          $scope.showTarget('#scheduleEditModal');
          $ionicLoading.hide();
        });
        break;
        case 'popupAddScheduleNote':
        dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupTaskNoteAddmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupAddScheduleNote = results;
          $scope.showTarget('#popupAddScheduleNote');
          $ionicLoading.hide();
        });
        break;
        case 'scheduleContent':
        dataHtml.getTemplate('templates/dashboard/schedules/shedulesContentDetailsmodal.tpl').success(function(results) {
          $scope.dataAppHtml.scheduleContent = results;
          $scope.showTarget('#scheduleContent');
          $ionicLoading.hide();
        });
        break;
        case 'scheduleDetailEdit':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentDetailsEditmodal.tpl').success(function(results) {
          $scope.dataAppHtml.scheduleDetailEdit = results;
          $scope.showTarget('#scheduleDetailEdit');
          $ionicLoading.hide();
        });
        break;
        case 'optionScheduleDetail':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentDetailsOptionsmodal.tpl').success(function(results) {
          $scope.dataAppHtml.optionScheduleDetail = results;
          $scope.showTarget('#optionScheduleDetail');
          $ionicLoading.hide();
        });
        break;
        case 'optionScheduleDetailFileManagement':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentDetailsOptionsFileManagermentmodal.tpl').success(function(results) {
          $scope.dataAppHtml.optionScheduleDetailFileManagement = results;
          $scope.showTarget('#optionScheduleDetailFileManagement');
          $ionicLoading.hide();
        });
        break;
        case 'popupScheduleDetailFileManagementDetail':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentFileManagermentmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleDetailFileManagementDetail = results;
          $scope.showTarget('#popupScheduleDetailFileManagementDetail');
          $ionicLoading.hide();
        });
        break;
        case 'popupScheduleDetailFileManagementDetailOfHistory':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentFileManagermentOfHistorymodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleDetailFileManagementDetailOfHistory = results;
          $scope.showTarget('#popupScheduleDetailFileManagementDetailOfHistory');
          $ionicLoading.hide();
        });
        break;
        case 'popupAddScheduleDetailFileManagementDetail':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentFileManagermentAddFilemodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupAddScheduleDetailFileManagementDetail = results;
          $scope.showTarget('#popupAddScheduleDetailFileManagementDetail');
          $ionicLoading.hide();
        });
        break;
        case 'popupScheduleDetailFileManagement':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/schedulesPopupAppointmentFileManagementByHistory.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleDetailFileManagement = results;
          $scope.showTarget('#popupScheduleDetailFileManagement');
          $ionicLoading.hide();
        });
        break;
        case 'popupFileViewerSchedule':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/schedulesPopupFileViewerSchedule.tpl').success(function(results) {
          $scope.dataAppHtml.popupFileViewerSchedule = results;
          $scope.showTarget('#popupFileViewerSchedule');
          $ionicLoading.hide();
          if($callback != null){
            return $callback();
          }
        });
        break;
        case 'optionFileDetailSchedule':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/schedulesOptionFileDetailSchedule.tpl').success(function(results) {
          $scope.dataAppHtml.optionFileDetailSchedule = results;
          $scope.showTarget('#optionFileDetailSchedule');
          $ionicLoading.hide();
        });
        break;
        case 'popupScheduleDetailJobStatus':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentDetailsJobStatusmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleDetailJobStatus = results;
          $scope.showTarget('#popupScheduleDetailJobStatus');
          $ionicLoading.hide();
        });
        break;
        case 'popupScheduleDetailJobSites':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentDetailsJobSitesmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleDetailJobSites = results;
          $scope.showTarget('#popupScheduleDetailJobSites');
          $ionicLoading.hide();
        });
        break;
        case 'popupScheduleDetailHistories':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentDetailsHistoriesmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleDetailHistories = results;
          $scope.showTarget('#popupScheduleDetailHistories');
          $ionicLoading.hide();
        });
        break;
        case 'customerDetailPopupAppointmentHistoryViewLog':
        dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailPopupAppointmentHistoryViewLogmodal.tpl').success(function(results) {
          $scope.dataAppHtml.customerDetailPopupAppointmentHistoryViewLog = results;
          $scope.showTarget('#customerDetailPopupAppointmentHistoryViewLog');
          $ionicLoading.hide();
        });
        break;
        case 'popupScheduleDetailDowntime':
        dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupDowntimemodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleDetailDowntime = results;
          $scope.showTarget('#popupScheduleDetailDowntime');
          $timeout(function() {
            $scope.resizeScroll('scrollDowntimeList');
          }, 1)
        });
        break;
        case 'popupAddScheduleDetailDowntime':
        dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupDowntimeTaskAddmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupAddScheduleDetailDowntime = results;
          $scope.showTarget('#popupAddScheduleDetailDowntime');
          $ionicLoading.hide();
        });
        break;
        case 'appointmentFileManagementByHistory':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/schedulesPopupAppointmentFileManagementByHistory.tpl').success(function(results) {
          $scope.dataAppHtml.appointmentFileManagementByHistory = results;
          $scope.showTarget('#appointmentFileManagementByHistory');
          $ionicLoading.hide();
        });
        break;
        case 'appointmentFileManagement':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentFileManagermentmodal.tpl').success(function(results) {
          $scope.dataAppHtml.appointmentFileManagement = results;
          dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentFileManagermentSortmodal.tpl').success(function(results) {
            $scope.dataAppHtml.popupAppointmentFileManagementSort = results;
          })
          dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentFileManagermentAddFilemodal.tpl').success(function(results) {
            $scope.dataAppHtml.popupAppointmentAddFile = results;
          })
          $timeout(function() {
            $scope.showTarget('#appointmentFileManagement');
            $ionicScrollDelegate.$getByHandle("scrollAppointmentFileManagement").scrollTop(true);
            $ionicLoading.hide();
          }, 500)
        })
        break;
        case 'schedulesPopupViewMessLogmodal':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/schedulesPopupViewMessLogmodal.tpl').success(function(results) {
          $scope.dataAppHtml.schedulesPopupViewMessLogmodal = results;
          $scope.showTarget('#schedulesPopupViewMessLogmodal');
          $ionicLoading.hide();
        });
        break;
        case 'optionScheduleEstimateInvoiceManagerment':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/scheduleEstimateInvoiceManagerment.tpl').success(function(results) {
          $scope.dataAppHtml.optionScheduleEstimateInvoiceManagerment = results;
          $scope.showTarget('#optionScheduleEstimateInvoiceManagerment');
          $ionicLoading.hide();
        });
        break;
        case 'popupPendingToEnroutemodal':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupPendingToEnroutemodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupPendingToEnroutemodal = results;
          $scope.showTarget('#popupPendingToEnroutemodal');
          $ionicLoading.hide();
        });
        break;
        case 'popupEnrouteToArivemodal':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupEnrouteToArivemodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupEnrouteToArivemodal = results;
          $scope.showTarget('#popupEnrouteToArivemodal');
          $ionicLoading.hide();
        });
        break;
        case 'popupAriveToWorkingmodal':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAriveToWorkingmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupAriveToWorkingmodal = results;
          $scope.showTarget('#popupAriveToWorkingmodal');
          $ionicLoading.hide();
        });
        break;
        case 'popupRemindersmodal':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupRemindersmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupRemindersmodal = results;
          $scope.showTarget('#popupRemindersmodal');
          $ionicLoading.hide();
        });
        break;
        case 'popupWorkingToFinishmodal':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupWorkingToFinishmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupWorkingToFinishmodal = results;
          $scope.showTarget('#popupWorkingToFinishmodal');
          $ionicLoading.hide();
        });
        break;
        case 'popupPendingToEnrouteCAmodal':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupPendingToEnrouteCAmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupPendingToEnrouteCAmodal = results;
          $scope.showTarget('#popupPendingToEnrouteCAmodal');
          $ionicLoading.hide();
        });
        break;
        case 'popupRetrySentMessegemodal':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupRetrySentMessegemodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupRetrySentMessegemodal = results;
          $scope.showTarget('#popupRetrySentMessegemodal');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailCustomerFlagNote':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailCustomerFlagNote.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailCustomerFlagNote = results;
          $scope.showTarget('#popupAppointmentDetailCustomerFlagNote');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailCustomerAddFlagNote':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailCustomerAddFlagNote.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailCustomerAddFlagNote = results;
          $scope.showTarget('#popupAppointmentDetailCustomerAddFlagNote');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailAddress':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailAddress.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailAddress = results;
          $scope.showTarget('#popupAppointmentDetailAddress');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailOrderOption':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailOrderOption.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailOrderOption = results;
          $scope.showTarget('#popupAppointmentDetailOrderOption');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailOrderHistory':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailOrderHistory.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailOrderHistory = results;
          $scope.showTarget('#popupAppointmentDetailOrderHistory');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailPhone':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailPhone.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailPhone = results;
          $scope.showTarget('#popupAppointmentDetailPhone');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailEmail':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailEmail.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailEmail = results;
          $scope.showTarget('#popupAppointmentDetailEmail');
          $timeout(function(val) {
            $('#inputagarea input').attr('readonly', 'readonly');
          }, 10);
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailZillow':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailZillow.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailZillow = results;
          $scope.showTarget('#popupAppointmentDetailZillow');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailReplaceAddressConfirm':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailReplaceAddressConfirm.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailReplaceAddressConfirm = results;
          $scope.showTarget('#popupAppointmentDetailReplaceAddressConfirm');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailRevertAppointmentConfirm':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailRevertAppointmentConfirm.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailRevertAppointmentConfirm = results;
          $scope.showTarget('#popupAppointmentDetailRevertAppointmentConfirm');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailJobStatusChat':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailJobStatusChat.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailJobStatusChat = results;
          $scope.showTarget('#popupAppointmentDetailJobStatusChat');
          $ionicLoading.hide();
        });
        break;
        case 'photoViewer':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/photoViewer.tpl').success(function(results) {
          $scope.dataAppHtml.photoViewer = results;
          $scope.showTarget('#photoViewer');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailTakePictureOption':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentDetailTakePictureOption.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailTakePictureOption = results;
          $scope.showTarget('#popupAppointmentDetailTakePictureOption');
          $ionicLoading.hide();
        });
        break;
        case 'pdfViewer':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/pdfViewer.tpl').success(function(results) {
          $scope.dataAppHtml.pdfViewer = results;
          $scope.showTarget('#pdfViewer');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentDetailAddEditWorkingInvoice':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/schedulesPopupAddEditWorkingInvoicemodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentDetailAddEditWorkingInvoice = results;
          $scope.showTarget('#popupAppointmentDetailAddEditWorkingInvoice');
          $ionicLoading.hide();
        });
        break;
        case 'schedulesPopupConfirmDeleteFlagNote':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/schedulesPopupConfirmDeleteFlagNote.tpl').success(function(results) {
          $scope.dataAppHtml.schedulesPopupConfirmDeleteFlagNote = results;
          $scope.showTarget('#schedulesPopupConfirmDeleteFlagNote');
          $ionicLoading.hide();
        });
        break;
        case 'popupConfirmAddWorkingInvoice':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupConfirmAddWorkingInvoice.tpl').success(function(results) {
          $scope.dataAppHtml.popupConfirmAddWorkingInvoice = results;
          $scope.showTarget('#popupConfirmAddWorkingInvoice');
          $ionicLoading.hide();
        });
        break;
        case 'popupScheduleDetailFileManagementName':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupScheduleDetailFileManagementName.tpl').success(function(results) {
          $scope.dataAppHtml.popupScheduleDetailFileManagementName = results;
          $scope.showTarget('#popupScheduleDetailFileManagementName');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentAddUrl':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAppointmentAddUrl.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentAddUrl = results;
          $scope.showTarget('#popupAppointmentAddUrl');
          $ionicLoading.hide();
        });
        break;
        case 'popupAppointmentUrl':
        dataHtml.getTemplate('templates/dashboard/schedules/appointment/schedulesPopupAppointmentUrl.tpl').success(function(results) {
          $scope.dataAppHtml.popupAppointmentUrl = results;
          $scope.showTarget('#popupAppointmentUrl');
          $ionicLoading.hide();
        });
        break;
        case 'popupNoteTaskLog':
        dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupNoteTaskLogmodal.tpl').success(function(results) {
          $scope.dataAppHtml.popupNoteTaskLog = results;
          $scope.showTarget('#popupNoteTaskLog');
          $ionicLoading.hide();
        });
        break;
      }
    }, 500);
}
$scope.openScheduleAppointmentMoveTo = function(id) {
    //Template scheduleContentAppointmentMoveTo dang viet tam trong schedule, vui long tach ra khi lam, please
    $scope.showTarget('#scheduleContentAppointmentMoveTo');
    console.log(id);
  }
  $scope.openPopupAddFile = function(appointment_id) {
    $scope.openByGetTemplate('popupAddScheduleDetailFileManagementDetail');
  }
  $scope.loadCriteria = function() {
    Appointments.getCriteria().success(function(data) {
      var criterias = _.indexBy(data, 'name');
      $scope.criteria1 = criterias['Criteria#1'].contents.split(';');
      $scope.criteria2 = criterias['Criteria#2'].contents.split(';');
      $scope.criteria3 = criterias['Criteria#3'].contents.split(';');
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.viewAppnote = function(dataOfficeNote, dataFieldWorkerNote, type) {
    $scope.noteViewMode = type;
    $ionicLoading.show({
      template: templateLoading
    });
    $scope.openByGetTemplate('customerDetailPopupAppointmentHistoryViewLog');
    $timeout(function(val) {
      $scope.dataViewAppNote.office = dataOfficeNote;
      $scope.dataViewAppNote.fieldworker = dataFieldWorkerNote;
      $ionicLoading.hide();
    }, 10);
  }
  $scope.setValueForInput = function(value, arrData) {
    var index = _.findLastIndex(arrData, {
      id: value
    });
    if (index >= 0) return arrData[index];
  }
  $scope.setValueShowSelect = function(getFrom, setTo, type) {
    var valText = $('#' + getFrom + ' option:selected').text();
    var valueData = $('#' + getFrom + ' option:selected').val();
    $('input[name=' + setTo + ']').val(valText);
    switch (type) {
      case 'jobsiteEdit':
      valueData == 'Select' ? valueData = '' : valueData;
      $scope.changeJobsiteEdit(valueData);
      break;
      case 'jobsites':
      valueData == 'Select' ? valueData = '' : valueData
      $scope.changeJobsite(valueData);
      break;
    }
    //$scope.resizeScroll('scrollAppointmentEditAppToSchedule');
  }
  $scope.setValueFlag = function(value) {
    $scope.Input_value.flag = "";
    $scope.Input_value.flag_color = "";
    if (value != null && value != '' && value != undefined) {
      var flag = $scope.setValueForInput(value, $scope.flags);
      if (flag != undefined) {
        $scope.Input_value.flag = flag.name;
      }
      $scope.Input_value.flag_color = _.where($scope.flags, {
        id: value
      })[0].color;
    }
  }
  $scope.setValueAppointmentType = function(value) {
    $scope.Input_value.appointmentType = "";
    if (value != null && value != '' && value != undefined) {
      var appointmentType = $scope.setValueForInput(value, $scope.allAppointmentTypesData);
      if (appointmentType != undefined) {
        $scope.Input_value.appointmentType = appointmentType.name;
      }
    }
  }
  $scope.setValuecustomerType = function(value) {
    $scope.Input_value.customerType = "";
    if (value != null && value != '' && value != undefined) {
      var customerType = $scope.setValueForInput(value, $scope.detailAppointmentData._customertypess);
      if (customerType != undefined) {
        $scope.Input_value.customerType = customerType.name;
      }
    }
  }
  $scope.setValueFlexible = function(value) {
    $scope.Input_value.flexible = "";
    if (value != null && value != '' && value != undefined) {
      var flexible = $scope.setValueForInput(value, $scope.detailAppointmentData._flexiblecustomerss);
      if (flexible != undefined) {
        $scope.Input_value.flexible = flexible.name;
      }
    }
  }
  $scope.setValueCallAhead = function(value) {
    $scope.Input_value.callAhead = "";
    if (value != null && value != '' && value != undefined) {
      var callAhead = $scope.setValueForInput(value, $scope.detailAppointmentData._callaheadss);
      if (callAhead != undefined) {
        $scope.Input_value.callAhead = callAhead.name;
      }
    }
  }
  $scope.setValueFieldWorker = function(value) {
    $scope.Input_value.fieldWorker = "";
    if (value != null && value != '' && value != undefined && value > 0) {
      var fieldWorker = $scope.setValueForInput(value, $scope.fieldWorkerByAppGroupList);
      if (fieldWorker != undefined) {
        $scope.Input_value.fieldWorker = fieldWorker.name;
      }
    }
  }
  $scope.setValuePrefFieldWorker = function(value) {
    $scope.Input_value.prefFieldWorker = "";
    if (value != null && value != '' && value != undefined) {
      var prefFieldWorker = $scope.setValueForInput(value, $scope.fieldWorkerByAppGroupList);
      if (prefFieldWorker != undefined) {
        $scope.Input_value.prefFieldWorker = prefFieldWorker.name;
      }
    }
  }
  $scope.clearSearch = function() {
    $scope.search.Text = '';
  }
  $scope.getAppointmentgroups = function() {
    if (!$scope.loadone) {
      $ionicLoading.show({
        template: templateLoading
      })
      Appointmentgroups.getSelect().success(function(data) {
        if (!startpage) $ionicLoading.hide();
        $scope.appointmentgroups = data;
        $scope.getCallaheads();
        $scope.loadone = true;
      }).error(function(data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
      });
    }
  }
  $scope.checkappointment_id = function(appointment_id) {
    Appointments.checkappointment_id(appointment_id).success(function(data) {
      $scope.selectedDay = data.dateofappt;
    });
  }
  $scope.getSelectListviews = function() {
    $ionicLoading.show({
      template: templateLoading
    })
    Listviews.getSelect().success(function(data) {
      if (!startpage) ionicLoading.hide();
      var view_all = {
        id: 0,
        name: "View All"
      };
      data.unshift(view_all);
      $scope.selectListviews = data;
      $scope.loadTreeDepart();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.autocompleteJobsiteAddress = function(input, addressFieldID, formID) {
    var selector = input + addressFieldID.toString().trim();
    var addressAddEmployeee;
    var componentAddressForm = {
      locality: 'long_name',
      administrative_area_level_1: 'short_name',
      postal_code: 'short_name'
    };
    var form = document.getElementById(formID);
    initAddressAddEmployeee();
    document.getElementById(selector).onfocus = geolocateAddressAddEmployeee();

    function initAddressAddEmployeee() {
      addressAddEmployeee = new google.maps.places.Autocomplete(
        (document.getElementById(selector)), {
          types: ['geocode']
        });
      addressAddEmployeee.addListener('place_changed', fillInAddressAddEmployeee);
    }

    function fillInAddressAddEmployeee() {
      var place = addressAddEmployeee.getPlace();
      for (var component in componentAddressForm) {
        $('#' + selector).parent().parent().parent().find('.' + component)[0].value = '';
        $('#' + selector).parent().parent().parent().find('.' + component)[0].disabled = false;
      }
      for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentAddressForm[addressType]) {
          var val = place.address_components[i][componentAddressForm[addressType]];
          $('#' + selector).parent().parent().parent().find('.' + addressType)[0].value = val;
          $('#' + selector).parent().parent().parent().find('.' + addressType).trigger('input');
        }
      }
      $('#' + selector).trigger('input');
    }

    function geolocateAddressAddEmployeee() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          var circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy
          });
          addressAddEmployeee.setBounds(circle.getBounds());
        });
      }
    }
  }
  $scope.addRowJobsiteCreate = function() {
    if (!$scope.addAppointmentsData.jobsites) {
      $scope.addAppointmentsData.jobsites = [];
    }
    $scope.addAppointmentsData.jobsites.push({
      customer_id: Customers.getCustomerId(),
      label: '',
      street: '',
      city: '',
      state: '',
      zipcode: '',
      contactperson: '',
      contactphone: '',
      time: new Date(),
    });
  }
  $scope.addRowJobsiteEdit = function() {
    if ($scope.editAppointmentsData.dataJobsite.length < 1) {
      $scope.editAppointmentsData.dataJobsite.push({
        customer_id: $scope.editAppointmentsData.dataApp.customer_id,
        label: '',
        street: '',
        city: '',
        state: '',
        zipcode: '',
        contactperson: '',
        contactphone: '',
        time: new Date(),
      });
    }
  }
  $scope.changeJobsite = function(val) {
    if (val != '') {
      if (val > 0) {
        $scope.jobsiteById(val);
        $scope.jobsiteshow = true;
        $scope.editJobsiteField = true;
      } else {
        $scope.holdValueAddress.addAppointment = [];
        $scope.jobsiteshow = true;
        $scope.editJobsiteField = false;
        $scope.addAppointmentsData.jobsites = {};
        $scope.addAppointmentsData.jobsites.id = 'addnew';
        $scope.addAppointmentsData.jobsites.customer_id = Customers.getCustomerId();
      }
    } else {
      $scope.addAppointmentsData.jobsites = [];
      $scope.jobsiteshow = false;
      $scope.editJobsiteField = false;
    }
  }
  $scope.changeJobsiteEdit = function(val) {
    if (val != '') {
      if (val > 0) {
        $scope.jobsiteByIdEdit(val);
        $scope.jobsiteshow = true;
        $scope.editJobsiteField = true;
      } else {
        $scope.holdValueAddress.editAppointment = [];
        $scope.jobsiteshow = true;
        $scope.editJobsiteField = false;
        $scope.editAppointmentsData.dataJobsite = {};
        $scope.editAppointmentsData.dataJobsite.id = 'addnew';
        $scope.editAppointmentsData.dataJobsite.customer_id = Customers.getCustomerId();
      }
    } else {
      $scope.jobsiteshow = false;
      $scope.editJobsiteField = false;
      $scope.editAppointmentsData.dataJobsite = {};
    }
  }
  $scope.jobsiteById = function(id) {
    Customers.jobsiteById(id).success(function(data) {
      $scope.addAppointmentsData.jobsites = data;
    });
  }
  $scope.jobsiteByIdEdit = function(id) {
    Customers.jobsiteById(id).success(function(data) {
      $scope.editAppointmentsData.dataJobsite = data;
    });
  }
  $scope.removeItemJobsiteCreate = function(index) {
    $scope.addAppointmentsData.jobsites.splice(index, 1);
  }
  $scope.removeItemJobsiteEdit = function(index) {
    $scope.editAppointmentsData.dataJobsite.splice(index, 1);
  }
  $scope.getCustomers = function() {
    Customers.getSelect().success(function(data) {
      $scope.customers = data;
    });
  }
  $scope.getCallaheads = function() {
    $ionicLoading.show({
      template: templateLoading
    })
    Callaheads.getSelect().success(function(data) {
      if (!startpage) $ionicLoading.hide();
      $scope.callaheads = data;
      $scope.addAppointmentsData.callahead_id = NoCAId.toString();
      $scope.getCustomertypes();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.getCustomertypes = function() {
    $ionicLoading.show({
      template: templateLoading
    })
    Customertypes.getSelect().success(function(data) {
      if (!startpage) $ionicLoading.hide();
      $scope.customertypes = data;
      $scope.getFlexiblecustomers();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.getFlexiblecustomers = function() {
    $ionicLoading.show({
      template: templateLoading
    })
    Flexiblecustomers.getSelect().success(function(data) {
      if (!startpage) $ionicLoading.hide();
      $scope.flexiblecustomers = data;
      $scope.getAddbies();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.getAddbies = function() {
    $ionicLoading.show({
      template: templateLoading
    })
    Users.getSelect().success(function(data) {
      if (!startpage) $ionicLoading.hide();
      $scope.users = data;
      $scope.currentuserId = currentIdLogin;
      //for app
      var curr = _.where($scope.users, {
        id: parseInt(currentIdLogin)
      });
      $scope.currAddbyShow = curr[0].first_name + ' ' + curr[0].last_name;
      //for app
      if (page == "scheduleapp.html") scope.getLeadSource();
      $scope.getSelectFieldworker();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.getSelectFieldworker = function() {
    $ionicLoading.show({
      template: templateLoading
    })
    Users.getSelectFieldworker().success(function(data) {
      if (!startpage) $ionicLoading.hide();
      $scope.fieldworkerSelect = data;
      $scope.refreshAppointmentType('');
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.getfieldworkerByAppType = function(appTypeId) {
    if (appTypeId.id != undefined) {
      appTypeId = appTypeId.id;
    }
    Users.getfieldworkerByAppType(appTypeId).success(function(data) {
      $scope.fieldworkerByAppType = data.data;
    });
  }
  $scope.fieldWorker = function(id) {
    var appgroup = _.find($scope.appointmentgroups, function(item) {
      return item.id == id;
    });
    if (appgroup) {
      Appointmentgroups.getUserByAppGroupId(appgroup.parent_id).success(function(data) {
        var userSerect = _.find(data, {
          'id': $scope.userSerectId
        });
        $scope.serectPos = _.indexOf(data, userSerect);
        $scope.appgroupusers = [];
        $scope.appgroupusers.push(userSerect);
        _.map(data, function(val, key) {
          if (key != $scope.serectPos) {
            $scope.appgroupusers.push(val);
          }
        });
        $scope.appgroupusers.push({
          id: '',
          name: 'Blank for Unscheduled'
        });
        $('input[name=seletedFieldwokerName]').val(userSerect.name);
        $scope.addAppointmentsData.fieldworker = userSerect.id;
      });
    }
  }
  $scope.getAppointments = function() {
    $('.loader').show();
    Appointments.getPaging($scope.searchAppointments).success(function(data) {
      $scope.appointments = data.data;
      $('.loader').hide();
      $scope.currentPage = data.page;
      $scope.itemsPerPage = $scope.searchAppointments.rows;
      appointments_pagesize.val($scope.itemsPerPage);
      $scope.totalItems = data.total_rows;
      $('#tableAppointments').tableRespondsive();
    });
  };
  $scope.getListToSchedule = function() {
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.getListToSchedule({
      arrDepart: $scope.arrDepart
    }).success(function(data) {
      if (!startpage) ionicLoading.hide();
      $scope.listToSchedule = data.data;
      $scope.listToSchedule = _.each($scope.listToSchedule, function(value) {
        var timeArr = value.timewindow.split(':');
        var date = new Date().setHours(timeArr[0], timeArr[1], timeArr[2])
        value.timeformat = moment(date).format("h:mm A");
      });
      $scope.listToScheduleCount = data.count;
      if (!$scope.loadListAppointment) {
        $scope.listDepartment = data.listDepartment;
        $scope.loadListAppointment = true;
      }
      angular.forEach($scope.listDepartment, function(item) {
        item.count = 0;
      })
      $scope.loadAppointmentByDay(moment().format('YYYY-MM-DD'));
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  };
  $scope.getDataHoverAppCell = function(id) {
    Appointments.getDataHoverAppCell(id).success(function(data) {
      $scope.dataAppCellHover = data;
    });
  };
  $scope.searchChanged = function() {
    $scope.getAppointments();
  }
  $scope.list_field_worker = [];
  $scope.loadAppointmentByDay = function(day, type) {
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.getAppoinmentByDay({
      defaultlistview: $scope.defaultlistview,
      user_id: $scope.currentuserId,
      day: day,
      listviewid: $scope.listviewId.value,
      unavailablefieldwoker: $scope.viewUnavailableValue,
      arrDepart: $scope.arrDepart
    }).success(function(data) {
      if ($scope.loadAppByListView) {
        $scope.closeTarget('#popupScheduleListView');
        $scope.closeTarget('#popupScheduleFilter');
      }
      $scope.loadAppByListView = false;
      $scope.setTime = true;
      $ionicScrollDelegate.$getByHandle('scrollSchedulesContent').scrollTop();
      $ionicScrollDelegate.$getByHandle('scrollSchedulesContent').resize();
      if (!startpage) ionicLoading.hide();
      $scope.defaultlistview = 0;
      if (data.listviewdata != '') {
        $scope.listviewId.value = data.listviewdata.id;
      }
      $scope.numberOldApp = parseInt(data.countApp);
      $scope.numberOldTask = parseInt(data.countTask);
      $scope.list_field_worker = data.fieldworker;
      var arrRSC = [];
      var arrEvt = [];
      var list_field_worker = [];
      for (var i = 0; i < data.fieldworker.length; i++) {
        data.fieldworker[i].app = _.sortBy(_.sortBy(data.fieldworker[i].app, 'endarrivalwindow'), 'arrivalwindow');
        $scope.list_field_worker[i].appHtml = '';
        $scope.list_field_worker[i].appHtmlInDetail = '';
        var itemFieldWorkerData = data.fieldworker[i];

        var appAndTaskArr = [];
        _.each(itemFieldWorkerData.app, function(value) {
          value.startime_sort = value.arrivalwindow;
          value.endtime_sort = value.endarrivalwindow;
          value.type = 'app';
          appAndTaskArr.push(value);
        });
        _.each(itemFieldWorkerData.task, function(value) {
          value.startime_sort = value.from_time;
          value.endtime_sort = value.to_time;
          value.type = 'task';
          appAndTaskArr.push(value);
        });
        appAndTaskArr = _.sortBy(_.sortBy(appAndTaskArr, 'endtime_sort'), 'startime_sort');

        if (_.indexOf(list_field_worker, itemFieldWorkerData.fieldworkerId) == -1) {
          list_field_worker.push(itemFieldWorkerData.fieldworkerId);
        } else {
          continue;
        }
        var calTime = 0;
        if (itemFieldWorkerData.inouttime.sumduration > 0) {
          calTime = itemFieldWorkerData.inouttime.sumduration + ' / ' + itemFieldWorkerData.inouttime.numberOfDay + ' = ' + itemFieldWorkerData.inouttime.avgDay
        }
        var fieldworker = {};
        var cellPhoneFormat = itemFieldWorkerData.cellPhone.replace(" ", "").replace("(", "").replace(")", "").replace("-", "");
        var arrow = '<i class="icon"><svg class="h15px" viewBox="0 0 47.255 47.255"> <g> <path d="M12.314,47.255c-0.256,0-0.512-0.098-0.707-0.293c-0.391-0.391-0.391-1.023,0-1.414l21.92-21.92l-21.92-21.92   c-0.391-0.391-0.391-1.023,0-1.414s1.023-0.391,1.414,0L35.648,22.92c0.391,0.391,0.391,1.023,0,1.414L13.021,46.962   C12.825,47.157,12.57,47.255,12.314,47.255z" fill="#01518E"/> </g> </svg></i>';
        if ($scope.roleName == $scope.isWarehouse) {
          arrow = '';
        }
        fieldworker = {
          id: itemFieldWorkerData.fieldworkerId,
          title: '<div class="person-cell">' + '<div class="name">' + itemFieldWorkerData.first_name + ' ' + itemFieldWorkerData.last_name + '</div>' + '<div class="more-option clear">' + '<div class="fnc-buttons left">' + '<a class="mgR10" href="#" onClick="callphonenumber(this)"  phone-number="' + cellPhoneFormat + '"><button class="button-field-1 white w22px h22px"> <svg class="h16px mgB1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"> <g> <path d="M256,0C114.844,0,0,114.844,0,256s114.844,256,256,256c23.188,0,46.156-3.094,70.469-10   c49.25-21.781,76.125-75.531,64.219-127.969l0.5-0.5c7.5-7.469,10.875-21.875,7.531-31.938l-1.438-4.375   c-3.375-10.062-14.5-20.562-24.75-23.375L334.688,303.5c-10.25-2.781-24.875,0.969-32.405,8.5l-13.688,13.688   c-49.75-13.469-88.781-52.5-102.219-102.25l13.688-13.688c7.5-7.5,11.25-22.125,8.469-32.406L198.219,139.5   c-2.781-10.25-13.344-21.375-23.406-24.75l-4.313-1.438c-10.094-3.375-24.5,0.031-32,7.563l-20.5,20.5   c-3.656,3.625-6,14.031-6,14.063c-0.688,65.063,24.813,127.719,70.813,173.75c45.875,45.875,108.313,71.345,173.156,70.781   c0.156,0,2.531-0.531,5.344-1.375c0.188,31.469-17.655,60.875-45.562,73.344C296.406,477.281,276.312,480,256,480   C132.5,480,32,379.5,32,256S132.5,32,256,32s224,100.5,224,224c0,36.812-8.75,72.031-26.031,104.625   c-4.125,7.812-1.125,17.5,6.656,21.625c7.844,4.188,17.5,1.156,21.625-6.625C501.719,338.875,512,297.5,512,256   C512,114.844,397.156,0,256,0z" fill="#0f8fa2"/> </g> </svg> </button></a>' + '<a class="mgR5" ng-click="openchat(' + itemFieldWorkerData.fieldworkerId + ')" target="_blank"><button class="button-field-1 white w22px h22px"> <svg class="h14px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 60.731 60.73" style="enable-background:new 0 0 60.731 60.73;" xml:space="preserve"> <g> <g> <path d="M14.882,0.77v16.388H0v30.109h6.693v12.694l11.31-12.694h21.579V35.561h0.405l12.937,14.517V35.561h7.808V0.77H14.882z     M58.482,33.307h-7.811v10.862l-9.681-10.862h-23.86V3.016h41.351V33.307z" fill="#0F8FA2"/> </g> </g> </svg> </button></a>' + '<h5 class="more-action inlineb relative">' + arrow + '<ul class="punch-area option-pop-1 pd5 rounded-10">' + '<li class="baseline">' + '<div class="label-1">' + '<div class="">Punch in: </div>' + '<div class="' + itemFieldWorkerData.pipus.typeClass + ' text-right">' + itemFieldWorkerData.pipus.time + '</div>' + '</div>' + '</li>' + '<li class="baseline mgT5">' + '<div class="label-1">' + '<div class="">Time worked: </div>' + '<div class="ft-number clr-black text-right">' + calTime + '</div>' + '</div>' + '</li>' + '<li class="baseline mgT5">' + '<div class="label-1">' + '<a class="link-1" onclick="addTaskDownTime(' + itemFieldWorkerData.fieldworkerId + ')" modal-open="#popupappointmentDowntime" >Downtime</a>' + '</div>' + '</li>' + '</ul>' + '</h5>' + '</div>' + '<div class="punch-time right"><b class="' + itemFieldWorkerData.pipus.typeClass + '">' + itemFieldWorkerData.pipus.time + '</b></div>' + '</div>' + '</div>',
        }
        arrRSC.push(fieldworker);
        for (var j = 0; j < appAndTaskArr.length; j++) {
          var item = appAndTaskArr[j];
          if (item.type == 'app') {
            var list_appointment_status_id = [];
            var _id = appAndTaskArr[j];
            if (_.indexOf(list_appointment_status_id, _id.id) == -1) {
              list_appointment_status_id.push(_id.id);
            } else {
              continue;
            }
            var list_status = _.where(itemFieldWorkerData.app, {
              id: _id.id
            });
            var countAppointmentStatus;
            if ($scope.tier.elastic) {
              appAndTaskArr[j].count_appointment_status == 0 ? appAndTaskArr[j].count_appointment_status = 1 : '';
              var countAppointmentStatus = appAndTaskArr[j].count_appointment_status;
            } else {
              var countAppointmentStatus = list_status.length;
            }
            if (countAppointmentStatus == 1) {
              var dataApp = list_status[0];
              var city = ''
              if (dataApp.jsCity != undefined && dataApp.jsCity.length > 0) {
                city = dataApp.jsCity + '-';
              } else {
                city = dataApp.ctCity + '-';
              }
              if (dataApp.nothomeutil != "00:00:00") {
                var timeArr = dataApp.nothomeutil.split(':');
                var date = new Date().setHours(timeArr[0], timeArr[1], timeArr[2])
                var timeformat = '-' + moment(date).format("h:mm A");
              } else {
                var timeformat = '';
              }
              var timeStart = dataApp.startimeShow.split(':');
              var date = new Date().setHours(timeStart[0], timeStart[1], timeStart[2])
              var timeStartFormat = moment(date).format("h:mm A");
              var timeEnd = dataApp.endtimeShow.split(':');
              var date = new Date().setHours(timeEnd[0], timeEnd[1], timeEnd[2])
              var timeEndFormat = moment(date).format("h:mm A");
              //console.log($scope.selectedDay + dataApp.startime+'//////');
              if (parseInt(dataApp.is_cancel)) {
                $scope.appStatusColor = appStatusColor;
                var evt = {
                  id: dataApp.id,
                  appointmentgroupsId: dataApp.appointmentgroup_id,
                  resourceId: itemFieldWorkerData.fieldworkerId,
                  start: $scope.selectedDay + dataApp.startime,
                  end: $scope.selectedDay + dataApp.endtime,
                  title: '<div class="mgT15" on-hold="openScheduleAppointmentMoveTo(\'' + dataApp.id + '\')"> <div class="layout-fixed" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="w50px v-top-i pdT5"> <div class="jobstatus-cell" style="background: ' + $scope.appStatusColor + '"></div> </div> <div class="v-top-i"> <div class="layout-fixed w-auto-i text-date-1"> <div>' + $scope.displayTime(timeStartFormat, false) + '</div> <div class="w16px text-center pdB2"> <svg class="h6px" viewBox="0 0 14 14"> <g> <g> <path fill="#b1c7d7" d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" /> </g> </g> </svg> </div> <div>' + $scope.displayTime(timeEndFormat, false) + '</div> </div> <div class="text"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> </div> <div class="w30px clear"> <button type="button" class="app-item-next-icon bg-transparent pd0-i right"> </button> </div> </div> </div>',
                  titleInDetail: '<li class="mgB10" ng-click="resizeScroll(\'scrollSchedulesContentDetail\')"> <div class="layout-fixed"> <div class="tasknote-cell" style="background: ' + $scope.appStatusColor + '"></div> <div> <div class="time" ng-click="changeTimeRangeSchedule($event)"> <div class="bar-area"></div> <div class="mark-start"> <i></i><span class="text-date-1 lowercase pdL10">' + $scope.displayTime(timeStartFormat, false) + '</span> </div> <div class="mark-end"> <i></i><span class="text-date-1 lowercase pdR10">' + $scope.displayTime(timeEndFormat, false) + '</span> </div> </div>                                    <div class="time-change"><input type="text" data-appt-id="' + dataApp.id + '" data-time-start="' + timeStartFormat + '" data-time-end="' + timeEndFormat + '" /><div class="control layout-fixed mgT20"> <div class="range-text"> <div class="layout-fixed w-auto-i text-title-4 clr-black"> <div class="label-time-start-change"></div> <div class="w16px text-center pdB2"> <svg viewBox="0 0 14 14" class="h6px clr-symbol"> <g> <g> <path d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" fill="#b1c7d7" /> </g> </g> </svg> </div> <div class="label-time-end-change"></div> </div> </div> <div class="clear"> <div class="layout-fixed w-auto-i right"> <div class="pdR20"> <button class="btn-update-range bg-transparent biger-3-time" type="button" ng-click="updateTimeRangeSchedule($event,\'app\')"> <svg viewBox="0 0 511.999 511.999" class="h20px clr-symbol-clickable"> <path d="M506.231,75.508c-7.689-7.69-20.158-7.69-27.849,0l-319.21,319.211L33.617,269.163c-7.689-7.691-20.158-7.691-27.849,0    c-7.69,7.69-7.69,20.158,0,27.849l139.481,139.481c7.687,7.687,20.16,7.689,27.849,0l333.133-333.136    C513.921,95.666,513.921,83.198,506.231,75.508z"/> </svg> </button> </div> <div> <button class="btn-close-range bg-transparent biger-3-time" type="button" ng-click="closeTimeRangeSchedule($event)"> <svg class="h17px clr-symbol-clickable" viewBox="0 0 512.001 512.001"> <path d="M505.922,476.567L285.355,256L505.92,35.435c8.106-8.105,8.106-21.248,0-29.354c-8.105-8.106-21.248-8.106-29.354,0    L256.001,226.646L35.434,6.081c-8.105-8.106-21.248-8.106-29.354,0c-8.106,8.105-8.106,21.248,0,29.354L226.646,256L6.08,476.567    c-8.106,8.106-8.106,21.248,0,29.354c8.105,8.105,21.248,8.106,29.354,0l220.567-220.567l220.567,220.567    c8.105,8.105,21.248,8.106,29.354,0S514.028,484.673,505.922,476.567z"/> </svg> </button> </div> </div> </div> </div></div>                                      <div class="schedule-content layout-fixed pdTB5 pdLR10" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="text-content"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> <div class="w50px clear"> <button class="app-item-next-icon bg-transparent pd0-i right" type="button"> </button> </div> </div> </div> </div> </li>'
                }
              } else {
                $scope.appStatusColor = dataApp.status == 'EnRoute' && dataApp.callahead_name != $scope.NoCaText ? $scope.differentNoCaAndRouteColor : dataApp.statusesColor;
                var evt = {
                  id: dataApp.id,
                  appointmentgroupsId: dataApp.appointmentgroup_id,
                  resourceId: itemFieldWorkerData.fieldworkerId,
                  start: $scope.selectedDay + dataApp.startime,
                  end: $scope.selectedDay + dataApp.endtime,
                  title: '<div class="mgT15" on-hold="openScheduleAppointmentMoveTo(\'' + dataApp.id + '\')"><div class="layout-fixed" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="w50px v-top-i pdT5"> <div class="appoinment-cell" style="border-color: ' + dataApp.appgroupColor + '"> <div class="bar" style="background: ' + dataApp.customertypesColor + '"></div> <div class="light" style="background: ' + dataApp.flexibleColor + '"></div> </div> </div> <div class="v-top-i"> <div class="layout-fixed w-auto-i text-date-1"> <div>' + $scope.displayTime(timeStartFormat, false) + '</div> <div class="w16px text-center pdB2"> <svg class="h6px" viewBox="0 0 14 14"> <g> <g> <path fill="#b1c7d7" d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" /> </g> </g> </svg> </div> <div>' + $scope.displayTime(timeEndFormat, false) + '</div> </div> <div class="text"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> </div> <div class="w30px clear"> <button type="button" class="app-item-next-icon bg-transparent pd0-i right"> </button> </div> </div> </div>',
                  titleInDetail: '<li class="mgB10" ng-click="resizeScroll(\'scrollSchedulesContentDetail\')"> <div class="layout-fixed"> <div class="appoinment-cell" style="border-color: ' + dataApp.appgroupColor + '"> <div class="bar" style="background: ' + dataApp.customertypesColor + '"></div> <div class="light" style="background: ' + dataApp.flexibleColor + '"></div> </div> <div> <div class="time" ng-click="changeTimeRangeSchedule($event)"> <div class="bar-area"></div> <div class="mark-start"> <i></i><span class="text-date-1 lowercase pdL10">' + $scope.displayTime(timeStartFormat, false) + '</span> </div> <div class="mark-end"> <i></i><span class="text-date-1 lowercase pdR10">' + $scope.displayTime(timeEndFormat, false) + '</span> </div> </div>                             <div class="time-change"><input type="text" data-appt-id="' + dataApp.id + '" data-time-start="' + timeStartFormat + '" data-time-end="' + timeEndFormat + '" /><div class="control layout-fixed mgT20"> <div class="range-text"> <div class="layout-fixed w-auto-i text-title-4 clr-black"> <div class="label-time-start-change"></div> <div class="w16px text-center pdB2"> <svg viewBox="0 0 14 14" class="h6px clr-symbol"> <g> <g> <path d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" fill="#b1c7d7" /> </g> </g> </svg> </div> <div class="label-time-end-change"></div> </div> </div> <div class="clear"> <div class="layout-fixed w-auto-i right"> <div class="pdR20"> <button class="btn-update-range bg-transparent biger-3-time" type="button" ng-click="updateTimeRangeSchedule($event,\'app\')"> <svg viewBox="0 0 511.999 511.999" class="h20px clr-symbol-clickable"> <path d="M506.231,75.508c-7.689-7.69-20.158-7.69-27.849,0l-319.21,319.211L33.617,269.163c-7.689-7.691-20.158-7.691-27.849,0    c-7.69,7.69-7.69,20.158,0,27.849l139.481,139.481c7.687,7.687,20.16,7.689,27.849,0l333.133-333.136    C513.921,95.666,513.921,83.198,506.231,75.508z"/> </svg> </button> </div> <div> <button class="btn-close-range bg-transparent biger-3-time" type="button" ng-click="closeTimeRangeSchedule($event)"> <svg class="h17px clr-symbol-clickable" viewBox="0 0 512.001 512.001"> <path d="M505.922,476.567L285.355,256L505.92,35.435c8.106-8.105,8.106-21.248,0-29.354c-8.105-8.106-21.248-8.106-29.354,0    L256.001,226.646L35.434,6.081c-8.105-8.106-21.248-8.106-29.354,0c-8.106,8.105-8.106,21.248,0,29.354L226.646,256L6.08,476.567    c-8.106,8.106-8.106,21.248,0,29.354c8.105,8.105,21.248,8.106,29.354,0l220.567-220.567l220.567,220.567    c8.105,8.105,21.248,8.106,29.354,0S514.028,484.673,505.922,476.567z"/> </svg> </button> </div> </div> </div> </div></div>                           <div class="schedule-content layout-fixed pdTB5 pdLR10" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="text-content"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> <div class="w50px clear"> <button class="app-item-next-icon bg-transparent pd0-i right" type="button"> </button> </div> </div> </div> </div> </li>'
                }
              }
              $scope.list_field_worker[i].appHtml += evt.title;
              $scope.list_field_worker[i].appHtmlInDetail += evt.titleInDetail;
              arrEvt.push(evt);
            } else {
              var dataApp = list_status[list_status.length - 1];
              var dataApp = list_status[0];
              var city = ''
              if (dataApp.jsCity != undefined && dataApp.jsCity.length > 0) {
                city = dataApp.jsCity + '-';
              } else {
                city = dataApp.ctCity + '-';
              }
              if (dataApp.nothomeutil != "00:00:00") {
                var timeArr = dataApp.nothomeutil.split(':');
                var date = new Date().setHours(timeArr[0], timeArr[1], timeArr[2])
                var timeformat = '-' + moment(date).format("h:mm A");
              } else {
                var timeformat = '';
              }
              var timeStart = dataApp.startimeShow.split(':');
              var date = new Date().setHours(timeStart[0], timeStart[1], timeStart[2])
              var timeStartFormat = moment(date).format("h:mm A");
              var timeEnd = dataApp.endtimeShow.split(':');
              var date = new Date().setHours(timeEnd[0], timeEnd[1], timeEnd[2])
              var timeEndFormat = moment(date).format("h:mm A");
              var evt = {
                id: dataApp.id,
                appointmentgroupsId: dataApp.appointmentgroup_id,
                resourceId: itemFieldWorkerData.fieldworkerId,
                start: $scope.selectedDay + dataApp.startime,
                end: $scope.selectedDay + dataApp.endtime,
                title: '<div class="mgT15" on-hold="openScheduleAppointmentMoveTo(\'' + dataApp.id + '\')"> <div class="layout-fixed" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="w50px v-top-i pdT5"> <div class="jobstatus-cell" style="background: ' + dataApp.statusesColor + '"></div> </div> <div class="v-top-i"> <div class="layout-fixed w-auto-i text-date-1"> <div>' + $scope.displayTime(timeStartFormat, false) + '</div> <div class="w16px text-center pdB2"> <svg class="h6px" viewBox="0 0 14 14"> <g> <g> <path fill="#b1c7d7" d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" /> </g> </g> </svg> </div> <div>' + $scope.displayTime(timeEndFormat, false) + '</div> </div> <div class="text"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> </div> <div class="w30px clear"> <button type="button" class="app-item-next-icon bg-transparent pd0-i right"> </button> </div> </div> </div>',
                titleInDetail: '<li class="mgB10" ng-click="resizeScroll(\'scrollSchedulesContentDetail\')"> <div class="layout-fixed"> <div class="tasknote-cell" style="background: ' + dataApp.statusesColor + '"></div> <div> <div class="time" ng-click="changeTimeRangeSchedule($event)"> <div class="bar-area"></div> <div class="mark-start"> <i></i><span class="text-date-1 lowercase pdL10">' + $scope.displayTime(timeStartFormat, false) + '</span> </div> <div class="mark-end"> <i></i><span class="text-date-1 lowercase pdR10">' + $scope.displayTime(timeEndFormat, false) + '</span> </div> </div>                                  <div class="time-change"><input type="text" data-appt-id="' + dataApp.id + '" data-time-start="' + timeStartFormat + '" data-time-end="' + timeEndFormat + '" /><div class="control layout-fixed mgT20"> <div class="range-text"> <div class="layout-fixed w-auto-i text-title-4 clr-black"> <div class="label-time-start-change"></div> <div class="w16px text-center pdB2"> <svg viewBox="0 0 14 14" class="h6px clr-symbol"> <g> <g> <path d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" fill="#b1c7d7" /> </g> </g> </svg> </div> <div class="label-time-end-change"></div> </div> </div> <div class="clear"> <div class="layout-fixed w-auto-i right"> <div class="pdR20"> <button class="btn-update-range bg-transparent biger-3-time" type="button" ng-click="updateTimeRangeSchedule($event,\'app\')"> <svg viewBox="0 0 511.999 511.999" class="h20px clr-symbol-clickable"> <path d="M506.231,75.508c-7.689-7.69-20.158-7.69-27.849,0l-319.21,319.211L33.617,269.163c-7.689-7.691-20.158-7.691-27.849,0    c-7.69,7.69-7.69,20.158,0,27.849l139.481,139.481c7.687,7.687,20.16,7.689,27.849,0l333.133-333.136    C513.921,95.666,513.921,83.198,506.231,75.508z"/> </svg> </button> </div> <div> <button class="btn-close-range bg-transparent biger-3-time" type="button" ng-click="closeTimeRangeSchedule($event)"> <svg class="h17px clr-symbol-clickable" viewBox="0 0 512.001 512.001"> <path d="M505.922,476.567L285.355,256L505.92,35.435c8.106-8.105,8.106-21.248,0-29.354c-8.105-8.106-21.248-8.106-29.354,0    L256.001,226.646L35.434,6.081c-8.105-8.106-21.248-8.106-29.354,0c-8.106,8.105-8.106,21.248,0,29.354L226.646,256L6.08,476.567    c-8.106,8.106-8.106,21.248,0,29.354c8.105,8.105,21.248,8.106,29.354,0l220.567-220.567l220.567,220.567    c8.105,8.105,21.248,8.106,29.354,0S514.028,484.673,505.922,476.567z"/> </svg> </button> </div> </div> </div> </div></div>                                  <div class="schedule-content layout-fixed pdTB5 pdLR10" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="text-content"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> <div class="w50px clear"> <button class="app-item-next-icon bg-transparent pd0-i right" type="button"> </button> </div> </div> </div> </div> </li>'
              }
              if ($scope.tier.t1) {
                var evt = {
                  id: dataApp.id,
                  appointmentgroupsId: dataApp.appointmentgroup_id,
                  resourceId: itemFieldWorkerData.fieldworkerId,
                  start: $scope.selectedDay + dataApp.startime,
                  end: $scope.selectedDay + dataApp.endtime,
                  title: '<div class="mgT15" on-hold="openScheduleAppointmentMoveTo(\'' + dataApp.id + '\')"> <div class="layout-fixed" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="w50px v-top-i pdT5"> <div class="jobstatus-cell" style="background: ' + (dataApp.status == 'EnRoute' && dataApp.callahead_name != $scope.NoCaText ? $scope.differentNoCaAndRouteColor : dataApp.statusesColor) + '"></div> </div> <div class="v-top-i"> <div class="layout-fixed w-auto-i text-date-1"> <div>' + $scope.displayTime(timeStartFormat, false) + '</div> <div class="w16px text-center pdB2"> <svg class="h6px" viewBox="0 0 14 14"> <g> <g> <path fill="#b1c7d7" d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" /> </g> </g> </svg> </div> <div>' + $scope.displayTime(timeEndFormat, false) + '</div> </div> <div class="text"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> </div> <div class="w30px clear"> <button type="button" class="app-item-next-icon bg-transparent pd0-i right"> </button> </div> </div> </div>',
                  titleInDetail: '<li class="mgB10" ng-click="resizeScroll(\'scrollSchedulesContentDetail\')"> <div class="layout-fixed"> <div class="tasknote-cell" style="background: ' + (dataApp.status == 'EnRoute' && dataApp.callahead_name != $scope.NoCaText ? $scope.differentNoCaAndRouteColor : dataApp.statusesColor) + '"></div> <div> <div class="time" ng-click="changeTimeRangeSchedule($event)"> <div class="bar-area"></div> <div class="mark-start"> <i></i><span class="text-date-1 lowercase pdL10">' + $scope.displayTime(timeStartFormat, false) + '</span> </div> <div class="mark-end"> <i></i><span class="text-date-1 lowercase pdR10">' + $scope.displayTime(timeEndFormat, false) + '</span> </div> </div>                                      <div class="time-change"><input type="text" data-appt-id="' + dataApp.id + '" data-time-start="' + timeStartFormat + '" data-time-end="' + timeEndFormat + '" /><div class="control layout-fixed mgT20"> <div class="range-text"> <div class="layout-fixed w-auto-i text-title-4 clr-black"> <div class="label-time-start-change"></div> <div class="w16px text-center pdB2"> <svg viewBox="0 0 14 14" class="h6px clr-symbol"> <g> <g> <path d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" fill="#b1c7d7" /> </g> </g> </svg> </div> <div class="label-time-end-change"></div> </div> </div> <div class="clear"> <div class="layout-fixed w-auto-i right"> <div class="pdR20"> <button class="btn-update-range bg-transparent biger-3-time" type="button" ng-click="updateTimeRangeSchedule($event,\'app\')"> <svg viewBox="0 0 511.999 511.999" class="h20px clr-symbol-clickable"> <path d="M506.231,75.508c-7.689-7.69-20.158-7.69-27.849,0l-319.21,319.211L33.617,269.163c-7.689-7.691-20.158-7.691-27.849,0    c-7.69,7.69-7.69,20.158,0,27.849l139.481,139.481c7.687,7.687,20.16,7.689,27.849,0l333.133-333.136    C513.921,95.666,513.921,83.198,506.231,75.508z"/> </svg> </button> </div> <div> <button class="btn-close-range bg-transparent biger-3-time" type="button" ng-click="closeTimeRangeSchedule($event)"> <svg class="h17px clr-symbol-clickable" viewBox="0 0 512.001 512.001"> <path d="M505.922,476.567L285.355,256L505.92,35.435c8.106-8.105,8.106-21.248,0-29.354c-8.105-8.106-21.248-8.106-29.354,0    L256.001,226.646L35.434,6.081c-8.105-8.106-21.248-8.106-29.354,0c-8.106,8.105-8.106,21.248,0,29.354L226.646,256L6.08,476.567    c-8.106,8.106-8.106,21.248,0,29.354c8.105,8.105,21.248,8.106,29.354,0l220.567-220.567l220.567,220.567    c8.105,8.105,21.248,8.106,29.354,0S514.028,484.673,505.922,476.567z"/> </svg> </button> </div> </div> </div> </div></div>                                   <div class="schedule-content layout-fixed pdTB5 pdLR10" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="text-content"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> <div class="w50px clear"> <button class="app-item-next-icon bg-transparent pd0-i right" type="button"> </button> </div> </div> </div> </div> </li>'
                }
              }
              if ($scope.tier.t2) {
                if (parseInt(dataApp.is_cancel)) {
                  $scope.appStatusColor = appStatusColor;
                } else {
                  $scope.appStatusColor = dataApp.status == 'EnRoute' && dataApp.callahead_name != $scope.NoCaText ? $scope.differentNoCaAndRouteColor : dataApp.statusesColor;
                }
                var evt = {
                  id: dataApp.id,
                  appointmentgroupsId: dataApp.appointmentgroup_id,
                  resourceId: itemFieldWorkerData.fieldworkerId,
                  start: $scope.selectedDay + dataApp.startime,
                  end: $scope.selectedDay + dataApp.endtime,
                  title: '<div class="mgT15" on-hold="openScheduleAppointmentMoveTo(\'' + dataApp.id + '\')"> <div class="layout-fixed" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="w50px v-top-i pdT5"> <div class="jobstatus-cell" style="background: ' + $scope.appStatusColor + '"></div> </div> <div class="v-top-i"> <div class="layout-fixed w-auto-i text-date-1"> <div>' + $scope.displayTime(timeStartFormat, false) + '</div> <div class="w16px text-center pdB2"> <svg class="h6px" viewBox="0 0 14 14"> <g> <g> <path fill="#b1c7d7" d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" /> </g> </g> </svg> </div> <div>' + $scope.displayTime(timeEndFormat, false) + '</div> </div> <div class="text"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> </div> <div class="w30px clear"> <button type="button" class="app-item-next-icon bg-transparent pd0-i right"> </button> </div> </div> </div>',
                  titleInDetail: '<li class="mgB10" ng-click="resizeScroll(\'scrollSchedulesContentDetail\')"> <div class="layout-fixed"> <div class="tasknote-cell" style="background: ' + $scope.appStatusColor + '"></div> <div> <div class="time" ng-click="changeTimeRangeSchedule($event)"> <div class="bar-area"></div> <div class="mark-start"> <i></i><span class="text-date-1 lowercase pdL10">' + $scope.displayTime(timeStartFormat, false) + '</span> </div> <div class="mark-end"> <i></i><span class="text-date-1 lowercase pdR10">' + $scope.displayTime(timeEndFormat, false) + '</span> </div> </div>                                       <div class="time-change"><input type="text" data-appt-id="' + dataApp.id + '" data-time-start="' + timeStartFormat + '" data-time-end="' + timeEndFormat + '" /><div class="control layout-fixed mgT20"> <div class="range-text"> <div class="layout-fixed w-auto-i text-title-4 clr-black"> <div class="label-time-start-change"></div> <div class="w16px text-center pdB2"> <svg viewBox="0 0 14 14" class="h6px clr-symbol"> <g> <g> <path d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" fill="#b1c7d7" /> </g> </g> </svg> </div> <div class="label-time-end-change"></div> </div> </div> <div class="clear"> <div class="layout-fixed w-auto-i right"> <div class="pdR20"> <button class="btn-update-range bg-transparent biger-3-time" type="button" ng-click="updateTimeRangeSchedule($event,\'app\')"> <svg viewBox="0 0 511.999 511.999" class="h20px clr-symbol-clickable"> <path d="M506.231,75.508c-7.689-7.69-20.158-7.69-27.849,0l-319.21,319.211L33.617,269.163c-7.689-7.691-20.158-7.691-27.849,0    c-7.69,7.69-7.69,20.158,0,27.849l139.481,139.481c7.687,7.687,20.16,7.689,27.849,0l333.133-333.136    C513.921,95.666,513.921,83.198,506.231,75.508z"/> </svg> </button> </div> <div> <button class="btn-close-range bg-transparent biger-3-time" type="button" ng-click="closeTimeRangeSchedule($event)"> <svg class="h17px clr-symbol-clickable" viewBox="0 0 512.001 512.001"> <path d="M505.922,476.567L285.355,256L505.92,35.435c8.106-8.105,8.106-21.248,0-29.354c-8.105-8.106-21.248-8.106-29.354,0    L256.001,226.646L35.434,6.081c-8.105-8.106-21.248-8.106-29.354,0c-8.106,8.105-8.106,21.248,0,29.354L226.646,256L6.08,476.567    c-8.106,8.106-8.106,21.248,0,29.354c8.105,8.105,21.248,8.106,29.354,0l220.567-220.567l220.567,220.567    c8.105,8.105,21.248,8.106,29.354,0S514.028,484.673,505.922,476.567z"/> </svg> </button> </div> </div> </div> </div></div>                                          <div class="schedule-content layout-fixed pdTB5 pdLR10" ng-click="getSchedulesCustomerInfo(\'' + dataApp.id + '\')"> <div class="text-content"> <div>' + city + dataApp.appointmentgroupsName + '</div> <div>' + $scope.displayTime(timeStartFormat, false) + '-' + $scope.displayTime(timeEndFormat, false) + '-' + dataApp.callahead_name + $scope.displayTime(timeformat, false) + '</div> </div> <div class="w50px clear"> <button class="app-item-next-icon bg-transparent pd0-i right" type="button"> </button> </div> </div> </div> </div> </li>'
                }
              }
              $scope.list_field_worker[i].appHtml += evt.title;
              $scope.list_field_worker[i].appHtmlInDetail += evt.titleInDetail;
              arrEvt.push(evt);
            }
          }
          if (item.type == 'task') {
            var itemTask = appAndTaskArr[j];
            var taskStatus = parseInt(itemTask.status);
            var taskColor = '';
            switch (taskStatus) {
              case 1:
              taskColor = pendingColor;
              break;
              case 2:
              taskColor = enrouteColor;
              break;
              case 3:
              taskColor = workingColor;
              break;
              case 4:
              taskColor = finishColor;
              break;
            }
            var evtTask = {
              id: itemTask.id,
              resourceId: itemFieldWorkerData.fieldworkerId,
              start: $scope.selectedDay + 'T' + itemTask.from_time,
              end: $scope.selectedDay + 'T' + itemTask.to_time,
              title: '<div class="mgT15" on-hold="openScheduleAppointmentMoveTo(\'' + itemTask.id + '\')"><div class="layout-fixed" ng-click="popupEditTasknote(' + itemTask.id + ')"><div class="w50px v-top-i pdT5"><div class="tasknote-cell" style="background: ' + taskColor + '"></div></div><div class="v-top-i"><div class="layout-fixed w-auto-i text-date-1"><div>' + $scope.displayTime(moment(itemTask.from_time, 'HH:mm:ss').format("h:mm A"), false) + '</div><div class="w16px text-center pdB2"><svg class="h6px" viewBox="0 0 14 14"><g><g><path fill="#b1c7d7" d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" /> </g> </g> </svg> </div> <div>' + $scope.displayTime(moment(itemTask.to_time, 'HH:mm:ss').format("h:mm A"), false) + '</div> </div> <div class="text"> <div>' + itemTask.detail + '</div> <div>' + itemTask.notetasktypeName + '</div> </div> </div> <div class="w30px clear"> <button type="button" class="app-item-next-icon bg-transparent pd0-i right"> </button> </div> </div></div>',
              titleInDetail: '<li class="mgB10" ng-click="resizeScroll(\'scrollSchedulesContentDetail\')"> <div class="layout-fixed"> <div class="tasknote-cell" style="background: ' + taskColor + '"></div> <div> <div class="time" ng-click="changeTimeRangeSchedule($event)"> <div class="bar-area"></div> <div class="mark-start"> <i></i><span class="text-date-1 lowercase pdL10">' + $scope.displayTime(moment(itemTask.from_time, 'HH:mm:ss').format("h:mm A"), false) + '</span> </div> <div class="mark-end"> <i></i><span class="text-date-1 lowercase pdR10">' + $scope.displayTime(moment(itemTask.to_time, 'HH:mm:ss').format("h:mm A"), false) + '</span> </div> </div>                                    <div class="time-change"><input type="text" data-appt-id="' + itemTask.id + '" data-time-start="' + timeStartFormat + '" data-time-end="' + timeEndFormat + '" /><div class="control layout-fixed mgT20"> <div class="range-text"> <div class="layout-fixed w-auto-i text-title-4 clr-black"> <div class="label-time-start-change"></div> <div class="w16px text-center pdB2"> <svg viewBox="0 0 14 14" class="h6px clr-symbol"> <g> <g> <path d="M5.396,13.433C8.037,10.859,12,7,12,7S8.037,3.141,5.396,0.567C5.033,0.218,4.543,0,4,0    C2.896,0,2,0.896,2,2v10c0,1.104,0.896,2,2,2C4.543,14,5.033,13.782,5.396,13.433z" fill="#b1c7d7" /> </g> </g> </svg> </div> <div class="label-time-end-change"></div> </div> </div> <div class="clear"> <div class="layout-fixed w-auto-i right"> <div class="pdR20"> <button class="btn-update-range bg-transparent biger-3-time" type="button" ng-click="updateTimeRangeSchedule($event,\'task\')"> <svg viewBox="0 0 511.999 511.999" class="h20px clr-symbol-clickable"> <path d="M506.231,75.508c-7.689-7.69-20.158-7.69-27.849,0l-319.21,319.211L33.617,269.163c-7.689-7.691-20.158-7.691-27.849,0    c-7.69,7.69-7.69,20.158,0,27.849l139.481,139.481c7.687,7.687,20.16,7.689,27.849,0l333.133-333.136    C513.921,95.666,513.921,83.198,506.231,75.508z"/> </svg> </button> </div> <div> <button class="btn-close-range bg-transparent biger-3-time" type="button" ng-click="closeTimeRangeSchedule($event)"> <svg class="h17px clr-symbol-clickable" viewBox="0 0 512.001 512.001"> <path d="M505.922,476.567L285.355,256L505.92,35.435c8.106-8.105,8.106-21.248,0-29.354c-8.105-8.106-21.248-8.106-29.354,0    L256.001,226.646L35.434,6.081c-8.105-8.106-21.248-8.106-29.354,0c-8.106,8.105-8.106,21.248,0,29.354L226.646,256L6.08,476.567    c-8.106,8.106-8.106,21.248,0,29.354c8.105,8.105,21.248,8.106,29.354,0l220.567-220.567l220.567,220.567    c8.105,8.105,21.248,8.106,29.354,0S514.028,484.673,505.922,476.567z"/> </svg> </button> </div> </div> </div> </div></div>                                      <div class="schedule-content layout-fixed pdTB5 pdLR10" ng-click="popupEditTasknote(' + itemTask.id + ')"> <div class="text-content"> <div>' + itemTask.detail + '</div> <div>' + itemTask.notetasktypeName + '</div> </div> <div class="w50px clear"> <button class="app-item-next-icon bg-transparent pd0-i right" type="button"> </button> </div> </div> </div> </div> </li>'
            };
            $scope.list_field_worker[i].appHtml += evtTask.title;
            $scope.list_field_worker[i].appHtmlInDetail += evtTask.titleInDetail;
            arrEvt.push(evtTask);
          }
        }
        for (var d = 0; d < itemFieldWorkerData.biweek.length; d++) {
          if (itemFieldWorkerData.biweek[d].toHour > itemFieldWorkerData.biweek[d].fromHour) {
            var evt = {
              id: 'disabledEvent' + itemFieldWorkerData.biweek[d].id,
              resourceId: itemFieldWorkerData.fieldworkerId,
              start: $scope.selectedDay + 'T' + itemFieldWorkerData.biweek[d].fromHour,
              end: $scope.selectedDay + 'T' + itemFieldWorkerData.biweek[d].toHour,
              title: '<div class="event-disabled mybiweek"></div>',
              editable: false
            }
            if ($scope.tier.t1) {
              var evt = {
                id: 'disabledEvent' + itemFieldWorkerData.biweek[d].id,
                resourceId: itemFieldWorkerData.fieldworkerId,
                start: $scope.selectedDay + 'T' + itemFieldWorkerData.biweek[d].fromHour,
                end: $scope.selectedDay + 'T' + itemFieldWorkerData.biweek[d].toHour,
                title: '<div class="event-disabled mybiweek appidcell" data-appid="' + itemFieldWorkerData.biweek[d].id + '" data-type="biweekevent" data-position="' + itemFieldWorkerData.biweek[d].position + '"></div>',
                editable: true
              }
            }
            arrEvt.push(evt);
          }
        }
      }
      if (type == 'inDetail') {
        var idx = _.findLastIndex($scope.list_field_worker, {
          fieldworkerId: $scope.detailSchedule.fieldworkerId
        });
        $scope.openPopupDetailSchedule($scope.list_field_worker[idx]);
      }
      $scope.paysounds = 0;
      $scope.playAudio = function(s) {
        $scope.paysounds = 1;
        var aud = document.getElementById(s);
        aud.play();
      }
      $scope.pauseAudio = function(s) {
        if ($scope.detailAppointmentData.recordingfile != null && $scope.detailAppointmentData.recordingfile != '') {
          $scope.paysounds = 0;
          try {
            var aud = document.getElementById(s);
            aud.pause();
          } catch (e) {
            console.log(e);
          }
        }
      }
      $scope.resetAudio = function(s) {
        $scope.paysounds = 1;
        var aud = document.getElementById(s);
        aud.currentTime = 0;
        aud.play();
      }
      if ($scope.tier.t1) {
        $scope.getNameAndPositionUserById = function(id, arr) {
          Users.nameAndPositionUserById(id).success(function(data) {
            arr['fieldworker'] = data;
            $scope.$broadcast('addNoteTaskSchedule', arr);
          });
          $('#addNoteTaskSchedule').trigger('click');
        }
      }
      $scope.assignToNewFieldworker = function(id, data, calendarDay) {
        Appointments.assignToNewFieldworker(id, data).success(function(data) {
          if (data.status) {
            toastr.success(data.msg);
            $scope.loadAppointmentByDay(calendarDay);
            $scope.dataConvertApp = {};
          } else {
            $cordovaToast.showLongTop(data.msg);
          }
        });
      }
      $scope.updateCellCalendar = function() {
        if ($scope.currentResourceId == $scope.newResourceId) {
          if ($scope.tier.t1) {
            switch ($scope.dataChangeCell.type) {
              case 'app':
              if ($scope.dataChangeCell.end < $scope.dataChangeCell.oldStart || $scope.dataChangeCell.start > $scope.dataChangeCell.oldEnd) {
                $scope.dataNewConfirm.appId = $scope.dataChangeCell.appId;
                $scope.dataNewConfirm.board_start = $scope.dataChangeCell.start;
                $scope.dataNewConfirm.board_end = $scope.dataChangeCell.end;
                $('#confirmStart').val(moment($scope.dataChangeCell.arrivalwindow, 'HH:mm:ss').format('HH:mm'));
                $('#confirmEnd').val(moment($scope.dataChangeCell.endarrivalwindow, 'HH:mm:ss').format('HH:mm'));
                openPopup('#popupnewconfirmbox');
              } else {
                $scope.appointmentCellChanged($scope.dataChangeCell.appId, $scope.dataChangeCell);
              }
              break;
              case 'task':
              $scope.appointmentCellChanged($scope.dataChangeCell.appId, $scope.dataChangeCell);
              break;
              case 'biweekevent':
              $scope.appointmentCellChanged($scope.dataChangeCell.appId, $scope.dataChangeCell);
              break;
            }
          } else {
            if ($scope.dataChangeCell.type == 'app') {
              if ($scope.dataChangeCell.end < $scope.dataChangeCell.oldStart || $scope.dataChangeCell.start > $scope.dataChangeCell.oldEnd) {
                $scope.dataNewConfirm.appId = $scope.dataChangeCell.appId;
                $scope.dataNewConfirm.board_start = $scope.dataChangeCell.start;
                $scope.dataNewConfirm.board_end = $scope.dataChangeCell.end;
                $('#confirmStart').val(moment($scope.dataChangeCell.arrivalwindow, 'HH:mm:ss').format('HH:mm'));
                $('#confirmEnd').val(moment($scope.dataChangeCell.endarrivalwindow, 'HH:mm:ss').format('HH:mm'));
                openPopup('#popupnewconfirmbox');
              } else {
                $scope.appointmentCellChanged($scope.dataChangeCell.appId, $scope.dataChangeCell);
              }
            } else {
              $scope.appointmentCellChanged($scope.dataChangeCell.appId, $scope.dataChangeCell);
            }
          }
        }
      }
      $scope.confirmBoxSubmit = function() {
        if (moment($scope.dataChangeCell.arrivalwindow, 'HH:mm:ss').format('HH:mm') == moment($('#confirmStart').val(), 'HH:mm').format('HH:mm')) {
          $('#confirmStart').parent().parent().find('.notif').html('You must change start time');
          return;
        }
        $('#confirmStart').parent().parent().find('.notif').html('');
        if (moment($scope.dataChangeCell.endarrivalwindow, 'HH:mm:ss').format('HH:mm') == moment($('#confirmEnd').val(), 'HH:mm').format('HH:mm')) {
          $('#confirmEnd').parent().parent().find('.notif').html('You must change end time');
          return;
        }
        $('#confirmEnd').parent().parent().find('.notif').html('');
        $startTimeCheck = moment($('#confirmStart').val(), 'HH:mmA').format('HH:mm');
        $endTimeCheck = moment($('#confirmEnd').val(), 'HH:mmA').format('HH:mm');
        if ($startTimeCheck > $endTimeCheck || $startTimeCheck == $endTimeCheck) {
          $('#confirmEnd').parent().parent().find('.notif').html('End time must be greater than start time');
          return;
        }
        $('#confirmEnd').parent().parent().find('.notif').html('');
        $scope.dataNewConfirm.start = $('#confirmStart').val();
        $scope.dataNewConfirm.end = $('#confirmEnd').val();
        Appointments.arrivalConfirm($scope.dataNewConfirm.appId, $scope.dataNewConfirm).success(function(data) {
          if (data.status) {
            $scope.dataNewConfirm = {};
            closePopupById('popupupdatelistsviewsappoiment');
            $scope.loadAppointmentByDay($("#scheduleDayValue").val());
          } else {
            $cordovaToast.showLongTop(data.msg);
          }
        });
      }
      $scope.cancelConfirm = function() {
        $scope.loadAppointmentByDay($("#scheduleDayValue").val());
      }
      $scope.getSelectListviews();
      $scope.$broadcast('scroll.refreshComplete');
    });
}
$scope.refreshLoadAppointMents = function() {
  $scope.loadAppointmentByDay($("#scheduleDayValue").val());
}
$scope.$watch('dataAppHtml.scheduleDay', function(value) {
  if ($scope.setTime) {
    $("#scheduleDay .day").html(moment(value).format('DD'));
    $("#scheduleDay .month").html(moment(value).format('MMMM'));
    $scope.loadAppointmentByDay(moment(value).format('YYYY-MM-DD'));
  }
})
$scope.viewUnavailable = function(val) {
  $scope.viewUnavailableValue = val;
  $scope.loadAppointmentByDay($("#scheduleDayValue").val());
}
$scope.departmentcheck = function(id, val) {
  if ($scope.arrDepart.length == 0) {
    $scope.val = false;
  }
  if (val) {
    $scope.checkall = false;
    $scope.departId = id;
    $scope.arrDepart.push(id);
  } else {
    if ($scope.checkall) {
      $scope.val = false;
    }
    $scope.checkall = false;
    $scope.pos = $scope.arrDepart.indexOf(id);
    $scope.arrDepart.splice($scope.pos, 1);
  }
  $scope.getListToSchedule();
};
$scope.checkAll = function(val) {
  if (val) {
    $scope.val = true;
    $scope.checkall = true;
    $('#popupFilter .cbDepart').prop('checked', true);
  } else {
    $scope.checkall = false;
    $scope.val = false;
    $('#popupFilter .cbDepart').prop('checked', false);
  }
  $scope.arrDepart = [];
  $scope.getListToSchedule();
    //$scope.loadAppointmentByDay($scope.selectedDay);
  };
  $scope.loadTreeDepart = function() {
    if (!$scope.dataTreeLoad) {
      $ionicLoading.show({
        template: templateLoading
      })
      Users.getUsersByDepart().success(function(data) {
        if (!startpage) ionicLoading.hide();
        $scope.filterClientdata = data;
        $scope.isbuildtree = true;
        $scope.dataTreeLoad = true;
        if ($scope.isbuildtree) {
          $scope.createStructTreeDepart();
          $scope.isbuildtree = false;
        }!$scope.check_init_schedule ? $interval($scope.checkLogin, time_refresh) : '';
        request_notify_get_chat = true;
        $scope.check_init_schedule = true;
        $scope.getAppointmentgroups();
      }).error(function(data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
      });
    }
  };
  $scope.createStructTreeDepart = function() {
    if ($scope.isbuildtree) {
      $scope.addresschecked = [];
      var depart = _.uniq(_.map($scope.filterClientdata, function(currentObject) {
        return _.extend(_.pick(currentObject, "name", "departmentId", 'usersName', 'id'), {
          label: currentObject.name,
          id: currentObject.userId,
          uid: "level_" + currentObject.userId + "_" + currentObject.departmentId,
          level: "1"
        });
      }), function(item, key, depart) {
        return item.name;
      });
      $scope.usersFill = _.map($scope.filterClientdata, function(currentObject) {
        return _.extend(_.pick(currentObject, "name", "departmentId", 'usersName', 'id'), {
          label: currentObject.usersName,
          id: currentObject.userId,
          uid: currentObject.departmentId + "_" + currentObject.userId,
          level: "2"
        });
      });
      var depart = _.each(depart, function(item) {
        usersOfDepart = _.where($scope.usersFill, {
          departmentId: item.departmentId
        });
        item.children = usersOfDepart;
        return item;
      });
      $scope.stuffEdit = [{
        label: 'Select All',
        level: "0",
        uid: "0",
        children: depart
      }];
      $scope.stuff0 = [{
        label: 'Select All',
        level: "0",
        children: depart
      }];
    }
  }
  $scope.editListviewusersData = {};
  $scope.editListviewusers = function(id) {
    $ionicLoading.show({
      template: templateLoading
    });
    $scope.openByGetTemplate('popupEditScheduleListView')
    Listviewusers.show(id).success(function(data) {
      $ionicLoading.hide();
      ivhTreeviewMgr.deselectAll($scope.stuffEdit);
      $scope.editListviewusersData = data;
      var unique_ids = [];
      for (var i = 0; i < data.arrayId.length; i++) {
        var t = data.arrayId[i];
        var dep = _.findWhere($scope.usersFill, {
          id: t
        });
        if (dep) {
          unique_ids.push(dep);
        }
      };
      ivhTreeviewMgr.selectEach($scope.stuffEdit, unique_ids);
      $scope.editListviewusersData.arrayId = unique_ids;
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.updateListviewusers = function(formValidate) {
    if (formValidate.$invalid) {
      var handle = $ionicScrollDelegate.$getByHandle('scrollUpdateListView');
      handle.scrollTop();
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    };
    var id = $scope.editListviewusersData.id;
    $ionicLoading.show({
      template: templateLoading
    });
    Listviewusers.update(id, $scope.editListviewusersData).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $scope.closeTarget('#popupEditScheduleListView')
        $scope.editListviewusersData = {};
        $scope.getSelectListviews();
        ivhTreeviewMgr.deselectAll($scope.stuffEdit);
        $cordovaToast.showLongTop(data.msg);
      } else {
        $cordovaToast.showLongTop(data.msg);
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.changeDepartGetFieldWokerId = function() {
    $scope.addListviewusersData.arrUserIdAddlistView = _.where($scope.usersFill, {
      selected: true
    });
  }
  $scope.changeDepartGetFieldWokerIdEdit = function() {
    $scope.editListviewusersData.arrayId = _.where($scope.usersFill, {
      selected: true
    });
  }
  $scope.addListViewFieldWorker = function(formValidate) {
    // console.log(formValidate);
    if (formValidate.$invalid) {
      var handle = $ionicScrollDelegate.$getByHandle('scrollAddListView');
      handle.scrollTop();
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    };
    $ionicLoading.show({
      template: templateLoading
    });
    Listviewusers.save($scope.addListviewusersData).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $scope.closeTarget('#popupAddScheduleListView');
        $scope.addListviewusersData = {};
        $scope.getSelectListviews();
        $cordovaToast.showLongTop(data.msg);
      } else {
        $cordovaToast.showLongTop(data.msg);
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.openAddlistview = function() {
    $scope.openByGetTemplate('popupAddScheduleListView');
    $timeout(function() {
      // dataHtml.getTemplate('templates/dashboard/schedules/schedulePopupListViewAddmodal.tpl').success(function(results) {
      //     $scope.dataAppHtml.addListView = results;
      ivhTreeviewMgr.deselectAll($scope.stuff0);
      $ionicLoading.hide();
      // })
    }, 500);
  }
  $scope.sizeChanged = function() {
    $scope.searchAppointments.rows = $scope.entryLimit;
    appointments_pagesize.val($scope.searchAppointments.rows);
    localStorage.setItem('appointments_pagesize', $scope.searchAppointments.rows);
    $scope.searchAppointments.current_page = 1;
    $scope.getAppointments();
  }
  $scope.pageChanged = function() {
    $scope.searchAppointments.current_page = $scope.currentPage;
    $scope.getAppointments();
  };
  $scope.setPage = function(pageNo) {
    $scope.currentPage = pageNo;
  };
  $scope.refreshAddresses = function(address) {
    if (address.length > 0) {
      var params = {
        search: address,
        customer_id: Customers.getCustomerId()
      };
      Jobsites.getSelect2(params).success(function(data) {
        var diff = differentArray(data, $scope.addAppointmentsData.jobsites);
        $scope.jobsites = diff;
      })
    }
  };
  $scope.refreshAddressesEdit = function(address) {
    if (address.length > 0) {
      var params = {
        search: address,
        customer_id: $scope.editAppointmentsData.dataApp.customer_id
      };
      Jobsites.getSelect2(params).success(function(data) {
        var diff = differentArray(data, $scope.editAppointmentsData.dataJobsite);
        $scope.jobsitesEdit = diff;
      })
    }
  };
  $scope.resetworkinginvoice = function(id, order_id) {
    // $scope.orderData = [];
    // $scope.order_idapp = undefined;
    $scope.refreshOrdersapp('', order_id);
    //$scope.order_idapp = null;
    $scope.workinginvoi_id = id;
    //popup = $scope.openIonicPopup('templates/dashboard/schedules/appointment/schedulesPopupAddEditWorkingInvoicemodal.tpl', 'Add Edit Working Invoice');
    $scope.openByGetTemplate('popupAppointmentDetailAddEditWorkingInvoice');
    //$scope.order_idapp = {};
    // $('#popupAddEditWorkingInvoice').parent().parent().find('.close-title-button').unbind("click");
    // $('#dismis-popupAddEditWorkingInvoice').unbind("click");
    // setTimeout(function () {
    //     $('#popupAddEditWorkingInvoice').parent().parent().find('.close-title-button').click(function () {
    //         openPopup('#popupAppointmentDetail');
    //     });
    //     $('#dismis-popupAddEditWorkingInvoice').click(function () {
    //         openPopup('#popupAppointmentDetail');
    //     });
    // }, 2000);
  }
  $scope.refreshOrdersapp = function(search) {
    // if (search.length > 0) {
      var params = {
        search: search,
        customer_id: $scope.detailCustomerData.id
      };
      $ionicLoading.show({
        template: templateLoading
      });
      Orders.getSelect2(params).success(function(data) {
        $ionicLoading.hide();
        var diff = differentArray(data);
        $scope.orderData = diff;
      })
    }
    $scope.getRootdataOrder = function(search, cusId, initialOrderId) {
    // if (search.length > 0) {
      var params = {
        search: search,
        customer_id: cusId
      };
      Orders.getSelect2(params).success(function(data) {
        $scope.rootOrder = data;
        $scope.initialOrderId = [initialOrderId];
      })
    }
    $scope.ViewAllOrders = function(id) {
      $ionicLoading.show({
        template: templateLoading
      });
      Orderstatuses.ViewAllOrder(id).success(function(data) {
        $ionicLoading.hide();
        $scope.resultsData = data;
        $scope.resultsData.forEach(function(value) {
          if (parseInt(value.ordertype_id) == 5 && value.payment.length > 0) {
            value.afterSort = $scope.sortAndGroupDataPayment(value.payment);
          }
        })
        $scope.allOrderOrginData = $scope.resultsData;
        $scope.ViewAllOrder = $scope.resultsData;
      // $scope.openIonicPopup('templates/dashboard/schedules/appointment/schedulesPopupViewAllOrdersmodal.tpl', 'View Order');
      $scope.openByGetTemplate('popupAppointmentDetailOrderHistory');
    });
    }
    var popup;
    $scope.openIonicPopup = function(templateUrl, title) {
      $ionicLoading.show({
        template: templateLoading
      });
      $timeout(function() {
        $(".popup-body").addClass('prevent-scroll');
        $ionicLoading.hide();
      }, 1000);
      return $ionicPopup.show({
        templateUrl: templateUrl,
        title: title,
        scope: $scope,
        buttons: [{
          text: 'Cancel'
        }]
      })
    }
    $scope.viewPdfFile = function(link) {
      var options = {
        location: 'yes',
        clearcache: 'no',
        toolbar: 'yes'
      };
      if (isiOs) {
        $cordovaInAppBrowser.open(link, '_blank', options);
      } else {
        $cordovaInAppBrowser.open(link, '_system', options);
      }
    }
    $scope.confirmAddWorkingInvoice = function() {
      $scope.openByGetTemplate('popupConfirmAddWorkingInvoice');
    }
    $scope.changeOrderapp = function(orderData, action) {
      $scope.actionopenform = action;
      $scope.order_idapp = angular.copy(orderData);
    // var path = window.location.href;
    // var pathname = window.location.href.split('/');
    // var pa = path.lastIndexOf('/' + pathname[pathname.length - 1]);
    $ionicLoading.show({
      template: templateLoading
    });
    if (orderData.ordertype_id == 4) {
      console.log(orderData);
      Orderstatuses.opportunitiesExport(orderData.id, orderData.name).success(function(data) {
        $ionicLoading.hide();
        $scope.urlOrder = $sce.trustAsResourceUrl(data.link);
        // $scope.openIonicPopup('templates/dashboard/schedules/appointment/schedulesPopupPdfViewmodal.tpl', 'Add Edit Working Invoice');
        $scope.confirmAddWorkingInvoice();
        $scope.viewPdfFile($scope.urlOrder);
      });
    } else {
      Ordertypes.export_file_pdf(orderData.id, 'opportunitiesExport', '').success(function(data) {
        $ionicLoading.hide();
        $scope.urlOrder = $sce.trustAsResourceUrl(data.link);
        // $scope.openIonicPopup('templates/dashboard/schedules/appointment/schedulesPopupPdfViewmodal.tpl', 'Add Edit Working Invoice');
        $scope.confirmAddWorkingInvoice();
        $scope.viewPdfFile($scope.urlOrder);
      });
    }
  }
  $scope.order_idapp = {};
  $scope.addOrderToAppointmentapp = function() {
    if ($scope.actionopenform == "addedit") {
      $ionicLoading.show({
        template: templateLoading
      });
      Appointments.AddEditWorkingInvoice($scope.workinginvoi_id, $scope.order_idapp).success(function(data) {
        $ionicLoading.hide();
        if (data.status) {
          $scope.getSchedulesCustomerInfo($scope.workinginvoi_id);
          $cordovaToast.showLongTop(data.msg);
        } else {
          $cordovaToast.showLongTop(data.msg);
        }
      });
    } else {
      $scope.editAppointmentsData.dataApp.order_id = $scope.order_idapp.id;
      $scope.setValueForInputOrderId($scope.order_idapp.id)
    }
  }
  $scope.setDatafromSearch = function(data) {
    // $scope.editAppointmentsData.dataJobsite = [];
    $scope.editAppointmentsData.dataJobsite = data;
  };
  $scope.createAppointments = function(type) {
    if (Customers.getCustomerId() == 0) {
      alert('Please select customer');
    }
    $scope.addAppointmentsDataClone = angular.copy($scope.addAppointmentsData);
    // _.each($scope.addAppointmentsData.jobsites, function (item) {
    //     item.customer_id = Customers.getCustomerId();
    //     return item;
    // })
    $scope.addAppointmentsDataClone.customer_id = Customers.getCustomerId();
    if ($scope.followUpId) {
      $scope.addAppointmentsDataClone.followUpId = $scope.followUpId;
    }
    if ($scope.pendingId) {
      $scope.addAppointmentsDataClone.followUpId = $scope.pendingId;
    }
    $scope.addAppointmentsDataClone.arrivalwindow = moment($('#arrivalwindowView').val(), 'hh:mmA').format('HH:mm:ss');
    $scope.addAppointmentsDataClone.endarrivalwindow = moment($('#endarrivalwindowView').val(), 'hh:mmA').format('HH:mm:ss');
    $scope.addAppointmentsDataClone.nothomeutil = moment($('#nothomeutilView').val(), 'hh:mmA').format('HH:mm:ss');
    $scope.addAppointmentsDataClone.dateofappt = $('#dateofappt').val();
    $scope.addAppointmentsDataClone.recordingfile = appScope.recordingfile;
    $scope.disableSubmit = true;
    $scope.addAppointmentsDataClone.check_order = appScope.check_order;
    $startTimeCheck = moment($scope.addAppointmentsDataClone.arrivalwindow, 'hh:mmA').format('HH:mm:ss');
    $endTimeCheck = moment($scope.addAppointmentsDataClone.endarrivalwindow, 'hh:mmA').format('HH:mm:ss');
    if ($startTimeCheck < '06:00:00' || $endTimeCheck > '22:00:00') {
      $cordovaToast.showLongTop('The appointment cannot be scheduled outside 6AM-10PM');
      return;
    }
    var check = validateTime($scope.addAppointmentsDataClone.arrivalwindow, $scope.addAppointmentsDataClone.endarrivalwindow);
    if (!check.status) {
      $cordovaToast.showLongTop('End time must be greater than start time');
      return;
    }
    if ($scope.addAppointmentsDataClone.fieldworker == '') {
      $scope.addAppointmentsDataClone.fieldworker = null;
    }
    if (type == 'AddFromOpp') {
      $scope.$emit('saveAppointment', {
        data: $scope.addAppointmentsDataClone
      });
      return;
    }
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.save($scope.addAppointmentsDataClone).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $scope.addAppointmentsData = {};
        $scope.disableSubmit = false;
        $scope.addAppointmentsData.customer_id = 0;
        $scope.addAppointmentsData.jobsites = [];
        $scope.addAppointmentsData.addby_id = $scope.currentuserId;
        if (oppScopeMobile.fromFollowup) {
          oppScopeMobile.countAllTab('follow');
        } else {
          oppScopeMobile.countAllTab('pending');
        }
        oppScopeMobile.fromFollowup = false;
        $cordovaToast.showLongTop(data.msg);
      } else {
        $scope.disableSubmit = false;
        $cordovaToast.showLongTop(data.msg);
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.editAppointments = function(id) {
    $scope.getAppointmentgroups();
    Appointments.show(id).success(function(data) {
      $('.loader').hide();
      $scope.editAppointmentsData = data.dataApp;
    });
  }
  $scope.editAppointmentsToSchedule = function(id) {
    // console.log($scope.order_idapp);
    $scope.order_idapp = undefined;
    $scope.initialOrderId = [];
    // $scope.getAppointmentgroups();
    $scope.click_on_working_invoice = false;
    $ionicLoading.show({
      template: templateLoading
    });
    $scope.openByGetTemplate('scheduleEditModal');
    Appointments.showDataToSchedule(id).success(function(data) {
      $ionicLoading.hide();
      if (data.dataApp.dateofappt == '00/00/0000' || data.dataApp.dateofappt == '01/01/2000') {
        data.dataApp.dateofappt = '';
      }
      data.dataApp.arrivalwindow = moment(data.dataApp.arrivalwindow, 'HH:mm:ss').format('hh:mmA');
      data.dataApp.endarrivalwindow = moment(data.dataApp.endarrivalwindow, 'HH:mm:ss').format('hh:mmA');
      data.dataApp.nothomeutil = moment(data.dataApp.nothomeutil, 'HH:mm:ss').format('hh:mmA');
      // console.log(data.dataApp);
      $scope.editAppointmentsData = data;
      if ($scope.editAppointmentsData.dataApp.addby_id != null && parseInt($scope.editAppointmentsData.dataApp.addby_id) > 0) {
        $scope.editAppointmentsData.dataApp.addby_id = parseInt($scope.editAppointmentsData.dataApp.addby_id);
      } else {
        $scope.editAppointmentsData.dataApp.addby_id = $scope.currentuserId;
      }
      $scope.customer_id = $scope.editAppointmentsData.dataApp.customer_id;
      if (data.order_id != '' && data.order_id != null) {
        $scope.order_idapp = data.order_id;
      }
      $scope.customer_id = $scope.editAppointmentsData.dataApp.customer_id;
      // console.log($scope.order_idapp);
      //$scope.refreshOrdersapp('');
      try {
        if ($scope.editAppointmentsData.dataJobsite.id > 0) {
          $scope.jobsiteshow = true;
          $scope.editJobsiteField = true;
        }
      } catch (err) {}
      $scope.setValueForSelectTitleInRootDataById($scope.editAppointmentsData.dataApp.prefieldworker, 'frefieldworker');
      $scope.setValueForSelectTitleInRootDataById($scope.editAppointmentsData.dataApp.callahead_id, 'callaheads');
      $scope.setValueForSelectTitleInRootDataById($scope.editAppointmentsData.dataApp.customertype_id, 'customertypes');
      $scope.setValueForSelectTitleInRootDataById($scope.editAppointmentsData.dataApp.flexiblecustomer_id, 'flexiblecustomers');
      $scope.initialAppType = [$scope.editAppointmentsData.dataApp.appointmentgroup_id.id];
      if ($scope.editAppointmentsData.order_id) {
        $scope.getRootdataOrder('', $scope.customer_id, $scope.editAppointmentsData.order_id.id);
        $scope.initialOrderId = [$scope.editAppointmentsData.order_id.id];
      } else {
        $scope.initialOrderId = [];
      }
      $scope.appTypeId = data.dataApp.appointmentgroup_id;
      if (parseInt(data.customer_data.customertype_id) > 0) {
        $scope.editAppointmentsData.dataApp.customertype_id = data.customer_data.customertype_id;
      } else {
        $scope.editAppointmentsData.dataApp.customertype_id = customer_type_new_customer_id;
      }
      var current_customer_type = _.where($scope.customertypes, {
        id: $scope.editAppointmentsData.dataApp.customertype_id
      });
      if (current_customer_type.length > 0) {
        $('input[name=selectedCusTypeName]').val(current_customer_type[0].name);
      } else {
        $('input[name=selectedCusTypeName]').val('');
      }
      $scope.getfieldworkerByAppType($scope.appTypeId);
      $scope.jobsitesByCustomerId($scope.editAppointmentsData.dataApp.customer_id);
    });
  }
  $scope.jobsitesByCustomerId = function(customerId) {
    Customers.jobsiteByCustomerId(customerId).success(function(data) {
      $scope.jobsitesByCustomer = data.data;
      if ($scope.editAppointmentsData.dataJobsite) {
        $scope.setValueForSelectTitleInRootDataById($scope.editAppointmentsData.dataJobsite.id, 'jobsite');
      }
      if ($scope.editAppointmentsData.dataJobsite) {
        var item = _.where($scope.jobsitesByCustomer, {
          id: $scope.editAppointmentsData.dataJobsite.id
        });
        $('input[name=selectedJobsiteName]').val(item.label);
        $scope.editAppointmentsData.dataJobsite.contactphone = item.contactphone;
      }
      $scope.Input_value.jobsite = 'Select';
      if ($scope.detailAppointmentData.appointmentjobsites && $scope.detailAppointmentData.appointmentjobsites.id) {
        var item = _.where($scope.jobsitesByCustomer, {
          id: $scope.detailAppointmentData.appointmentjobsites.id
        });
        if(item.length > 0){
          $scope.Input_value.jobsite = item[0].label;
        }else{
          $scope.Input_value.jobsite = 'Select';
        }
      }
    });
  }
  $scope.updateAppointments = function() {
    $scope.editAppointmentsDataClone = angular.copy($scope.editAppointmentsData);
    var id = $scope.editAppointmentsDataClone.dataApp.id;
    $scope.editAppointmentsDataClone.arrivalwindow = $('#formAppointmentEdit input[name=arrivalwindowView]').val();
    $scope.editAppointmentsDataClone.dateofappt = $('#formAppointmentEdit input[name=dateofappt]').val();
    $scope.editAppointmentsDataClone.endarrivalwindow = $('#formAppointmentEdit input[name=endarrivalwindowView]').val();
    $scope.editAppointmentsDataClone.nothomeutil = $('#formAppointmentEdit input[name=nothomeutilView]').val();
    $scope.editAppointmentsDataClone.order_id = ($scope.order_idapp ? $scope.order_idapp.id : null);
    $scope.editAppointmentsDataClone.dataApp.order_id = ($scope.order_idapp ? $scope.order_idapp.id : null);
    $scope.editAppointmentsDataClone.dataApp.dateofappt = $scope.editAppointmentsDataClone.dateofappt;
    $scope.editAppointmentsDataClone.dataApp.appointmentgroup_id = $scope.editAppointmentsDataClone.dataApp.appointmentgroup_id[0];
    $scope.editAppointmentsDataClone.dataApp.arrivalwindow = $('#arrivalwindowView').val();
    $scope.editAppointmentsDataClone.dataApp.endarrivalwindow = $('#endarrivalwindowView').val();
    $scope.editAppointmentsDataClone.dataApp.nothomeutil = moment($scope.editAppointmentsDataClone.dataApp.nothomeutil, 'hh:mmA').format('HH:mm:ss');
    if ($scope.editAppointmentsDataClone.dataJobsite && $scope.editAppointmentsDataClone.dataJobsite.id) {
      $scope.dataTempJobSite = $scope.editAppointmentsDataClone.dataJobsite;
      $scope.editAppointmentsDataClone.dataJobsite = {};
      $scope.editAppointmentsDataClone.dataJobsite = $scope.dataTempJobSite;
    } else {
      $scope.editAppointmentsDataClone.dataJobsite = null;
    }
    $startTimeCheck = moment($scope.editAppointmentsDataClone.dataApp.arrivalwindow, 'hh:mmA').format('HH:mm:ss');
    $endTimeCheck = moment($scope.editAppointmentsDataClone.dataApp.endarrivalwindow, 'hh:mmA').format('HH:mm:ss');
    if ($startTimeCheck < '06:00:00' || $endTimeCheck > '22:00:00') {
      $cordovaToast.showLongTop('The appointment cannot be scheduled outside 6AM-10PM');
      return;
    }
    var check = validateTime($scope.editAppointmentsDataClone.dataApp.arrivalwindow, $scope.editAppointmentsDataClone.dataApp.endarrivalwindow);
    if (!check.status) {
      $cordovaToast.showLongTop('End time must be greater than start time');
      return;
    }
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.update(id, $scope.editAppointmentsDataClone).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $scope.closeTarget('#scheduleEditModal');
        document.getElementById("formAppointmentEdit").reset();
        $scope.editAppointmentsData = {};
        $scope.holdValueAddress.editAppointment = [];
        $scope.jobsiteshow = false;
        $scope.getListToSchedule();
      } else {
        $cordovaToast.showLongTop(data.msg);
      }
      //$scope.getAppointments();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.confrimAppointments = function(id, title, content) {
    $scope.deleteAppointmentsData = {
      id: id
    };
    var confirm = $.confirm(title, '<div class="text-content baseline">' + content + '</div>', {
      messageType: 'warning',
      titleIcon: 'remove',
      overlayTransparent: .75
    }, function() {
      $scope.deleteAppointments(id, confirm);
    });
  }
  $scope.deleteAppointments = function(id, confirm) {
    Appointments.destroy(id).success(function(data) {
      $scope.deleteAppointmentsData = {};
      if (data.status) {
        $.notification('<div class="text-content">' + data.msg + '</div>', {
          messageType: 'message-success',
          autoClose: true
        });
        confirm.switchStateDialog("close");
      } else {
        $.notification('<div class="text-content">' + data.msg + '</div>', {
          messageType: 'message-success',
          autoClose: true
        });
        confirm.switchStateDialog("close");
      }
      $scope.getAppointments();
    });
  }
  // Appointment Detail
  $scope.getDetailCustomer = function(id) {
    var flagsData = $scope.flags;
    $scope.detailCustomerData = {};
    Customers.showDetail(id).success(function(data) {
      $scope.detailCustomerData = data;
      $scope.detailCustomerData.mailto = $sce.trustAsHtml('<a href="mailto:' + $scope.detailCustomerData.email + '">' + $scope.detailCustomerData.email + '</a>');
      $scope.detailCustomerData.padphone1 = $sce.trustAsHtml('<a href="tel:' + $scope.detailCustomerData.phone_number + '">' + $scope.detailCustomerData.phone_number + '</a>');
      $scope.detailCustomerData.additionalPhone.length >= 1 ? $scope.detailCustomerData.padphone2 = $sce.trustAsHtml('<a href="tel:' + $scope.detailCustomerData.additionalPhone[0] + '">' + $scope.detailCustomerData.additionalPhone[0] + '</a>') : '';
      $scope.detailCustomerData.additionalPhone.length >= 2 ? $scope.detailCustomerData.padphone3 = $sce.trustAsHtml('<a href="tel:' + $scope.detailCustomerData.additionalPhone[1] + '">' + $scope.detailCustomerData.additionalPhone[1] + '</a>') : '';
      if ($scope.detailAppointmentData.appointmentjobsites) {
        $scope.detailAppointmentData.appointmentjobsites.ctPhoneHtml = $sce.trustAsHtml('<a href="tel:' + $scope.detailAppointmentData.appointmentjobsites.contactphone + '">' + $scope.detailAppointmentData.appointmentjobsites.contactphone + '</a>');
      }
      var addresses = $scope.detailCustomerData.street.split(',');
      $scope.zillow2({
        address: addresses[0],
        csz: $scope.detailCustomerData.city + ',' + $scope.detailCustomerData.state
      });
      $scope.phone_number_mobile1 = $scope.detailCustomerData.phone_number.replace(/[^0-9]/g, '');
      $scope.phone_number_additionalPhone = [];
      for (var i = 0; i < $scope.detailCustomerData.additionalPhone.length; i++) {
        $scope.phone_number_additionalPhone.push(String($scope.detailCustomerData.additionalPhone[i].phone.replace(/[^0-9]/g, '')));
      }
      $timeout(function() {
        $scope.setValueFlag($scope.detailCustomerData.flag_id);
      }, 2000)
    });
  }
  $scope.zillow = {};
  $scope.zillow2 = function(data) {
    Appointments.getZillow(data).success(function(data) {
      if (data.response && data.response.results && data.response.results.result) {
        var item = data.response.results.result;
        $scope.zillow.sold = item.lastSoldPrice;
        $scope.zillow.soldon = item.lastSoldDate;
        $scope.zillow.zestimate = item.zestimate ? item.zestimate.amount : 0;
        $scope.zillow.buildin = item.yearBuilt;
      } else {
        $scope.zillow = {};
      }
      $ionicLoading.hide();
    });
  }
  $scope.getDetailAppointment = function(id) {
    if(!parseInt(id) > 0){
       //$cordovaToast.showLongTop('Can not find this appointment !!!');
       console.log('Can not find this appointment !!!');
       return false;
     }
     $scope.numOfCol = 2;
     $scope.hideChangeApp = false;
     $scope.detailAppointmentData = {};
     $scope.allAppointmentGroupsData = [];
     $scope.allAppointmentTypesData = [];
     $ionicLoading.show({
      template: templateLoading
    });
     Appointments.show(id).success(function(data) {
      $ionicLoading.hide();
      if (data.isComplete) {
        $scope.numOfCol = 1;
        $scope.hideChangeApp = true;
        $scope.hideArrow = true;
      }
      if (data.mess_log.length > 0) {
        $scope.oppid = _.filter(data.mess_log, function(val) {
          return parseInt(val.opportunity_id) > 0;
        })[0].opportunity_id;
        $scope.mess_sendtodispath = data.mess_log[0].id;
        $scope.checkUserInDispath = data.checkUserInDispath;
      }
      data.mess_log.shift();
      $scope.mess_log = data.mess_log;
      $scope.detailAppointmentData = data;
      $scope.current_customertype_id = $scope.detailAppointmentData.customertype_id;
      $scope.detailAppointmentData.arrivalwindow = moment($scope.detailAppointmentData.arrivalwindow, 'HH:mm:ss').format("hh:mmA");
      $scope.detailAppointmentData.endarrivalwindow = moment($scope.detailAppointmentData.endarrivalwindow, 'HH:mm:ss').format("hh:mmA");
      $scope.detailAppointmentData.nothomeutil = moment($scope.detailAppointmentData.nothomeutil, 'HH:mm:ss').format("hh:mmA");
      $scope.appIsCancel = $scope.detailAppointmentData.is_cancel;
      $scope.oldAppFieldwoker = $scope.detailAppointmentData.fieldworker;
      $scope.oldAppPrefFieldwoker = $scope.detailAppointmentData.prefieldworker;
      $scope.old_arrivalwindow_time = $scope.detailAppointmentData.arrivalwindow;
      $scope.old_endarrivalwindow_time = $scope.detailAppointmentData.endarrivalwindow;
      $scope.oldDateOfAppDetail = moment($scope.detailAppointmentData.dateofappt, 'YYYY-MM-DD HH:mm:ss').format('MM/DD/YYYY');
      var customerID = $scope.detailAppointmentData.customer_id;
      $scope.getDetailCustomer(customerID);
      $scope.getAllAppointmentHistoryByCustomer(customerID);
      $scope.allAppointmentGroupsData = $scope.detailAppointmentData._appointmentgroups;
      _.each($scope.allAppointmentGroupsData, function(val) {
        _.each(val.types, function(item) {
          _.extend(item, {
            parent_id: val.id
          });
          $scope.allAppointmentTypesData.push(item);
          item.id == $scope.detailAppointmentData.appointmentgroup_id ? _.extend($scope.detailAppointmentData, {
            appointmentgroup_parent_id: val.id
          }) : '';
        });
      })
      $scope.allAppointmentTypesData = _.sortBy($scope.allAppointmentTypesData, 'id');
      $scope.detailAppointmentData.jobstatusCurrent = {
        id: $scope.detailAppointmentData.appointmentstatusess[$scope.detailAppointmentData.appointmentstatusess.length - 1].id,
        name: $scope.detailAppointmentData.appointmentstatusess[$scope.detailAppointmentData.appointmentstatusess.length - 1].name,
        bgcolor: $scope.detailAppointmentData.appointmentstatusess[$scope.detailAppointmentData.appointmentstatusess.length - 1].bgcolor,
        jobstatusNext: {
          appointment_id: $scope.detailAppointmentData.id,
          jobstatus_id: $scope.detailAppointmentData.appointmentstatusess[$scope.detailAppointmentData.appointmentstatusess.length - 1].nextstep_id,
        }
      }
      $scope.jobsitesByCustomerId(customerID);
      $scope.detailAppointmentData.dateofappt = Date.parseDate($scope.detailAppointmentData.dateofappt).dateFormat('MM/DD/YYYY');
      try {
        if (scope.appointments == null) {
          scope.initCtrl();
          scope.getLeadSource();
        }
      } catch (e) {
        console.log(e);
      }
      $scope.setTempDataViewApp();
      scope.setActionJob($scope.detailAppointmentData.appointmentstatusess.length);
      scope.getFieldWorkerByAppGroup();
      scope.getFieldWorker();
      scope.getBookingAgent();
      scope.renderDateFileMan('all');
      scope.captureOnMobile();
      $scope.setValueAppointmentType($scope.detailAppointmentData.appointmentgroup_id);
      $scope.setValuecustomerType($scope.detailAppointmentData.customertype_id);
      $scope.setValueFlexible($scope.detailAppointmentData.flexiblecustomer_id);
      $scope.setValueCallAhead($scope.detailAppointmentData.callahead_id);
      if ($scope.detailAppointmentData.files) {
        $scope.detailAppointmentData.files.forEach(function(value) {
          value.type = $scope.sortFiletypeAppointment(value.extension);
        })
      }
      $scope.countFile.photo = _.where($scope.detailAppointmentData.files, {
        type: 'Photo'
      }).length;
      $scope.countFile.pdf = _.where($scope.detailAppointmentData.files, {
        type: 'PDFs'
      }).length;
      $scope.countFile.other = _.where($scope.detailAppointmentData.files, {
        type: 'Other'
      }).length;
      $timeout(function() {
        $scope.setValueFieldWorker($scope.holdFieldWorkerOnApp.id);
        $scope.setValuePrefFieldWorker($scope.detailAppointmentData.prefieldworker);
      }, 2000);
      var dataApp = {};
      dataApp.id = id;
      $scope.clickOnAppHistory(dataApp);
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.changeAppointmentTypes = function() {
    Appointmentgroups.getallappointmenttypesbygroup($scope.detailAppointmentData.appointmentgroups_id).success(function(data) {
      if (data.length) {
        $scope.allAppointmentTypesData = data;
        $scope.detailAppointmentData.appointmentgroup_id = data[0].id;
      }
    });
  }
  $scope.getAllAppointmentHistoryByCustomer = function(id) {
    $scope.customer_id = id;
    $scope.allAppointmentHistoryData = [];
    Customers.getappointmenthistory(id).success(function(data) {
      $scope.customeraddress = data.customeraddress;
      $scope.dataJobsiteToAutocomplete = data.jobsitedata;
      $scope.dataCounterForAppDetail.count_estimate = data.count_estimate;
      $scope.dataCounterForAppDetail.count_invoice = data.count_invoice;
      $scope.jobsitedataView = [{
        id: '',
        name: 'All'
      }];
      if (data.data.length) {
        $scope.allAppointmentHistoryData = data.data;
        $scope.allAppointmentHistoryData.forEach(function(item) {
          item.files.forEach(function(row) {
            row.type = $scope.sortFiletypeAppointment(row.extension);
          })
          item.countPhoto = _.where(item.files, {
            type: 'Photo'
          }).length;
          item.countPdf = _.where(item.files, {
            type: 'PDFs'
          }).length;
          item.countUrl = _.where(item.files, {
            type: 'url'
          }).length;
          item.countOther = item.files.length - (item.countPhoto + item.countPdf + item.countUrl);
          item.customer_id = $scope.customer_id;
        });
      }
      if ($scope.dataAppointmentHistoryFileItem) {
        $scope.allAppointmentHistoryData.forEach(function(item) {
          if (item.id == $scope.dataAppointmentHistoryFileItem.id) $scope.dataAppointmentHistoryFileItem.files = item.files;
        });
      }
      $scope.initialJobsiteFilter = [""];
    });
  }
  $scope.fileFolderViewerSchedule = function(e) {
    var index = $(e.target).closest('li').index();
    var boxFileIndex = $(e.target).closest('.box-files').index();
    var nFileAbove = $(e.target).closest('.app-content-popup').find('.box-files:lt(' + boxFileIndex + ')').find('.lst-file > li').length;
    index = index + nFileAbove;
    $scope.filesViewerSchedule = [];
    for (var i = 0; i < $(e.target).closest('.app-content-popup').find('.lst-file > li').length; i++) {
      var itmData = JSON.parse($(e.target).closest('.app-content-popup').find('.lst-file > li').eq(i).attr('data-item'));
      var itm = {};
      itm.type = itmData.type;
      itm.name = itmData.name;
      itm.url = itmData.path +'?v='+ String(new Date().getTime())+Math.random().toString(36).substring(7);
      itm.id = itmData.id;
      $scope.filesViewerSchedule.push(itm);
    }
    $scope.openByGetTemplate('popupFileViewerSchedule', function(){
      fileFolderViewer('#popupFileViewerSchedule', index);
    });
  }
  $scope.initPlayAudio = function() {
    if ($scope.detailAppointmentData.recordingfile != null && $scope.detailAppointmentData.recordingfile != "") {
      var listTrack = [$scope.detailAppointmentData.recordingfile];
      if ($scope.detailAppointmentData.recordingfile.indexOf('###') >= 0) {
        listTrack = $scope.detailAppointmentData.recordingfile.split('###');
      }
      audioPlayerMultiTrack('#callRecordAudioArea', listTrack);
    }
    $scope.showTarget('#popupScheduleDetailCallRecording')
  }
  // $scope.getAllAppointmentHistoryByCustomer = function(id) {
  //     $scope.allAppointmentHistoryData = [];
  //     Customers.getappointmenthistory(id).success(function(data) {
  //         $('.f.tblloader').hide();
  //         if (data.length) {
  //             $scope.allAppointmentHistoryData = data;
  //             scope.renderDateFileMan('app');
  //         }
  //     });
  // }
  $scope.openAutocompleteFilter = function(className) {
    $scope.initialJobsiteFilter = $scope.selectJobIdArr;
    var ionAutocompleteElement = document.getElementsByClassName(className);
    angular.element(ionAutocompleteElement).controller('ionAutocomplete').fetchSearchQuery("", true);
    angular.element(ionAutocompleteElement).controller('ionAutocomplete').showModal();
    $timeout(function() {
      angular.element('.backdrop').removeClass('visible').removeClass('active');
    }, 1000);
  }
  $scope.autocomplete = {};
  $scope.filterAppoinmentHistory = function(query, isInitializing) {
    $scope.jobsitedata = [];
    $scope.jobsitedata.push({
      id: '',
      name: 'All',
      label: 'All'
    });
    $scope.jobsitedata.push({
      id: 'Estimates/Invoices not attached to appointment',
      name: 'Estimates/Invoices not attached to appointment',
      label: 'Estimates/Invoices not attached to appointment'
    });
    $scope.jobsitedata.push({
      id: 'Billing Address',
      name: 'Billing Address | ' + $scope.customeraddress.street,
      label: 'Billing Address | ' + $scope.customeraddress.street
    });
    _.each($scope.dataJobsiteToAutocomplete, function(item) {
      $scope.jobsitedata.push(item);
    })
    var returnValue = {
      items: []
    };
    $scope.jobsitedata.forEach(function(item) {
      if (item.name && $scope.selectJobIdArr.indexOf(item.id) < 0 && item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        returnValue.items.push(item);
      }
    });
    return returnValue;
  }
  $scope.onRemoveJobsite = function(callback) {
    var index = $scope.selectJobIdArr.indexOf(callback.item.id);
    $scope.selectJobIdArr.splice(index, 1);
    if ($scope.selectJobIdArr.length < 1) {
      $scope.selectJobIdArr = [''];
      $scope.initialJobsiteFilter = [''];
      $scope.filterJobsiteArr = [{
        id: '',
        name: 'All',
        label: 'All'
      }];
    }
    var indexA = _.findIndex($scope.filterJobsiteArr, {
      id: callback.item.id
    });
    $scope.filterJobsiteArr.splice(indexA, 1);
  }
  $scope.removeTagFilter = function(id) {
    if (id != '') {
      $scope.initialJobsiteFilter = [];
      if ($scope.filterJobsiteArr.length > 1) {
        var index = $scope.selectJobIdArr.indexOf(id);
        $scope.selectJobIdArr.splice(index, 1);
        var indexA = _.findIndex($scope.filterJobsiteArr, {
          id: id
        });;
        $scope.filterJobsiteArr.splice(indexA, 1);
      } else {
        $scope.selectJobIdArr = [''];
        $scope.filterJobsiteArr = [{
          id: '',
          name: 'All',
          label: 'All'
        }];
      }
      $scope.cancelButtonclickedMethod();
    }
  }
  $scope.jobsitedataView = [];
  $scope.filterJobsiteArr = [];
  $scope.onSelectJobsite = function(callback) {
    if (callback.item.id == '') {
      $scope.selectJobIdArr = [''];
      if (callback.selectedItems.length > 1) {
        $scope.initialJobsiteFilter = [''];
      }
      $scope.filterJobsiteArr = [{
        id: '',
        name: 'All',
        label: 'All'
      }];
    } else {
      if ($scope.selectJobIdArr.indexOf(callback.item.id) < 0) {
        $scope.selectJobIdArr.push(callback.item.id);
        var index = $scope.selectJobIdArr.indexOf('');
        if (index > -1) {
          $scope.selectJobIdArr.splice(index, 1);
          $scope.initialJobsiteFilter = $scope.selectJobIdArr;
        }
      }
      indexA = _.findIndex($scope.filterJobsiteArr, {
        id: callback.item.id
      });
      if (indexA < 0) {
        $scope.filterJobsiteArr.push(callback.item);
        var indexB = _.findIndex($scope.filterJobsiteArr, {
          id: ''
        });
        if (indexB > -1) {
          $scope.filterJobsiteArr.splice(indexB, 1);
        }
      }
      if ((callback.selectedItems.length == $scope.jobsitedata.length - 1) && $scope.selectJobIdArr.indexOf('') < 0) {
        $scope.selectJobIdArr = [''];
        $scope.initialJobsiteFilter = [''];
        $scope.filterJobsiteArr = [{
          id: '',
          name: 'All',
          label: 'All'
        }];
      }
    }
  }
  $scope.modelToItemMethodJobsiterFilter = function(modelValue) {
    $scope.jobsitedata = [];
    $scope.jobsitedata.push({
      id: '',
      name: 'All',
      label: 'All'
    });
    $scope.jobsitedata.push({
      id: 'Estimates/Invoices not attached to appointment',
      name: 'Estimates/Invoices not attached to appointment',
      label: 'Estimates/Invoices not attached to appointment'
    });
    $scope.jobsitedata.push({
      id: 'Billing Address',
      name: 'Billing Address | ' + $scope.customeraddress.street,
      label: 'Billing Address | ' + $scope.customeraddress.street
    });
    _.each($scope.dataJobsiteToAutocomplete, function(item) {
      $scope.jobsitedata.push(item);
    })
    for (var i = 0; i < $scope.jobsitedata.length; i++) {
      if ($scope.jobsitedata[i].id == modelValue) {
        return $scope.jobsitedata[i];
      }
    }
  };
  $scope.cancelButtonclickedMethod = function(callback) {
    $ionicLoading.show({
      template: templateLoading
    });
    Customers.changeJobsiteOnAppHistory($scope.selectJobIdArr, $scope.customer_id).success(function(data) {
      $ionicLoading.hide();
      if (data['error']) {
        $scope.allAppointmentHistoryData = {};
        if ($scope.selectJobIdArr.indexOf('Estimates/Invoices not attached to appointment') > -1 || $scope.selectJobIdArr.indexOf('') > -1) {
          $scope.showNoAttacRecored = true
        } else {
          $scope.showNoAttacRecored = false;
        }
      } else {
        if ($scope.selectJobIdArr.indexOf('Estimates/Invoices not attached to appointment') > -1 || $scope.selectJobIdArr.indexOf('') > -1) {
          $scope.showNoAttacRecored = true
        } else {
          $scope.showNoAttacRecored = false;
        }
        $scope.allAppointmentHistoryData = data;
      }
    });
  }
  $scope.openPopupETA = function(status) {
    if (status == 'to_enroute') {
      $scope.openByGetTemplate('popupPendingToEnroutemodal');
      //$scope.etatime = moment().format('hh:mmA');
    }
    if (status == 'to_working') {
      $scope.openByGetTemplate('popupAriveToWorkingmodal');
      //$scope.etatime = moment().format('hh:mmA');
    }
    $scope.currentStatusApp = status;
  }
  $scope.Revert_func = function() {
    popup = $ionicPopup.show({
      title: 'Finishing to Complete',
      template: 'Are you sure to Revert The Appointment?!',
      buttons: [{
        text: '<b>OK</b>',
        onTap: function(e) {
          popup.close();
          $scope.detailAppointmentData.jobstatusCurrent.name = 'Complete';
          $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext = {
            appointment_id: $scope.detailAppointmentData.id,
            jobstatus_id: 7
          }
          $scope.createAppointmentstatuses('to_complete');
        }
      }, {
        text: 'Cancel'
      }]
    });
  }
  $scope.changeAappointmentstatusess = function() {
    switch ($scope.detailAppointmentData.jobstatusCurrent.name) {
      case "Pending": // Pending to Enroute
      if ($scope.detailAppointmentData.callahead_id == NoCAId) {
        $scope.openPopupETA('to_enroute');
      } else {
        $scope.openByGetTemplate('popupPendingToEnrouteCAmodal');
      }
      break;
      case "EnRoute": // EnRoute to Arrived On Site
      $scope.currentStatusApp = 'to_arrived_on_site';
      $scope.openByGetTemplate('popupEnrouteToArivemodal');
      break;
      case "Arrived On Site": // Arrived On Site to Woking
      $scope.openPopupETA('to_working');
      break;
      case "Working": // Woking to Finishing
      // var template = '<input required type="text" class="full-w" name="statusworkingPopupETA" id="statusworkingPopupETA" value="" placeholder="">';
      $scope.openByGetTemplate('popupRemindersmodal');
      $scope.currentStatusApp = 'to_finish';
      break;
      case "Finishing": // Finishing to Complete
        if ($scope.showCheckList) {
          $ionicLoading.show({
            template: templateLoading
          });
          dataHtml.getTemplate('templates/dashboard/checklist/checklistPopupmodal.tpl').success(function(results) {
            $scope.dataAppHtml.checklistPopup = results;
            $ionicLoading.hide();
            $scope.$broadcast('checklist-popup', {
              appointment_id: $scope.detailAppointmentData.id,
              appointmentgroup_id: $scope.detailAppointmentData.appointmentgroup_id,
              customer_id: $scope.detailAppointmentData.customer_id,
              order_id: $scope.detailAppointmentData.order_id,
              fw_note: $scope.detailAppointmentData.fieldworkernote,
              customertype_id: $scope.detailAppointmentData.customertype_id,
              scope: scope
            });
          });
        } else {
          $scope.createAppointmentstatuses('to_complete');
        }
        break;
        // case "Complete": // Complete to Revert
        // popup = $ionicPopup.show({
        //     title: 'Finishing to Complete',
        //     template: 'Are you sure to Revert The Appointment?!',
        //     buttons: [{
        //         text: '<b>OK</b>',
        //         onTap: function (e) {
        //             popup.close();
        //             $scope.createAppointmentstatuses('to_complete');
        //         }
        //     }, {
        //         text: 'Cancel'
        //     }]
        // });
        // break;
      }
    }
    $scope.createAppointmentstatuses = function(status) {
      if (!$scope.accessChangeJobStatus) {
        $cordovaToast.showLongTop('Please wait');
        return false;
      }
      $scope.accessChangeJobStatus = false;
      if (status == 'to_finish' && $('#statusworkingPopupETA').val() == '') {
        $cordovaToast.showLongTop('Please insert required fill!!!');
        $scope.accessChangeJobStatus = true;
        return;
      }
      if (status == 'to_enroute') {
        var inputValue = moment($('#etatimePopupETA').val(), 'hh:mmA').format('h:mm a');
      } else if (status == 'to_working') {
        var inputValue = moment($('#etatimePopupETC').val(), 'hh:mmA').format('h:mm a');
      } else if (status == 'to_finish') {
        var inputValue = $('#statusworkingPopupETA').val();
      }
      if($scope.create_status_from_order == true && status =='to_complete'){
        var temp_data_create_app_status = {};
        temp_data_create_app_status.infor_attached = '';
        temp_data_create_app_status.jobstatus_id = '6';
        temp_data_create_app_status.appointment_id = $scope.data_from_order_check_list.appointment_id;
        var data_create_app_status = temp_data_create_app_status;
      }else{
        $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.infor_attached = '';
        if ($scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.jobstatus_id == '2') {
          var etatime_string = $('#creatAppStatusEta [name="etatime"]').val();
          if(etatime_string.length < 1){
            $cordovaToast.showLongTop('Invalid Time !');
            $scope.accessChangeJobStatus = true;
            return false;
          }
          $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.infor_attached = etatime_string;
        }
        if ($scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.jobstatus_id == '4') {
          var etctime_string = $('#creatAppStatusEtc [name="etctime"]').val();
          if(etctime_string.length < 1){
            $cordovaToast.showLongTop('Invalid Time !');
            $scope.accessChangeJobStatus = true;
            return false;
          }
          $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.infor_attached = etctime_string;
        }
        if ($scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.jobstatus_id == '5') {
          $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.infor_attached = $('#statusworkingPopupETA').val();
        }
        var data_create_app_status = $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext;
      }
      
      $ionicLoading.show({
        template: templateLoading
      });
      Appointmentstatuses.save(data_create_app_status).success(function(data) {
        $ionicLoading.hide();
        if (data.status) {
          switch ($scope.currentStatusApp) {
            case "to_enroute":
            $scope.closeTarget('#popupPendingToEnroutemodal');
            break;
            case "to_arrived_on_site":
            $scope.closeTarget('#popupEnrouteToArivemodal');
            break;
            case "to_working":
            $scope.closeTarget('#popupAriveToWorkingmodal');
            break;
            case "to_finish":
            $scope.closeTarget('#popupWorkingToFinishmodal');
            break;
          }
          $scope.accessChangeJobStatus = true;
          $scope.data_from_order_check_list = {};
          $scope.create_status_from_order = false;
          setTimeout(function() {
            $scope.current_job_status = status;
            $scope.current_job_inputValue = inputValue;
            scope.sendPushRoom(status, inputValue);
          }, 1500);
        } else {
          $cordovaToast.showLongTop(data.msg);
        }
      });
    }
    $scope.retrySentMessege = function() {
      setTimeout(function() {
        scope.sendPushRoom($scope.current_job_status, $scope.current_job_inputValue);
        $scope.closeTarget('#popupRetrySentMessegemodal');
      }, 200);
    }
    $scope.getSchedulesCustomerInfo = function(appoinmentID) {
      $scope.scheduleDetailAllowEdit = true;
      $scope.scheduleDetailAllowEditName = 'Edit';
      $scope.upload_to_appointment_id = appoinmentID;
      $ionicLoading.show({
        template: templateLoading
      })
      $scope.openByGetTemplate('scheduleDetailEdit');
      $timeout(function() {
        $scope.getDetailAppointment(appoinmentID);
      // $ionicScrollDelegate.$getByHandle('scrollAppointmentEdit').scrollTop();
      // dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentDetailsmodal.tpl').success(function(results) {
      //     $scope.dataAppHtml.appointmentDetail = results;
      //     dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentDetailsEditmodal.tpl').success(function(results) {
      //         $scope.dataAppHtml.appointmentDetailEdit = results;
      //         dataHtml.getTemplate('templates/dashboard/schedules/appointment/shedulesPopupAppointmentToolsmodal.tpl').success(function(results) {
      //             $scope.dataAppHtml.appointmentTools = results;
      //             $scope.getDetailAppointment(appoinmentID);
      //             $timeout(function() {
      //                 $scope.showTarget('#appointmentDetail');
      //                 $ionicScrollDelegate.$getByHandle('scrollAppointmentEdit').scrollTop();
      //             }, 500);
      //         })
      //     })
      // })
    }, 500);
      $scope.loadCriteria();
    }
    if ($scope.appointment_id != '') {
      $scope.getSchedulesCustomerInfo($scope.appointment_id);
    }
    $scope.allowEditscheduleDetail = function() {
      $scope.scheduleDetailAllowEdit = true;
      $scope.scheduleDetailAllowEditName = 'Save';
    }
    $scope.sortFiletypeAppointment = function(ext) {
      switch (ext.toLowerCase()) {
        case "bmp":
        case "BMP":
        case "gif":
        case "GIF":
        case "jpeg":
        case "JPEG":
        case "jpg":
        case "JPG":
        case "png":
        case "PNG":
        return "Photo";
        break;
        case "pdf":
        case "PDF":
        return "PDFs";
        case "url":
        return "url"
        default:
        return "Other";
        break;
      }
    }
    $scope.sizeName = function(n) {
      var convertSize = n / 1024;
      if (convertSize < 1024) {
        return (Math.round(convertSize)).toFixed(2) + 'KB';
      } else {
        var convertSize = convertSize / 1024;
        return (Math.round(convertSize)).toFixed(2) + 'MB';
      }
    }
    /* Change string format Datetime */
    $scope.changeDatetime = function(type, s) {
      if (s == null) return "";
      switch (type) {
        case "DT2D":
        var dateS = s.split(' ');
        return dateS[0];
        break;
        case "DT2T":
        return Date.parseDate(s);
        // var dateS = s.split(' ');
        // return dateS[1];
        break;
        default:
      }
    }
    $scope.loadNoteTasksData = function(id) {
      noteTaskScope.editNotetasks(id);
    }
  // by sinhdang
  $scope.appPopulateInfo = function(id) {
    $scope.detailAppointmentData.appointmentgroup_parent_id = _.where($scope.allAppointmentTypesData, {
      id: id
    })[0].parent_id;
    $scope.setValueAppointmentType(id);
    scope.getFieldWorkerByAppGroup();
  }
  $scope.switchView = function($viewForm, $viewBy) {
    scope.viewForm($viewForm, $viewBy);
  }
  $scope.upLoadFileMan = function(formValidate, dataFiles) {
    if (formValidate.$invalid || dataFiles.length == '0') {
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    }
    $scope.dataFiles = dataFiles;
    $scope.upLoadFileProgress($scope.dataFiles, 0);
  }
  $scope.upLoadFileProgress = function(files, index) {
    var item = files[index];
    var d = new Date();
    if (item.type == 'image/jpeg') {
      item.fullName = item.criterias1 + "-" + item.criterias2 + "-" + item.criterias3 + "-" + d.getTime() + "." + item.name.substr(item.name.lastIndexOf('.') + 1);
    } else {
      item.fullName = item.fullName + "_" + d.getTime() + "." + item.name.substr(item.name.lastIndexOf('.') + 1);
    }
    item.fullName = item.fullName.split('#').join('t');
    $scope.fileUploadData = {};
    $scope.fileUploadData.name = item.fullName;
    $scope.fileUploadData.type = item.type;
    $scope.fileUploadData.bucket = bucketName;
    $scope.fileUploadData.acl = aclConfig;
    $scope.fileUploadData.for = 'app';
    $scope.fileUploadData.appointment_id = $scope.upload_to_appointment_id;
    $scope.fileUploadData.customer_id = $scope.detailCustomerData.id;
    $ionicLoading.show({
      template: templateLoading
    });
    Login.getConfigFileUpload($scope.fileUploadData).success(function(data) {
      var Uoptions = {};
      Uoptions.fileKey = "file";
      Uoptions.fileName = data.folder + '/' + $scope.fileUploadData.name;
      Uoptions.mimeType = item.type;
      Uoptions.chunkedMode = false;
      Uoptions.headers = {
        connection: "close"
      };
      Uoptions.params = {
        "Key": data.folder + '/' + item.fullName,
        "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 {
          $scope.fileLocation = return_data.headers.Location;
        } catch (e) {
          $scope.jsonObject = xml2json.parser(return_data.response);
          $scope.fileLocation = $scope.jsonObject.postresponse.location;
        }
        item.locationFile = decodeURIComponent($scope.fileLocation);
        $scope.fileUploadData = {};
        $scope.addFileManager(item, index);
      }, function(err) {
        console.log(err);
        $ionicLoading.hide();
        $cordovaToast.showLongTop('Upload file ' + item.fullname + ' fail!!!');
      }, function(progress) {
        $ionicLoading.show({
          template: templateLoading
        });
      });
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.addFileManager = function(item, index) {
    item.customer_id = $scope.detailCustomerData.id;
    item.appointment_id = $scope.upload_to_appointment_id;
    item.phoneApp = true;
    if (item.type == 'image/jpeg') {
      item.extension = 'jpg';
    } else {
      item.extension = item.name.substr(item.name.lastIndexOf('.') + 1);
    }
    item.file_name = item.fullName;
    item.file_type = item.extension;
    item.file_size = item.size ? item.size : '';
    item.filedes = item.file_des ? item.file_des : '';
    var options = {
      fileName: item.fullName,
      fileKey: "file",
      params: item,
      mimeType: item.type,
      chunkedMode: false
    };
    options.headers = headers;
    $cordovaFileTransfer.upload(url_server + 'appointments/upLoadFileMan', item.localURL, options).then(function(e) {
      $ionicLoading.hide();
      if (index == $scope.dataFiles.length - 1) {
        $scope.files = [];
        $scope.getDetailAppointment(item.appointment_id);
      }
      var results = JSON.parse(e.response);
      if (results.status) {
        // var idx = _.findLastIndex($scope.files, {fullName: item.fullName});
        // $scope.files.splice(idx, 1);
        $ionicLoading.hide();
        $cordovaToast.showLongTop('Upload file ' + item.fullName + ' successful!!!');
        $scope.closeTarget('#popupAddScheduleDetailFileManagementDetail');
        $scope.closeTarget('#popupAppointmentDetailTakePictureOption');
        if (index < $scope.dataFiles.length - 1) {
          index++;
          $scope.upLoadFileProgress($scope.dataFiles, index);
        }
      } else {
        $cordovaToast.showLongTop(results.msg);
      }
    }, function(err) {
      console.log(err);
      $ionicLoading.hide();
      $cordovaToast.showLongTop('Upload file ' + item.fullName + ' fail!!!');
    }, function(progress) {
      $ionicLoading.show({
        template: templateLoading
      });
    });
  }
  $scope.checkFileType = function($fname) {
    var fileName = $fname;
    var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
    return ext;
  }
  $scope.upLoadOnMobile = function($file) {
    scope.upLoadOnMobile($file);
  }
  $scope.updateAppDetail = function() {
    if ((parseInt($scope.oldAppPrefFieldwoker) > 0) && ($scope.oldAppPrefFieldwoker == $scope.oldAppFieldwoker) && ($scope.holdFieldWorkerOnApp.id != $scope.oldAppFieldwoker)) {
      $scope.oldPrefFieldworkerLabel = _.where($scope.fieldWorkerByAppGroupList, {
        id: $scope.oldAppPrefFieldwoker
      })[0].name;
      dataHtml.getTemplate('templates/dashboard/schedules/appointment/schedulesPopupConfirmChangeFielworker.tpl').success(function(results) {
        $scope.dataAppHtml.schedulesPopupConfirmChangeFielworker = results;
        $scope.showTarget('#schedulesPopupConfirmChangeFielworker');
      });
    } else {
      $scope.startUpdateAppDetail();
    }
  }
  $scope.startUpdateAppDetail = function() {
    $scope.closeTarget('#schedulesPopupConfirmChangeFielworker');
    scope.updateAppDetail();
  };
  $scope.filterAppGroup = function(item) {
    return function(item) {
      if (item.parent_id > 0) {
        return true;
      }
      return false;
    };
  };
  $scope.$on('closeappointment', function(event, args) {
    //var finishConfirm = $.confirm("Finishing to Complete", '<div class="text-content baseline">Are you sure to change status Finishing to Complete?</div></div>', {}, function () {
      $scope.create_status_from_order = args.from_order;
      $scope.data_from_order_check_list = args;
      $scope.createAppointmentstatuses('to_complete');
      $scope.closeTarget('#checklistPopup');
      $scope.closeTarget('#popupScheduleDetailJobStatus');
      $scope.getListToSchedule();
      if (args.from_order) {
        $scope.$broadcast('reload_app_status', {
          action: 'reload_app_status'
        });
      }
    //finishConfirm.switchStateDialog("close");
    //});
    //finishConfirm.e.parent().parent().find('.close-title-button').addClass('dismis-popup');
    //finishConfirm.e.parent().parent().find('.close-title-button').unbind();
    // finishConfirm.e.parent().parent().find('.dismis-popup').click(function () {
    //finishConfirm.switchStateDialog("close");
    // openPopup('#popupAppointmentDetail');
    //})
    //finishConfirm.e.parent().parent().find('.button input').last().addClass('dismis-popup');
    //finishConfirm.e.parent().parent().find('.button input').last().unbind();
    //finishConfirm.e.parent().parent().find('.dismis-popup').click(function () {
    //finishConfirm.switchStateDialog("close");
    //openPopup('#popupAppointmentDetail');
    // })
    // $('#content2').hide();
    // $('#content').show();
    // $('#contentArea').show();
    //mo lai appointment tai day va set complete.
    //send complete 
  });
  //by thuandinh 
  $scope.get_appointmentHistory = function(id, date) {
    date = moment(date, 'MM-DD-YYYY').format('YYYY-MM-DD');
    $scope.getSchedulesCustomerInfo(id);
    if (page == 'scheduleapp.html') {
      $scope.loadAppointmentByDay(date);
      $scope.selectedDay = date;
    }
  }
  //on filemanager
  var click = 0;
  $scope.get_appointmentHistoryOnFilemanager = function(id, date) {
    click++;
    $timeout(function() {
      click = 0
    }, 500);
    if (click > 1) {
      $scope.get_appointmentHistory(id, date);
      $scope.getDetailAppointment(id);
      $scope.openByGetTemplate('appointmentFileManagement');
      $timeout(function() {
        $scope.closeTarget('#popupScheduleDetailFileManagement');
      }, 2000);
    }
  }
  $scope.show_appointmentHistoryOnFilemanager = function(data) {
    $scope.openByGetTemplate('popupScheduleDetailFileManagementDetailOfHistory');
    $scope.dataAppointmentHistoryFileItem = data;
    $scope.upload_to_appointment_id = data.id;
  }
  // for map app
  $scope.geocoder = null;
  $scope.objMap = null;
  $scope.initMapApp = function() {
    $scope.objMap = new google.maps.Map(document.getElementById('mapOnApp'), {
      zoom: 16,
      center: {
        lat: -34.397,
        lng: 150.644
      }
    });
    $scope.geocoder = new google.maps.Geocoder();
  }
  $scope.addressToMap = function(address) {
    if ($scope.geocoder == null) {
      jQuery('#mapOnApp').css({
        height: ($(window).outerHeight() - 120) + 'px'
      });
      $scope.initMapApp();
      setTimeout(function() {
        $('#addressToMap').parent().parent().parent().find('.close-title-button').click(function() {
          openPopup('#popupAppointmentDetail');
        });
      }, 100);
    }
    $scope.geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK) {
        $scope.objMap.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
          map: $scope.objMap,
          position: results[0].geometry.location
        });
      } else {
        closePopupById('popupappointmentMap');
        alert('Geocode was not successful for the following reason: ' + status);
        openPopup('#popupAppointmentDetail');
      }
    });
  }
  $scope.refreshAppointmentType = function(search) {
    var params = {
      search: search
    };
    $ionicLoading.show({
      template: templateLoading
    })
    Opportunities.getAppointmentType(params).success(function(data) {
      $ionicLoading.hide();
      startpage = false;
      var diff = differentArray(data, $scope.addAppointmentsData.appointmentgroup_id);
      $scope.AppointmentType = diff;
      $scope.rootAppointmentType = data;
      $(".modal-backdrop").removeClass('active');
      $scope.loadCriteria();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  };
  $scope.getUsers = function() {
    $scope.formData = {};
    $scope.grouptask = [];
    $scope.userFollow = [];
    var _param = {
      rows: 'All'
    }
    $ionicLoading.show({
      template: templateLoading
    });
    Groups.getSelect().success(function(data) {
      if (!startpage) ionicLoading.hide();
      $scope.grouptask = data;
      if ($scope.allUser == undefined) {
        $scope.allUser = [];
        Users.getPaging(_param).success(function(data) {
          $scope.getListToSchedule();
          _.each(data.data, function(val, index) {
            nick_name = val.first_name + ' ' + val.last_name;
            var _item = {
              id: val.id,
              screen_name: nick_name + ' - ' + val.positiontitles_name,
              name: nick_name,
              imgprofile: val.image_pic,
              email: val.email,
            }
            $scope.allUser.push(_item);
          });
        });
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  };
  $scope.getAssign = function($id_user) {
    $scope.formData = {};
    $scope.userFollow = [];
    $scope.formData.starttime = moment().add(0, 'days').format('MM/DD/YYYY');
    $scope.formData.endtime = moment().add(1, 'days').format('MM/DD/YYYY');
    $scope.formData.type = 'Downtime';
    $scope.formData.assign = _.where($scope.allUser, {
      id: parseInt($id_user)
    })[0];
    $('#holdTCAssign').val($scope.formData.assign.screen_name);
  }
  $scope.filterFollow = function($query) {
    var qStringUser = [];
    $scope.formData.assign == undefined ? qStringUser = $scope.allUser : qStringUser = _.filter($scope.allUser, function(val) {
      return val.id != parseInt($scope.formData.assign.id);
    });
    return $scope.allUser.filter(function(user) {
      return user.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
    });
  };
  // change assign
  $scope.onSelectCreate = function($item, $model, $label) {
    if (_.filter($scope.userFollow, function(val) {
      return parseInt(val.id) == parseInt($item.id);
    }).length > 0) {
      setTimeout(function() {
        $scope.$apply(function(val) {
          $('#holdTCAssign').val('');
          toastr.warning('User exits in Follower');
        });
      }, 1);
      return;
    }
  }
  $scope.createTask = function() {
    var objParam = _.extend(this.formData, {
      usersfollow: $scope.userFollow,
      starttime: $('#frmAddTaskDownTime input[name="starttime"]').val(),
      endtime: $('#frmAddTaskDownTime input[name="endtime"]').val(),
      fdate: conFig.fDatetoServer,
      type: 'Downtime' // type for option
    });
    $ionicLoading.show({
      template: templateLoading
    });
    Opportunities.createTask(objParam, currentIdLogin).success(function(data) {
      var message = data.msg;
      var url = url_site + '/tasks.html';
      Tasks.sendmail(data.id, 'createTask', parseInt(currentIdLogin), url).success(function(data) {
        Tasks.createHistory(data.id, data.comments).success(function(data) {
          $ionicLoading.hide();
          $scope.closeTarget('#popupAddScheduleDetailDowntime');
          $scope.showDowntimeTask($scope.userForcounterTask);
          $scope.userFollow = [];
          $scope.initialFollower = [];
          document.getElementById('frmAddTaskDownTime').reset();
          $cordovaToast.showLongTop(message);
        })
      }).error(function(data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Can\'t send mail!!!');
      });
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.getDataGroup = function(group_id) {
    $scope.formData.assign = '';
    $scope.userFollow = [];
    if (group_id == '') return;
    Tasks.getDataGroup(group_id).success(function(data) {
      $scope.userFollow = data.follow;
      $scope.formData.assign = data.assige;
    });
  }
  $scope.confrimListviewusers = function(id) {
    $scope.openByGetTemplate('confirmDeleteScheduleListView');
    $scope.deleteListviewusersData = {
      id: id
    };
  }
  $scope.deleteListviewusers = function() {
    $ionicLoading.show({
      template: templateLoading
    });
    Listviewusers.destroy($scope.deleteListviewusersData.id).success(function(data) {
      $ionicLoading.hide();
      $scope.deleteListviewusersData = {};
      if (data.status) {
        $scope.getSelectListviews();
        $scope.closeTarget("#confirmDeleteScheduleListView");
        $cordovaToast.showLongTop(data.msg);
      } else {
        $cordovaToast.showLongTop(data.msg);
      }
      //$scope.getListviewusers();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  //validate time picker
  // init app
  $scope.checkLogin = function() {
    return Login.checkLogin().success(function(data) {
      if (data.status == false) {
        // $window.location.href = url_login;
      } else {
        $scope.currentIdLogin = parseInt(data.status.id);
        current_ext = data.status.extension_phone;
        $scope.imagePath = pathToPublic + data.status.image_pic;
        scope.getLeadSource();
      }
    });
  }
  $scope.saveFile = function(path) {
    saveFile(path);
  }
  $scope.checkReloadCalendar = function() {
    Appointments.checkReloadCalendar({
      day: $scope.selectedDay,
      listviewid: $scope.listviewId.value,
      unavailablefieldwoker: $scope.viewUnavailableValue,
      arrDepart: $scope.arrDepart
    }).success(function(data) {
      $scope.countNewApp = parseInt(data.countApp);
      $scope.countNewTask = parseInt(data.countTask);
      if ($scope.countNewApp > $scope.numberOldApp || $scope.countNewTask > $scope.numberOldTask) {
        $scope.alertReload();
      }
      $scope.numberOldApp = $scope.countNewApp;
      $scope.numberOldTask = $scope.countNewTask;
    });
  }
  $scope.cancelAndRedoAppoiment = function(appoinmentId, currentStatus) {
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.cancelAndRedoAppoiment(appoinmentId, currentStatus).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $scope.appIsCancel = data.isCancel;
        // by thuanquach
        if ($scope.viewFromMap) {
          $scope.refreshPageFromApp();
        } else {
          $scope.loadAppointmentByDay($("#scheduleDayValue").val());
          $cordovaToast.showLongTop(data.msg);
        }
        // end by thuanquach
      } else {
        $cordovaToast.showLongTop(data.msg);
      }
    });
  }
  $scope.alertReload = function() {
    var confirm = $.confirm('Page reloading', '<div class="text-content baseline">' + 'The page is going to be reloaded. If you want to prevent the page from reloading, please click cancel.' + '</div>', {
      messageType: 'info',
      overlayTransparent: .75
    }, function() {
      confirm.switchStateDialog("close");
      $scope.loadAppointmentByDay($("#scheduleDayValue").val());
    });
  }
  $scope.getUserLogin = function() {
    return Login.getUserLogin().success(function(data) {
      if (data == false) {
        localStorage.setItem("login_status", "1");
        redirectTo('index.html');
      } else {
        $scope.imagePath = pathToPublic + data.image_pic;
        var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
        if ($.trim(displayname) == "") {
          $scope.displayname = "Hello, " + data.email;
        } else {
          $scope.displayname = "Hello, " + displayname;
        }
        $scope.currentIdLogin = parseInt(data.id);
        current_ext = data.extension_phone;
        $scope.imagePath = pathToPublic + data.image_pic;
        $('.dashboard > .tblloader').hide();
        $('#document').show();
        scope.getLeadSource();
        $scope.getUsers();
      }
    });
  }
  $scope.hideForFieldWorker = function() {
    if ($scope.roleName == $scope.isFieldinstaller || $scope.roleName == $scope.isSalesman) {
      return true;
    } else {
      return false;
    }
  }
  $scope.Input_value = {};
  $scope.redirectTo = function(url) {
    $ionicLoading.show({
      template: templateLoading
    });
    $timeout(function() {
      redirectTo(url);
    }, 1000)
  }
  $scope.redirectToChat = function(id) {
    if (parseInt(id) != parseInt($scope.currentIdLogin)) {
      $ionicLoading.show({
        template: templateLoading
      });
      $timeout(function() {
        redirectTo('chat.html#/board/chat/' + id + '_');
      }, 1000)
    }
  }
  $scope.openPopupViewPuchTime = function(item) {
    $scope.detailPunchTime = item;
    appDialogToggle('open', '#popupViewPunchTime');
  }
  $scope.popupAddAppointmentTasknote = function(fieldWorkerId) {
    $scope.$broadcast('send_fieldWorkerId', {
      id: fieldWorkerId
    });
    appDialogToggle('open', '#popupAddAppointmentTasknote');
  }
  $scope.popupEditTasknote = function(taskNotesId) {
    $ionicLoading.show({
      template: templateLoading
    });
    $timeout(function() {
      dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupTaskNoteEditmodal.tpl').success(function(results) {
        $scope.dataAppHtml.popupEditScheduleNote = results;
        $scope.$broadcast('send_taskNotesId', {
          id: taskNotesId
        });
      });
    }, 500)
  }
  $scope.popupAddTasknote = function(fieldWorkerId) {
    $scope.openByGetTemplate('addTaskNote');
    $scope.$broadcast('send_fieldWorkerId', {
      id: fieldWorkerId
    });
  }
  $scope.openPopupAddDowntimeTask = function() {
    $ionicLoading.show({
      template: templateLoading
    });
    $scope.openByGetTemplate('popupAddScheduleDetailDowntime');
    // dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupDowntimeTaskAddmodal.tpl').success(function(results) {
    //     $scope.dataAppHtml.addDowntimeTask = results;
    $timeout(function() {
      console.log($scope.userForcounterTask);
      $scope.formData.assign = _.where($scope.allUser, {
        id: parseInt($scope.userForcounterTask)
      })[0];
      $scope.fromDate = moment().format(conFig.formatDate.toUpperCase());
      $scope.toDate = moment().add(1, 'days').format(conFig.formatDate.toUpperCase());
      $scope.initialFollower = [];
    }, 500);
    // })
  }
  $scope.showDowntimeTask = function(fieldworkerId) {
    $scope.userForcounterTask = fieldworkerId;
    $scope.dataShowDowntimeTask = {};
    $scope.dataShowDowntimeTask.fieldworkerId = fieldworkerId;
    $scope.openByGetTemplate('popupScheduleDetailDowntime');
    Appointments.showDowntimeTask($scope.dataShowDowntimeTask).success(function(data) {
      $ionicLoading.hide();
      $scope.dataTaskByUser = data.data;
      $scope.counterTask = data.count;
      $scope.counterTask = data.count;
      $('#downtimeUserName').html(data.userNameLabel);
    });
  }
  if ($scope.tier.t1) {
    $scope.getNameAndPositionUserById = function(id, arr) {
      Users.nameAndPositionUserById(id).success(function(data) {
        arr['fieldworker'] = data;
        $scope.$broadcast('addNoteTaskSchedule', arr);
      });
      $('#addNoteTaskSchedule').trigger('click');
    }
  }
  $scope.openPopupDetailSchedule = function(item) {
    $scope.currentSelectedFieldworker = item.fieldworkerId;
    $scope.openByGetTemplate('scheduleContent');
    $scope.detailSchedule = item;
    $scope.detailSchedule.appDate = $("#scheduleDayValue").val();
    $scope.selectedDay = $scope.detailSchedule.appDate;
    // $timeout(function() {
    //     dataHtml.getTemplate('templates/dashboard/schedules/shedulesContentDetailsmodal.tpl').success(function(results) {
    //         $scope.dataAppHtml.scheduleContent = results;
    //         $scope.showTarget('#scheduleContent');
    //         $ionicLoading.hide();
    //     })
    // }, 500);
  }
  $scope.changeTimeRangeSchedule = function(e) {
    var $input = $(e.target).closest('li').show().addClass('opening').find('.time-change > input');
    var startTime = $input.attr('data-time-start');
    var endTime = $input.attr('data-time-end');
    var mStartTime = convertTimeformat('24', startTime).h * 60 + convertTimeformat('24', startTime).m;
    var mEndTime = convertTimeformat('24', endTime).h * 60 + convertTimeformat('24', endTime).m;
    var slider = $input.slider({
      range: true,
      min: 6 * 60,
      max: 22 * 60,
      step: 15,
      value: [mStartTime, mEndTime]
    });
    slider.on('slide', function() {
      var value = slider.data('slider').getValue();
      var time24Min = convertMinsToTime(value[0]);
      var time12Min = convertTimeformat('12', time24Min).time12;
      var time24Max = convertMinsToTime(value[1]);
      var time12Max = convertTimeformat('12', time24Max).time12;
      $(e.target).closest('li').addClass('changing');
      $(slider.data('slider').$element).attr('data-time-start-change', time12Min);
      $(slider.data('slider').$element).siblings('.control').find('.label-time-start-change').text(time12Min);
      $(slider.data('slider').$element).attr('data-time-end-change', time12Max);
      $(slider.data('slider').$element).siblings('.control').find('.label-time-end-change').text(time12Max);
    });
  }
  $scope.closeTimeRangeSchedule = function(e) {
    $(e.target).closest('li').removeClass('opening changing');
    var slider = $(e.target).closest('li').find('.time-change > input').data('slider');
    slider.refresh();
  }
  $scope.updateTimeRangeSchedule = function(e, type) {
    var $input = $(e.target).closest('li').find('.time-change > input');
    var slider = $input.data('slider');
    var params = {};
    params.start = moment($input.attr('data-time-start-change'), 'hh:mm A').format('HH:mm:ss');
    params.end = moment($input.attr('data-time-end-change'), 'hh:mm A').format('HH:mm:ss');
    params.type = type;
    params.appId = $input.attr('data-appt-id');
    params.day = $scope.selectedDay;
    params.app = true;
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.appointmentCellChange(params.appId, params).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $(e.target).closest('li').removeClass('opening changing');
        slider.destroy();
        // $(e.target).closest('li').find('.mark-start > span').html(moment(params.start,'HH:mm:ss').format('hh:mmA'));
        // $(e.target).closest('li').find('.mark-end > span').html(moment(params.end,'HH:mm:ss').format('hh:mmA'));
        $scope.loadAppointmentByDay($("#scheduleDayValue").val(), 'inDetail');
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.autocompleteList = {};
  $scope.autocompleteList.appType = [];
  $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.formData.assign.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.filterAppType = function(query) {
    var returnValue = {
      items: []
    };
    if (query.length) {
      var params = {
        search: query
      };
      $scope.rootAppointmentType.forEach(function(item) {
        if ($scope.autocompleteList.appType.indexOf(item.id) < 0) {
          if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            returnValue.items.push(item);
          } else if (item.id.indexOf(query) > -1) {
            returnValue.items.push(item);
          }
        }
      });
    }
    return returnValue;
  };
  $scope.filterOrder = function(query, cusId) {
    var returnValue = {
      items: []
    };
    var params = {
      search: query,
      customer_id: cusId
    };
    $scope.autocompleteList.dataOrder = [];
    Orders.getSelect2(params).success(function(data) {
      $scope.rootOrder = data;
      $scope.rootOrder.forEach(function(item) {
        if ($scope.autocompleteList.dataOrder.indexOf(item.id) < 0) {
          if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            returnValue.items.push(item);
          } else if (item.id.indexOf(query) > -1) {
            returnValue.items.push(item);
          }
        }
      });
      $scope.click_on_working_invoice = true;
    })
    return returnValue;
  };
  $scope.setValueForInputAppType = function(modelValue) {
    for (var i = 0; i < $scope.rootAppointmentType.length; i++) {
      if ($scope.rootAppointmentType[i].id == modelValue) {
        return $scope.rootAppointmentType[i];
      }
    }
    return {};
  };
  $scope.initialOrderId = [];
  $scope.setValueForInputOrderId = function(modelValue) {
    for (var i = 0; i < $scope.rootOrder.length; i++) {
      if ($scope.rootOrder[i].id == modelValue) {
        $scope.autocompleteList.dataOrder = $scope.order_idapp;
        return $scope.rootOrder[i];
      }
    }
    return {};
  };
  $scope.clickOnItemAppType = function(callback) {
    $scope.editAppointmentsData.dataApp.appointmentgroup_id = [callback.item.id];
    $scope.getfieldworkerByAppType($scope.editAppointmentsData.dataApp.appointmentgroup_id);
  }
  $scope.clickOnItemOrder = function(callback) {
    if (!$scope.editAppointmentsData.order_id) {
      $scope.editAppointmentsData.order_id = [];
    }
    if ($scope.click_on_working_invoice) {
      $scope.changeOrderapp(callback.item, '');
    }
  }
  $scope.locationChangeEditApp = function(location) {
    $scope.editAppointmentsData.dataJobsite.city = location['locality'];
    $scope.editAppointmentsData.dataJobsite.state = location['administrative_area_level_1'];
    $scope.editAppointmentsData.dataJobsite.zipcode = location['postal_code'];
  }
  $scope.initialFollower = [];
  $scope.setValueForFollower = function(modelValue) {
    for (var i = 0; i < $scope.allUser.length; i++) {
      // console.log($scope.allUser[i].id,modelValue)
      if ($scope.allUser[i].id == modelValue) {
        // data={id:$scope.rootSupplieritems[i].id,name:$scope.rootSupplieritems[i].name};
        return $scope.allUser[i];
      }
    }
    return {};
  };
  $scope.onSelectFollower = function(callback) {
    if ($scope.userFollow.indexOf(callback.item) < 0) $scope.userFollow.push(callback.item);
    // console.log($scope.userFollow);
  }
  $scope.onRemoveFollower = function(callback) {
    if ($scope.roleName == $scope.isSalesman || $scope.roleName == $scope.isFieldinstaller) {
      return false;
    }
    var index = $scope.userFollow.indexOf(callback.item);
    $scope.userFollow.splice(index, 1);
    // console.log($scope.userFollow);
  }
  $scope.appointmentHistory = {};
  $scope.openPopupAppointmentHistory = function(officeapptnote, fieldworkernote) {
    $scope.appointmentHistory.officeapptnote = officeapptnote;
    $scope.appointmentHistory.fieldworkernote = fieldworkernote;
    appDialogToggle('open', '#popupAppointmentHistory');
  }
  $scope.scrollHandle = function(positionID, style, offset) {
    // $location.hash(positionID); //set the location hash
    // var handle = $ionicScrollDelegate.$getByHandle('popupAppointment' + style);
    // handle.anchorScroll(true);
    // $timeout(function() {
    //     var top = handle.getScrollPosition().top - 30;
    //     // console.log(top);
    //     handle.scrollTo(0, top, false);
    // }, 500);
  }
  $scope.validateForm = function(formValidate, style) {
    $('#contactphone').trigger('input');
    // $ionicLoading.show({
    //     template: templateLoading
    // });
    var exitLoop = false;
    if (formValidate.$invalid) {
      $ionicScrollDelegate.$getByHandle('scrollAppointment' + style).scrollTop();
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      // // console.log(formValidate.$error.required[0].$name);
      // angular.forEach(formValidate.$error, function(item) {
      //     if (!exitLoop) {
      //         var id = item[0].$name;
      //         // console.log(id);
      //         $location.hash(id); //set the location hash
      //         var handle = $ionicScrollDelegate.$getByHandle('popupAppointment' + style);
      //         handle.anchorScroll(true);
      //         exitLoop = true;
      //         $timeout(function() {
      //             // console.log(handle.getScrollPosition());
      //             var top = handle.getScrollPosition().top - 170;
      //             // console.log(top);
      //             handle.scrollTo(0, top, true);
      //             $ionicLoading.hide();
      //             //$cordovaToast.showLongTop('Please fill all the required information.!!!');
      //         }, 1000);
      //     }
      // })
      return;
    };
    // if (style == 'Add') {
    //     $scope.createAppointments();
    // } else {
    //     $scope.updateAppDetail();
    // }
    if (style == 'Add' || style == 'AddFromOpp') {
      $scope.createAppointments(style);
    } else if (style == 'EditAppToSchedule') {
      $scope.updateAppointments();
    } else {
      $scope.updateAppDetail();
    }
  }
  $scope.openPopupFileManagerment = function(typeId) {
    $scope.sortAppointmentFile.type = typeId;
    $scope.openByGetTemplate('appointmentFileManagement');
  }
  $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) {
      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
    });
    if ($scope.uploadType == 'takePicture') {
      $scope.openPopupAddFile($scope.detailAppointmentData.id)
    }
  }
  $scope.openPicker = function() {
    var options = {
      maximumImagesCount: 50,
      width: 0,
      height: 0,
      quality: 100
    };
    $cordovaImagePicker.getPictures(options).then(function(results) {
      results.forEach(function(itm) {
        var filename = itm.substr(itm.lastIndexOf('/') + 1);
        $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 });
        // });
        if ($scope.uploadType == 'takePicture') {
          $scope.openPopupAddFile($scope.detailAppointmentData.id)
        }
      })
    });
  }
  $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,
      correctOrientation: true
    };
    // $timeout(function() {
      $cordovaCamera.getPicture( ).then(function(imageData) {
        var filename = imageData.substr(imageData.lastIndexOf('/') + 1);
        $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 });
      // });
      if ($scope.uploadType == 'takePicture') {
        $scope.openPopupAddFile($scope.detailAppointmentData.id)
      }
    }, function(err) {
      $cordovaToast.showLongTop(err);
      console.log(err);
    });
    // }, 500)
  }
  $scope.filePicker = function(style) {
    // 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);
        $scope.files.push({
          name: filename,
          type: type,
          localURL: path
        });
        $scope.openPopupAddFile($scope.detailAppointmentData.id);
      //if error change picker for android
    }, function(err) {
      fileChooser.open(function(uri) {
        window.resolveLocalFileSystemURL(uri, function(fileObj) {
          var path = fileObj.nativeURL;
          fileObj.file(function(data) {
            var type = data.type;
            console.log(type);
            var filename = name;
            switch (type) {
              case 'image/jpeg':
              filetype = 'images';
              break;
              case 'application/pdf':
              filetype = 'pdf';
              break;
              case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
              case 'application/vnd.ms-excel':
              case 'text/comma-separated-values':
              filetype = 'excel';
              break;
              case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
              case 'application/msword':
              filetype = 'word';
              break;
              case 'video/mp4':
              case 'video/quicktime':
              filetype = 'video';
              break;
              default:
              filetype = 'others';
              break;
            }
            $scope.files.push({
              name: filename,
              type: type,
              localURL: path,
              filetype: filetype
            });
            if ($scope.uploadType == 'takePicture') {
              $scope.openPopupAddFile($scope.detailAppointmentData.id)
            }
          })
        }, function(errer) {
          $cordovaToast.showLongTop(errer.message);
        });
      }, function(err) {
        $cordovaToast.showLongTop(err);
      });
    });
    // }, 500)
  }
  $scope.removeFile = function(idx) {
    $scope.files.splice(idx, 1);
  }
  $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.filterFiles = function($files) {
    var $newFiles = new Array();
    var $isAll = true;
    for (var i = 0; i < $files.length; i++) {
      var $ext = $scope.sortFiletypeAppointment($files[i].extension);
      if ($scope.filetypeAppointment == $ext) {
        $newFiles.push($files[i]);
        $isAll = false;
      }
    }
    if ($isAll) {
      return $files;
    } else {
      return $newFiles;
    }
  }
  $scope.createZipFile = function(dataItem) {
    var _directory = '/upload/customers/' + dataItem.customer_id + '/appointment/' + dataItem.files[0].appointment_id;
    var _full_filename = dataItem.files[0].appointment_id + '.zip';
    var _file_names = $scope.filterFiles(dataItem.files);
    var _data = {
      file_names: _file_names,
      directory: _directory,
      full_filename: _full_filename,
    }
    $ionicLoading.show({
      template: templateLoading
    });
    Customerfiles.zipFilesAndDownload(_data).success(function(res) {
      if (parseInt(res)) {
        $scope.downloadFile(_data.directory + '/appointment' + _full_filename);
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $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);
      console.log('then');
      $cordovaToast.showLongTop('Download Successful!!! Target: ' + result.fullPath);
    }, function(err) {
      $ionicLoading.hide();
      console.log(err);
      console.log('err');
    }, function(progress) {
      console.log('progress');
    });
  }
  $scope.keypress = function(delegate, style) {
    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.downTimer(delegate, style);
  };
  $scope.downTimer = function(delegate, style) {
    $scope.myTime = setInterval(function() {
      $scope.coundown--;
      if ($scope.coundown <= 0) {
        clearInterval($scope.myTime);
        if (style == "searchOrder") {
          $scope.refreshOrdersapp($scope.autocompleteList.searchOrder, $scope.detailAppointmentData.order_id);
          return;
        }
        // if ($scope.search.Text.length > 0) {
        //     var params = {
        //         search: $scope.search.Text
        //     };
        //     $ionicLoading.show({
        //         template: templateLoading
        //     });
        //     Appointments.searchAppointment(params).success(function(data) {
        //         // var diff = differentArray(data, $scope.searchResult);
        //         $scope.searchResult = data;
        //         $ionicLoading.hide();
        //         $ionicScrollDelegate.$getByHandle(delegate).scrollTop(true);
        //     })
        // }
      }
    }, 100);
  }
  $scope.setValueForSelectTitleInRootDataById = function(id, type) {
    switch (type) {
      case 'callaheads':
      var item = _.where($scope.callaheads, {
        id: id
      });
      if (item.length > 0) $('input[name=seletedCallAheadName]').val(item[0].name);
      break;
      case 'frefieldworker':
      var item = _.where($scope.fieldworkerSelect, {
        id: id
      });
      if (item[0]) $('input[name=seletedPrefFieldwokerName]').val(item[0].name);
      break;
      case 'customertypes':
      var item = _.where($scope.customertypes, {
        id: id
      });
      if (item.length > 0) $('input[name=selectedCusTypeName]').val(item[0].name);
      break;
      case 'flexiblecustomers':
      var item = _.where($scope.flexiblecustomers, {
        id: id
      });
      if (item.length > 0) $('input[name=selectedFlexName]').val(item[0].name);
      break;
      case 'jobsite':
      var item = _.where($scope.jobsitesByCustomer, {
        id: id
      });
      if (item) $('input[name=selectedJobsiteName]').val(item.label);
      $scope.editAppointmentsData.dataJobsite.contactphone = item.contactphone;
      break;
    }
  };
  $timeout(function() {
    $scope.classDevice = isiOs ? 'ios' : 'android';
    // console.log($scope.classDevice);
  }, 2000)
  $scope.showEstimateOption = function() {
    $scope.openByGetTemplate('optionScheduleEstimateInvoiceManagerment');
    //popup = $scope.openIonicPopup('templates/dashboard/schedules/appointment/schedulesPopupEstimateInvoiceToolsmodal.tpl', 'Estimate / Invoice Managerment');
  }
  $scope.filterScheduleForSearch = function(query) {
    if (query == '') {
      return;
    }
    var returnValue = {
      items: []
    };
    $scope.coundown = 10;
    if ($scope.myTimer != null) clearInterval($scope.myTimer);
    $scope.myTimer = setInterval(function() {
      $scope.coundown--;
      if ($scope.coundown <= 0) {
        $ionicLoading.show({
          template: templateLoading
        });
        clearInterval($scope.myTimer);
        var params = {
          rows: 50,
          current_page: 1,
          search: query,
          showuser: 0
        };
        $ionicLoading.show({
          template: templateLoading
        });
        $('#temp-autocompletetemp-autocomplete .none-result').css('display', 'none');
        Appointments.searchAppointment(params).success(function(data) {
          if (data.length) {
            $scope.rootDatasSchedule = data;
            $scope.rootDatasSchedule.forEach(function(item) {
              returnValue.items.push(item);
            })
          }
          // else{
          //     messagebox('fail', '', 'There are no appointments match the keyword.');
          // }
          $timeout(function() {
            $ionicLoading.hide();
          }, 200);
          if (returnValue.items.length > 0) {
            $('#temp-autocomplete .none-result').css('display', 'none');
          } else {
            $('#temp-autocomplete .none-result').css('display', 'block');
          }
        })
      }
    }, 100);
    return returnValue;
  }
  $scope.selectScheduleFormSearch = function(callback) {
    $scope.getSchedulesCustomerInfo(callback.item.id);
  }
  $scope.showAppointmentHistoryDetail = [];
  $scope.checkAppointmentHistoryDetail = function(idx) {
    $scope.showAppointmentHistoryDetail[idx] = $scope.showAppointmentHistoryDetail[idx] == 1 ? 0 : 1;
    $ionicScrollDelegate.$getByHandle('').resize();
  }
  $scope.openAutocomplete = function(className) {
    dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupAppointmentSearchmodal.tpl').success(function(results) {
      $scope.dataAppHtml.schedulesSearch = results;
    });
    $timeout(function() {
      var ionAutocompleteElement = document.getElementsByClassName(className);
      angular.element(ionAutocompleteElement).controller('ionAutocomplete').fetchSearchQuery("", true);
      angular.element(ionAutocompleteElement).controller('ionAutocomplete').showModal();
      $timeout(function() {
        angular.element('.backdrop').removeClass('visible').removeClass('active');
      }, 1000);
    }, 500)
  }
  $scope.changeDateOnAppDetail = function() {
    if ($scope.oldDateOfAppDetail != $scope.detailAppointmentData.dateofappt) {
      $scope.arrIdToInstallSecret = _.pluck(_.filter($scope.allAppGroupData, function(x) {
        return (parseInt(x.parent_id) > 0 && x.name == 'Door or Section Installation') || (parseInt(x.parent_id) > 0 && x.name == 'Installation Team Service Call') || (parseInt(x.parent_id) > 0 && x.name == 'Home Owner Door Installation');
      }), 'id');
      $scope.posInInstallSecret = $scope.arrIdToInstallSecret.indexOf($scope.detailAppointmentData.appointmentgroup_id);
      if ($scope.posInInstallSecret > -1) {
        $scope.detailAppointmentData.fieldworker = '3793';
        $scope.holdFieldWorkerOnApp = _.where($scope.fieldWorkerByAppGroup, {
          id: '3793'
        })[0].id;
        return;
      }
      $scope.arrIdToSecretSecret = _.pluck(_.filter($scope.allAppGroupData, function(x) {
        return (parseInt(x.parent_id) == 0 && x.name == 'Easy Sales') || (parseInt(x.parent_id) == 0 && x.name == 'Moderate Sales') || (parseInt(x.parent_id) == 0 && x.name == 'New Door Estimate') || (parseInt(x.parent_id) == 0 && x.name == 'Challenging Sales') || (parseInt(x.parent_id) == 0 && x.name == 'WMA') || (parseInt(x.parent_id) == 0 && x.name == 'Yearly Tune Up Program') || (parseInt(x.parent_id) == 0 && x.name == 'Free Service') || (parseInt(x.parent_id) == 0 && x.name == 'Pre-Sold Regular Service Appt') || (parseInt(x.parent_id) == 0 && x.name == 'Pre-Sold Ordered Service Appt');
      }), 'id');
      $scope.arrIdToSecretSecretParent = [];
      _.each($scope.arrIdToSecretSecret, function(val) {
        $scope.miniarr = _.pluck(_.filter($scope.allAppGroupData, function(x) {
          return (parseInt(x.parent_id) == val);
        }), 'id');
        $scope.arrIdToSecretSecretParent = $scope.arrIdToSecretSecretParent.concat($scope.miniarr);
      })
      $scope.posInSecretSecret = $scope.arrIdToSecretSecretParent.indexOf($scope.detailAppointmentData.appointmentgroup_id);
      if ($scope.posInSecretSecret > -1) {
        $scope.detailAppointmentData.fieldworker = '3779';
        $scope.holdFieldWorkerOnApp = _.where($scope.fieldWorkerByAppGroup, {
          id: '3779'
        })[0].id;
        return;
      }
      $scope.arrIdToDefault = _.pluck(_.filter($scope.allAppGroupData, function(x) {
        return (parseInt(x.parent_id) == 0 && x.name == 'Non Direct Amarr Orders') || (parseInt(x.parent_id) == 0 && x.name == 'Amarr Special Order');
      }), 'id');
      $scope.arrIdToarrIdToDefaultParent = [];
      _.each($scope.arrIdToDefault, function(val) {
        $scope.miniarrDefault = _.pluck(_.filter($scope.allAppointmentTypesData, function(x) {
          return (parseInt(x.parent_id) == val);
        }), 'id');
        $scope.arrIdToarrIdToDefaultParent = $scope.arrIdToarrIdToDefaultParent.concat($scope.miniarrDefault);
      })
      $scope.posInDefault = $scope.arrIdToarrIdToDefaultParent.indexOf($scope.detailAppointmentData.appointmentgroup_id);
      if ($scope.posInDefault > -1) {
        $scope.detailAppointmentData.fieldworker = $scope.oldFieldworkerAppDetail;
        $scope.holdFieldWorkerOnApp = $scope.oldFieldworkerAppDetail;
      }
    }
  }
  $scope.$watch('detailAppointmentData.dateofappt', function(value) {
    if ($scope.setTime) {
      $scope.changeDateOnAppDetail();
    }
  })
  $scope.$on('openFileManager', function(event, data) {
    $scope.detailCustomerData = {};
    $scope.detailCustomerData.id = data.customer_id;
    $scope.openByGetTemplate('popupScheduleDetailFileManagement');
    $scope.getAllAppointmentHistoryByCustomer($scope.detailCustomerData.id);
    $scope.loadCriteria();
  })
  $scope.dataRename = {};
  $scope.getNameFile = function(id) {
    $ionicLoading.show({
      template: templateLoading
    });
    $scope.dataRename.id = id;
    Customerfiles.getNameFile({
      id: id
    }).success(function(data) {
      $ionicLoading.hide();
      $scope.dataRename.name = data;
      $scope.oldNameFile = data;
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.reName = function() {
    if ($scope.oldNameFile == $scope.dataRename.name) {
      $scope.closeTarget('#popupScheduleDetailFileManagementName')
      return;
    }
    $ionicLoading.show({
      template: templateLoading
    });
    Customerfiles.reName($scope.dataRename).success(function(data) {
      $ionicLoading.hide();
      $scope.closeTarget('#popupScheduleDetailFileManagementName');
      if (data.status) {
        $scope.dataRename = {};
        $scope.getAllAppointmentHistoryByCustomer($scope.detailCustomerData.id);
        $cordovaToast.showLongTop(data.msg);
      } else {
        $cordovaToast.showLongTop(data.msg);
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.fileDelete = {};
  $scope.confirmDeleteFile = function(data) {
    $scope.fileDelete.id = data.id;
    $scope.fileDelete.name = data.name;
    $scope.showTarget('#popupScheduleDetailFileManagementDelete');
  }
  $scope.deleteFile = function() {
    $ionicLoading.show({
      template: templateLoading
    });
    Customerfiles.deleteFile({
      id: $scope.fileDelete.id
    }).success(function(data) {
      $ionicLoading.hide();
      $scope.closeTarget('#popupScheduleDetailFileManagementDelete');
      if (data.status) {
        $scope.fileDelete = {};
        $scope.getAllAppointmentHistoryByCustomer($scope.detailCustomerData.id);
        $cordovaToast.showLongTop(data.msg)
      } else {
        $cordovaToast.showLongTop(data.msg)
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  // end edit
  //by thuanquach
  $scope.$on('openAppDetailFromMap', function(event, args) {
    $scope.loadCriteria();
    $scope.viewFromMap = true;
    $scope.loadListAppointment = true;
    $scope.getSchedulesCustomerInfo(args.id);
  });
  $scope.refreshPageFromApp = function() {
    if ($scope.viewFromMap) {
      $scope.$emit('refreshMap', {
        action: "refreshMap"
      });
    }
  }
  // end
  //    role
  $scope.removeItemsAutocomplete = function(callback, type) {
    $scope.editAppointmentsData.order_id = [];
  }
  $scope.viewFileWithType = function(type) {
    $scope.filetypeAppointment = type;
    $scope.openByGetTemplate('popupScheduleDetailFileManagement');
  }
  $scope.beforeRidirectToDispathRoom = function() {
    if ($scope.checkUserInDispath) {
      redirectTo('chat.html?room_id=2&message=' + $scope.mess_sendtodispath + '&opp_id=' + $scope.oppid + '#/board/chat')
    } else {
      $cordovaToast.showLongTop('Youâre not a member of the room, so you cannot access it. Please add admin for access permission.');
    }
  }
  $scope.parseTimeWorking = function(time) {
    return moment(time, 'HH:mm:ss').format("h:mm A");
  }
  $scope.replaceNewAddress = function() {
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.replaceNewAddress({
      appId: $scope.detailAppointmentData.id
    }).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $cordovaToast.showLongTop(data.msg);
        $scope.detailAppointmentData.serviceLocation = data.newAddress;
        $scope.closeTarget('#popupAppointmentDetailReplaceAddressConfirm');
      } else {
        $cordovaToast.showLongTop(data.msg);
      }
    });
  }
  $scope.openFormFlagNote = function() {
    if (parseInt($scope.detailCustomerData.flag_id)) {
      $scope.dataUpdateFlagNote.flag_color = _.where($scope.flags, {
        id: $scope.detailCustomerData.flag_id
      })[0].color;
      $scope.dataUpdateFlagNote.flag_color_name = _.where($scope.flags, {
        id: $scope.detailCustomerData.flag_id
      })[0].name;
    } else {
      $scope.dataUpdateFlagNote.flag_color = '';
      $scope.dataUpdateFlagNote.flag_color_name = '';
    }
    $scope.dataUpdateFlagNote.flag_note = $scope.detailCustomerData.flag_note;
    $scope.dataUpdateFlagNote.note = $scope.detailCustomerData.note;
    $scope.dataUpdateFlagNote.cus_id = $scope.detailCustomerData.id;
    $scope.dataUpdateFlagNote.flag_id = $scope.detailCustomerData.flag_id;
    $scope.openByGetTemplate('popupAppointmentDetailCustomerFlagNote');
  }
  $scope.updateFlagNote = function() {
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.updateFlagNote($scope.dataUpdateFlagNote).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $scope.detailCustomerData.note = $scope.dataUpdateFlagNote.note;
        $scope.detailCustomerData.flag_id = $scope.dataUpdateFlagNote.flag_id;
        $scope.detailCustomerData.flag_note = $scope.dataUpdateFlagNote.flag_note;
        $scope.Input_value.flag_color = _.where($scope.flags, {
          id: $scope.detailCustomerData.flag_id
        })[0].color;
        $scope.closeTarget('#popupAppointmentDetailCustomerFlagNote');
      }
    })
  }
  $scope.setColorForFlag = function(value) {
    if (value != '' && value != null) {
      $scope.dataUpdateFlagNote.flag_color = _.where($scope.flags, {
        id: value
      })[0].color;
      $scope.dataUpdateFlagNote.flag_color_name = _.where($scope.flags, {
        id: value
      })[0].name;
    } else {
      $scope.dataUpdateFlagNote.flag_color = '';
      $scope.dataUpdateFlagNote.flag_color_name = 'Select';
    }
  }
  $scope.openFormAddress = function() {
    $scope.openByGetTemplate('popupAppointmentDetailAddress');
  }
  $scope.tabOrderActive = 'estimate';
  $scope.setTabOrder = function(tab) {
    $scope.tabOrderActive = tab;
    $scope.ViewAllOrder = $scope.allOrderOrginData;
    $scope.initialJobsiteOrder = ["All"];
    $scope.arrFilterJobsite = [];
  }
  $scope.viewEstimatePdf = function(url, orderData) {
    $scope.holderOrderType = 'est'
    $scope.holderOrderId = orderData.id;
    if (url == null || url.length == 0) {
      $ionicLoading.show({
        template: templateLoading
      });
      Orderstatuses.opportunitiesExport(orderData.id, orderData.invoice_no).success(function(data) {
        $ionicLoading.hide();
        $scope.pdfLocation = url_site + '/' + data.link;
        $scope.openByGetTemplate('pdfViewer');
      });
    } else {
      $scope.pdfLocation = url;
      $scope.openByGetTemplate('pdfViewer');
    }
  }
  $scope.viewInvoicePdf = function(url, order_id) {
    $scope.holderOrderType = 'inv';
    $scope.holderOrderId = order_id;
    if (url == null || url.length == 0) {
      $ionicLoading.show({
        template: templateLoading
      });
      Ordertypes.export_file_pdf(order_id, 'opportunitiesExport', '').success(function(data) {
        $ionicLoading.hide();
        $scope.pdfLocation = url_site + '/' + data.link;
        $scope.openByGetTemplate('pdfViewer');
      });
    } else {
      $scope.pdfLocation = url;
      $scope.openByGetTemplate('pdfViewer');
    }
  }
  $scope.callbackItem = {};
  $scope.filterOrderJobsite = function(query) {
    $scope.orderJobsiteList = [];
    $scope.orderJobsiteList.push({
      id: 'All',
      name: 'All'
    });
    $scope.orderJobsiteList.push({
      id: $scope.detailCustomerData.street,
      name: 'Billing Address'
    });
    $scope.existAddressOrder = [];
    _.each($scope.dataJobsiteToAutocomplete, function(item) {
      if ($scope.existAddressOrder.indexOf(item.name) < 0) {
        $scope.existAddressOrder.push(item.name);
        $scope.orderJobsiteList.push({
          id: item.name,
          name: item.name
        });
      }
    })
    var returnValue = {
      items: []
    };
    $scope.orderJobsiteList.forEach(function(item) {
      if ($scope.autocompleteEstimate.jobsiteFilter.indexOf(item.id) < 0 && item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        returnValue.items.push(item);
      }
    });
    return returnValue;
  }
  $scope.onSelectFilterOrderJobsite = function(callback) {
    if ($scope.arrFilterJobsite.indexOf(callback.item.id) < 0) {
      $scope.arrFilterJobsite.push(callback.item.id.trim());
    }
    if (callback.item.id == 'All') {
      $scope.ViewAllOrder = $scope.allOrderOrginData;
    } else {
      $scope.startFilterOrder();
    }
  }
  $scope.startFilterOrder = function() {
    if ($scope.arrFilterJobsite.indexOf('All') > -1) {
      $scope.ViewAllOrder = $scope.allOrderOrginData;
    } else {
      if ($scope.tabOrderActive == 'estimate') {
        $scope.ViewAllOrder = _.filter($scope.allOrderOrginData, function(val) {
          if (parseInt(val.ordertype_id) == 4) {
            return $scope.arrFilterJobsite.indexOf(val.service_localtion.trim()) > -1;
          }
        });
      } else {
        $scope.ViewAllOrder = _.filter($scope.allOrderOrginData, function(val) {
          if (parseInt(val.ordertype_id) == 5) {
            return $scope.arrFilterJobsite.indexOf(val.service_localtion.trim()) > -1;
          }
        });
      }
    }
  }
  $scope.onRemoveOrderAddress = function(callback) {
    var index = $scope.arrFilterJobsite.indexOf(callback.item.id);
    $scope.arrFilterJobsite.splice(index, 1);
    $scope.startFilterOrder();
  }
  $scope.modelToItemMethodJobsiteOrder = function(modelValue) {
    $scope.jobsitedata = [];
    $scope.jobsitedata.push({
      id: 'All',
      name: 'All'
    });
    _.each($scope.allOrderOrginData, function(item) {
      $scope.jobsitedata.push(item);
    })
    for (var i = 0; i < $scope.jobsitedata.length; i++) {
      if ($scope.jobsitedata[i].id == modelValue) {
        return $scope.jobsitedata[i];
      }
    }
    return {};
  };
  $scope.openFormSendMail = function() {
    $scope.dataSendMail.mail1 = $scope.detailCustomerData.email;
    $scope.dataSendMail.customized = 'Hi ' + $scope.detailCustomerData.first_name + ' ' + $scope.detailCustomerData.last_name + '. Thank you for the opportunity to earn your business. I personally appreciate you as a customer.';
    $scope.currentMail = _.where($scope.allUser, {
      id: parseInt($scope.currentuserId)
    })[0].email;
    $scope.dataSendMail.sendFrom = [{
      text: $scope.currentMail
    }];
    $scope.dataSendMail.mail1 = [{
      text: $scope.detailCustomerData.email
    }];
    $scope.openByGetTemplate('popupAppointmentDetailEmail');
  }
  // $scope.dataSendMail.selectedMailSendFrom = [
  // ];
  $scope.loadTagsEmail = function(query) {
    mailArr = [];
    _.each($scope.detailCustomerData.additionalEmail, function(value) {
      mailArr.push({
        text: value
      })
    });
    var returnValue = [];
    mailArr.forEach(function(item) {
      if (item.text.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        returnValue.push(item);
      }
    });
    return returnValue;
  };
  $scope.loadTagsEmail2 = function(query) {
    mailArr = [];
    mailArr.push({
      text: $scope.detailCustomerData.email
    })
    _.each($scope.detailCustomerData.additionalEmail, function(value) {
      mailArr.push({
        text: value
      })
    });
    var returnValue = [];
    mailArr.forEach(function(item) {
      if (item.text.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        returnValue.push(item);
      }
    });
    return returnValue;
  };
  $scope.loadTagsEmailSendFrom = function(query) {
    mailArrSendFrom = [];
    _.each($scope.allUser, function(value) {
      mailArrSendFrom.push({
        text: value.email
      })
    });
    var returnValue = [];
    returnValue.push({
      text: 'info@reliablegaragdoor.com'
    });
    returnValue.push({
      text: 'service@reliablegaragdoor.com'
    });
    mailArrSendFrom.forEach(function(item) {
      if (item.text.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        returnValue.push(item);
      }
    });
    return returnValue;
  };
  $scope.selectMail = function(value) {
    $scope.dataSendMail.sendFrom = [value];
  };
  $scope.sendMail = function(formValidate) {
    if (formValidate.$invalid) {
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    }
    if ($scope.dataSendMail.mail1.length == 0) {
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    }
    if ($scope.dataSendMail.sendFrom.length > 0) {
      $scope.dataSendMail.sendFromEmail = $scope.dataSendMail.sendFrom[0].text;
    }
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.sendMail($scope.dataSendMail).success(function(data) {
      if (data.status) {
        $ionicLoading.hide();
        $cordovaToast.showLongTop(data.msg);
        $scope.closeTarget('#popupAppointmentDetailEmail');
      }
    });
  };
  $scope.revertApp = function() {
    $scope.detailAppointmentData.jobstatusCurrent.name = 'Complete';
    $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext = {
      appointment_id: $scope.detailAppointmentData.id,
      jobstatus_id: 7
    }
    $scope.createAppointmentstatuses('to_complete');
    $scope.closeTarget('#popupAppointmentDetailRevertAppointmentConfirm');
  }
  $scope.sendToPushRoom = function() {
    $ionicLoading.show({
      template: templateLoading
    });
    Users.getCurrentUserRoom().success(function(data) {
      if (data.status) {
        $scope.dataSendToPushRoom.room_id = data.room_id;
        scope.sendToPushRoomFromAppDetail($scope.dataSendToPushRoom);
      } else {
        $ionicLoading.hide();
        $cordovaToast.showLongTop(data.msg);
      }
    });
  }
  $scope.setTempDataViewApp = function() {
    $scope.tempDataNote.officeapptnote = $scope.detailAppointmentData.officeapptnote;
    $scope.tempDataNote.fieldworkernote = $scope.detailAppointmentData.fieldworkernote;
  }
  $scope.saveAndLoadOfficeNote = function(type) {
    if ($scope.tempDataNote.officeapptnote == $scope.detailAppointmentData.officeapptnote || $scope.tempDataNote.officeapptnote == '') {
      return;
    }
    $ionicLoading.show({
      template: templateLoading
    });
    $scope.dataSaveOfficeNote.note = $scope.tempDataNote.officeapptnote;
    $scope.dataSaveOfficeNote.appId = $scope.detailAppointmentData.id;
    Appointments.saveAndLoadOfficeNote($scope.dataSaveOfficeNote).success(function(data) {
      if (data.status) {
        $ionicLoading.hide();
        $cordovaToast.showLongTop(data.msg);
        $scope.detailAppointmentData.logOffice = data.data_log;
        $scope.detailAppointmentData.officeapptnote = data.lasted_log;
      }
    });
  }
  $scope.saveAndLoadFieldWorkerNote = function(type) {
    if ($scope.tempDataNote.fieldworkernote == $scope.detailAppointmentData.fieldworkernote || $scope.tempDataNote.fieldworkernote == '') {
      return;
    }
    $ionicLoading.show({
      template: templateLoading
    });
    $scope.dataSaveFieldWorkerNote.note = $scope.tempDataNote.fieldworkernote;
    $scope.dataSaveFieldWorkerNote.appId = $scope.detailAppointmentData.id;
    Appointments.saveAndLoadFieldWorkerNote($scope.dataSaveFieldWorkerNote).success(function(data) {
      if (data.status) {
        $ionicLoading.hide();
        $cordovaToast.showLongTop(data.msg);
        $scope.detailAppointmentData.logFieldworker = data.data_log;
        $scope.detailAppointmentData.fieldworkernote = data.lasted_log;
      }
    });
  }
  $scope.updateAppointmentInfor = function() {
    $scope.dataAppointmentInfor.appId = $scope.detailAppointmentData.id;
    $scope.dataAppointmentInfor.arrivalwindow = $('#id_arrivalwindow').val();
    $scope.dataAppointmentInfor.appointmentgroup_id = $scope.detailAppointmentData.appointmentgroup_id;
    $scope.dataAppointmentInfor.endarrivalwindow = $('#id_endarrivalwindow').val();
    $scope.dataAppointmentInfor.dateofappt = Date.parseDate($scope.detailAppointmentData.dateofappt).dateFormat('MM/DD/YYYY');
    $scope.dataAppointmentInfor.callahead_id = $scope.detailAppointmentData.callahead_id;
    $scope.dataAppointmentInfor.nothomeutil = $('#inputnothomeutil').val();
    $scope.dataAppointmentInfor.fieldworker = $scope.holdFieldWorkerOnApp.id;
    $scope.dataAppointmentInfor.prefieldworker = $scope.detailAppointmentData.prefieldworker;
    $scope.dataAppointmentInfor.flexiblecustomer_id = $scope.detailAppointmentData.flexiblecustomer_id;
    $scope.dataAppointmentInfor.customertype_id = $scope.detailAppointmentData.customertype_id;
    if ($scope.tempDataNote.officeapptnote != $scope.detailAppointmentData.officeapptnote && $scope.tempDataNote.officeapptnote != '') {
      $scope.dataAppointmentInfor.officenote = $scope.tempDataNote.officeapptnote;
    }
    if ($scope.tempDataNote.fieldworkernote != $scope.detailAppointmentData.fieldworkernote && $scope.tempDataNote.fieldworkernote != '') {
      $scope.dataAppointmentInfor.fieldworkernote = $scope.tempDataNote.fieldworkernote;
    }
    if ($scope.old_arrivalwindow_time != $scope.dataAppointmentInfor.arrivalwindow || $scope.old_endarrivalwindow_time != $scope.dataAppointmentInfor.endarrivalwindow || $scope.dataAppointmentInfor.dateofappt != $scope.oldDateOfAppDetail) {
      $scope.dataAppointmentInfor.appointment_change_time = true;
    } else {
      $scope.dataAppointmentInfor.appointment_change_time = false;
    }
    var startTimeCheck = moment($scope.dataAppointmentInfor.arrivalwindow, 'HH:mmA').format('HH:mm');
    var endTimeCheck = moment($scope.dataAppointmentInfor.endarrivalwindow, 'HH:mmA').format('HH:mm');
    if (startTimeCheck > endTimeCheck || startTimeCheck == endTimeCheck) {
      $cordovaToast.showLongTop('End time must be greater than start time');
      return;
    }
    $scope.dataAppointmentInfor.dataJobsite = $scope.detailAppointmentData.appointmentjobsites;
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.updateAppointmentInfor($scope.dataAppointmentInfor).success(function(data) {
      if (data.status) {
        $ionicLoading.hide();
        $cordovaToast.showLongTop(data.msg);
        $scope.closeTarget('#scheduleDetailEdit');
      }
    });
  }
  $scope.clickOnNotAttached = function($event, p, pe, e) {
    $scope.noAttackClicked = true;
    $scope.viewOfficeNoteAppHistory = false;
    $scope.viewFieldWorkerNotesAppHistory = false;
    $scope.viewPhotoCounter = false;
    $scope.viewPdfCounter = false;
    $scope.viewOtherfileCounter = false;
    $scope.viewAudioCounter = false;
    $scope.viewStatusLogCounter = false;
    $scope.viewDispathLogCounter = false;
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.getAllEstimateInvoiceId({
      cus_id: $scope.detailCustomerData.id
    }).success(function(data) {
      $ionicLoading.hide();
      $scope.estimateAppDetail = data.estimate;
      $scope.invoiceAppDetail = data.invoice;
      $scope.estimateCounterAppDetail = $scope.estimateAppDetail.length;
      $scope.invoiceCounterAppDetail = $scope.invoiceAppDetail.length;
      $('.appointment-history-item' + " " + '.appointment-detail').hide();
      $($event.target).closest(pe).find(e).toggle();
      $scope.countAllFilesOfAppHistory = $scope.estimateAppDetail.length + $scope.invoiceAppDetail.length;
    });
  }
  $scope.clickOnAppHistory = function(app) {
    $scope.noAttackClicked = false;
    $scope.viewOfficeNoteAppHistory = true;
    $scope.viewFieldWorkerNotesAppHistory = true;
    $scope.viewPhotoCounter = true;
    $scope.viewPdfCounter = true;
    $scope.viewOtherfileCounter = true;
    $scope.viewAudioCounter = true;
    $scope.viewStatusLogCounter = true;
    $scope.viewDispathLogCounter = true;
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.getAppHistoryDetailByAppId({
      id: app.id
    }).success(function(data) {
      $scope.selectedApp = data;
      $scope.officeNoteAppHistory = $scope.selectedApp.officeapptnote;
      $scope.fieldWorkerNotesAppHistory = $scope.selectedApp.fieldworkernote;
      _.each($scope.selectedApp.files, function(value) {
        value.type = $scope.sortFiletypeAppointment(value.extension);
      });
      $scope.photoCounter = _.where($scope.selectedApp.files, {
        type: 'Photo'
      }).length;
      if ($scope.photoCounter == 0) {
        $scope.viewPhotoCounter = false;
      }
      $scope.allPhotoAppHistory = _.where($scope.selectedApp.files, {
        type: 'Photo'
      });
      $scope.estimateFile = $scope.selectedApp.dataestimatepdf;
      $scope.invoiceFile = $scope.selectedApp.datainvoicepdf;
      $scope.estimateCounterAppDetail = $scope.selectedApp.dataestimatepdf.length;
      $scope.invoiceCounterAppDetail = $scope.selectedApp.datainvoicepdf.length;
      if ($scope.estimateCounterAppDetail == 0) {
        $scope.viewEstimateCounter = false;
      } else {
        $scope.viewEstimateCounter = true;
      }
      if ($scope.invoiceCounterAppDetail == 0) {
        $scope.viewInvoiceCounter = false;
      } else {
        $scope.viewInvoiceCounter = true;
      }
      $scope.dataPdfFile = $scope.selectedApp.pdf;
      if ($scope.dataPdfFile.length == 0) {
        $scope.viewPdfCounter = false;
      }
      var otherFilesCounter = _.where($scope.selectedApp.files, {
        type: 'Other'
      }).length;
      if (otherFilesCounter == 0) {
        $scope.viewOtherfileCounter = false;
      }
      $scope.otherFile = _.where($scope.selectedApp.files, {
        type: 'Other'
      });
      if ($scope.selectedApp.audio) {
        if ($scope.selectedApp.audio.recordingfile != null && $scope.selectedApp.audio.recordingfile != "") {
          $scope.viewAudioCounter = true;
        } else {
          $scope.viewAudioCounter = false;
        }
      } else {
        $scope.viewAudioCounter = false;
      }
      if ($scope.selectedApp.status.current_status != null && $scope.selectedApp.status.current_status != "" && $scope.selectedApp.status.current_status != "Pending") {
        $scope.viewStatusLogCounter = true;
      } else {
        $scope.viewStatusLogCounter = false;
      }
      if ($scope.selectedApp.dispatchlogs.data.length) {
        $scope.viewDispathLogCounter = true;
      } else {
        $scope.viewDispathLogCounter = false;
      }
      $ionicLoading.hide();
    });
  }
  $scope.clickOnAppHistoryLog = function(type) {
    $scope.viewAppnote($scope.selectedApp.officeNote, $scope.selectedApp.fieldworkerNote, type);
  }
  $scope.openPhotoViewer = function(type) {
    if ($scope.noAttackClicked) {
      if (type == 'estimate') {
        $scope.indexSlide = 0;
      }
      if (type == 'invoice') {
        $scope.indexSlide = $scope.estimateAppDetail.length;
      }
      $scope.countAllFilesOfAppHistory = $scope.invoiceAppDetail.length + $scope.estimateAppDetail.length;
    } else {
      $scope.allPhotoAppHistory.length ? $scope.countPhotoSkip = $scope.allPhotoAppHistory.length : $scope.countPhotoSkip = 0;
      $scope.estimateFile.length ? $scope.countEstimateSkip = $scope.estimateFile.length : $scope.countEstimateSkip = 0;
      $scope.invoiceFile.length ? $scope.countInvoiceSkip = $scope.invoiceFile.length : $scope.countInvoiceSkip = 0;
      $scope.dataPdfFile.length ? $scope.countPdfSkip = $scope.dataPdfFile.length : $scope.countPdfSkip = 0;
      $scope.otherFile.length ? $scope.countOtherSkip = $scope.otherFile.length : $scope.countOtherSkip = 0;
      $scope.viewAudioCounter ? $scope.countAudioSkip = 1 : $scope.countAudioSkip = 0;
      $scope.viewStatusLogCounter ? $scope.countStatusLogSkip = 1 : $scope.countStatusLogSkip = 0;
      if (type == 'photo') {
        $scope.indexSlide = 0;
      }
      if (type == 'estimate') {
        $scope.indexSlide = $scope.countPhotoSkip;
      }
      if (type == 'invoice') {
        $scope.indexSlide = $scope.countPhotoSkip + $scope.countEstimateSkip;
      }
      if (type == 'pdf') {
        $scope.indexSlide = $scope.countPhotoSkip + $scope.countEstimateSkip + $scope.countInvoiceSkip;
      }
      if (type == 'other') {
        $scope.indexSlide = $scope.countPhotoSkip + $scope.countEstimateSkip + $scope.countInvoiceSkip + $scope.countPdfSkip;
      }
      if (type == 'audio') {
        $scope.indexSlide = $scope.countPhotoSkip + $scope.countEstimateSkip + $scope.countInvoiceSkip + $scope.countPdfSkip + $scope.countOtherSkip;
      }
      if (type == 'status') {
        $scope.indexSlide = $scope.countPhotoSkip + $scope.countEstimateSkip + $scope.countInvoiceSkip + $scope.countPdfSkip + $scope.countOtherSkip + $scope.countAudioSkip;
      }
      if (type == 'dispathlog') {
        $scope.indexSlide = $scope.countPhotoSkip + $scope.countEstimateSkip + $scope.countInvoiceSkip + $scope.countPdfSkip + $scope.countOtherSkip + $scope.countAudioSkip + $scope.countStatusLogSkip;
      }
      $scope.countAllFilesOfAppHistory = $scope.countPhotoSkip + $scope.countEstimateSkip + $scope.countInvoiceSkip + $scope.countPdfSkip + $scope.countOtherSkip + $scope.countAudioSkip + $scope.countStatusLogSkip;
    }
    $scope.activeIndex = $scope.indexSlide;
    $scope.openByGetTemplate('photoViewer');
    $timeout(function(val) {
      if ($scope.selectedApp && $scope.selectedApp.audio) {
        if ($scope.selectedApp.audio.recordingfile != null && $scope.selectedApp.audio.recordingfile != "") {
          var listTrack = [$scope.selectedApp.audio.recordingfile];
          if ($scope.selectedApp.audio.recordingfile.indexOf('###') >= 0) {
            listTrack = $scope.selectedApp.audio.recordingfile.split('###');
          }
          audioPlayerMultiTrack('#callRecordAudioAreaHistory', listTrack);
        }
      }
    }, 1000);
    var callBackSlideViewFile = function() {
      setTimeout(function() {
        if ($scope.dataSlider.slider) {
          $scope.dataSlider.slider.slideTo($scope.indexSlide, 300);
          var $targetActive = angular.element($scope.dataSlider.slider.wrapper[0]);
          $scope.activeDataFile($targetActive);
        } else {
          callBackSlideViewFile();
        }
      }, 100)
    }
    callBackSlideViewFile();
  }
  $scope.changePhotoViewMode = function(type) {
    $scope.modePhotoView = type;
  }
  $scope.trustSrc = function(src, isview) {
    if (isview) {
      src = 'http://docs.google.com/gview?url=' + src + '&embedded=true#:0.page.20';
    }
    return $sce.trustAsResourceUrl(src);
  }
  $scope.newFileAction = function(type) {
    $scope.uploadType = 'takePicture';
    switch (type) {
      case 'videorecord':
      $scope.recordVideo();
      break;
      case 'camera':
      $scope.takePicture();
      break;
      case 'photo':
      $scope.openPicker();
      break;
      case 'file':
      $scope.filePicker();
      break;
      case 'url':
      $scope.getAppUrlByAppid($scope.detailAppointmentData.id, 'openform');
      break;
    }
  }
  $scope.showFlagNoteCellBefore = function() {
    if (parseInt($scope.detailCustomerData.flag_id) > 0 && $scope.detailCustomerData.flag_note.length) {
      return true;
    } else {
      return false;
    }
  }
  $scope.showFlagNoteCellAfter = function() {
    if (!parseInt($scope.detailCustomerData.flag_id) > 0 || !$scope.detailCustomerData.flag_note.length) {
      return true;
    } else {
      return false;
    }
  }
  $scope.closeFormAddnote = function() {
    $scope.closeTarget('#popupAppointmentDetailCustomerAddFlagNote');
  }
  $scope.nextSlide = function() {
    if ($('.video-area video')[0] != undefined) {
      $('.video-area video')[0].pause();
    }
    $scope.dataSlider.slider.slideNext();
  }
  $scope.prevSlide = function() {
    if ($('.video-area video')[0] != undefined) {
      $('.video-area video')[0].pause();
    }
    $scope.dataSlider.slider.slidePrev();
  }
  $scope.$on("$ionicSlides.slideChangeStart", function(event, data) {
    setTimeout(function() {
      $scope.$apply(function(val) {
        $scope.activeIndex = data.slider.activeIndex;
      });
    }, 1);
  });
  $scope.$on("$ionicSlides.slideChangeEnd", function(event, data) {
    if ($('.video-area video')[0] != undefined) {
      $('.video-area video')[0].pause();
    }
    var $targetActive = angular.element(data.slider.wrapper[0]);
    $scope.activeDataFile($targetActive);
  });
  $scope.activeDataFile = function($target) {
    $target.find('.swiper-slide-prev').find('.data-path-file').attr('src', 'http://#');
    $target.find('.swiper-slide-active').find('.data-path-file').attr('src', $target.find('.swiper-slide-active').find('.data-path-file').attr('data-path-file'));
    $target.find('.swiper-slide-active').find('.data-type-file').length > 0 ? $scope.dataTypeFile = true : $scope.dataTypeFile = false;
  }
  $scope.deleteFlagNote = function() {
    $ionicLoading.show({
      template: templateLoading
    });
    Customers.deleteFlagNote({
      cus_id: $scope.detailCustomerData.id
    }).success(function(data) {
      if (data.status) {
        $ionicLoading.hide();
        $cordovaToast.showLongTop(data.msg);
        $scope.detailCustomerData.flag_id = null;
        $scope.detailCustomerData.flag_note = null;
        $scope.Input_value.flag_color = '';
        $scope.closeTarget('#schedulesPopupConfirmDeleteFlagNote');
        $scope.closeTarget('#popupAppointmentDetailCustomerFlagNote');
      }
    });
  }
  $scope.listviewChange = function() {
    $scope.loadAppByListView = true;
    $scope.loadAppointmentByDay($scope.selectedDay);
  }
  $scope.openPopupAddScheduleNote = function(fieldworker) {
    $scope.dataSentToNoteTask = {};
    $scope.dataSentToNoteTask.fieldworker = [fieldworker];
    $scope.$broadcast('sentFieldworkerId', $scope.dataSentToNoteTask);
  }
  $scope.$on('openPopupAddScheduleNote', function(event, args) {
    $scope.openByGetTemplate('popupAddScheduleNote');
  });
  $scope.onclickBackBUttonAppDetail = function() {
    if (parseInt($scope.appointment_id) > 0) {
      if ($scope.org_page == 'schedules') {
        $scope.closeTarget('#scheduleDetailEdit');
      } else if ($scope.org_page == 'customers') {
        redirectTo('customers.html?customer_id=' + $scope.detailCustomerData.id + '&org_page=apphistory');
      } else if ($scope.org_page == 'opportunities') {
        redirectTo('opportunity.html');
      } else {
        redirectTo('customers.html?customer_id=' + $scope.detailCustomerData.id + '#/board/customers');
      }
    } else {
      $scope.closeTarget('#scheduleDetailEdit');
    }
  }
  $scope.$on('beginScopeWatch', function(event, args) {
    $scope.beginScopeWatch = args.value;
  });
  $scope.$watch('addAppointmentsData.dateofappt', function(val) {
    if ($scope.beginScopeWatch) {
      var appDate = moment(val).format('MM/DD/YYYY');
      $('#formAppointmentAdd #dateofappt').val(appDate);
    }
  });
  $scope.$watch('addAppointmentsData.arrivalwindow', function(val) {
    if ($scope.beginScopeWatch) {
      //var time = moment(val).format("h:mm A");
      $('#formAppointmentAdd #arrivalwindowView').val(val);
    }
  });
  $scope.$watch('addAppointmentsData.endarrivalwindow', function(val) {
    if ($scope.beginScopeWatch) {
      //var time = moment(val).format("h:mm A");
      $('#formAppointmentAdd #endarrivalwindowView').val(val);
    }
  });
  $scope.$on('resetValue', function(events, data) {
    $scope.addAppointmentsData = {};
    $scope.holdValueAddress.addAppointment = [];
    $scope.jobsiteshow = false;
  });
  $scope.showPaymentHistory = function(index) {
    $('#list-payment-history-' + index).toggle();
  }
  $scope.formatTimePayment = function(date) {
    return moment(date).format('h:mm A');
  };
  $scope.closeFileViewer = function(date) {
    if ($('.video-area video')[0] != undefined) {
      $('.video-area video')[0].pause();
    }
    $scope.closeTarget('#photoViewer');
  };
  $scope.sortAndGroupDataPayment = function(data) {
    $scope.dataAfterSort = [];
    $scope.arrDayPayment = _.uniq(_.pluck(data, 'dateToSort'));
    _.each($scope.arrDayPayment, function(value) {
      $scope.createdDatePayment = value;
      $scope.paymentByDay = _.where(data, {
        dateToSort: $scope.createdDatePayment
      });
      _.each($scope.paymentByDay, function(value) {
        _.extend(value, {
          timeToSort: moment(value.created_date).format('HH:mm:ss')
        });
      });
      $scope.oldTimeToSort = '';
      $scope.paymentByDay = _.sortBy($scope.paymentByDay, 'timeToSort');
      _.each($scope.paymentByDay, function(value) {
        if ($scope.oldTimeToSort == value.timeToSort) {
          _.extend(value, {
            showSignature: false
          });
        } else {
          _.extend(value, {
            showSignature: true
          });
        }
        $scope.oldTimeToSort = value.timeToSort;
      });
      $scope.dataAfterSort.push({
        date: $scope.createdDatePayment,
        payment: $scope.paymentByDay
      })
    });
    return $scope.dataAfterSort;
  };
  $scope.selectAddressApp = function(value, type) {
    if (type == 'addapp') {
      if ($scope.holdValueAddress.addAppointment.length > 0) {
        $scope.holdValueAddress.addAppointment.splice(0, 1);
      }
    }
    if (type == 'editapp') {
      if ($scope.holdValueAddress.editAppointment.length > 0) {
        $scope.holdValueAddress.editAppointment.splice(0, 1);
      }
    }
    $scope.valueClone = value;
    var data = [];
    var componentAddressForm = {
      locality: 'long_name',
      administrative_area_level_1: 'short_name',
      postal_code: 'short_name'
    };
    LocationService.getDetails(value.place_id).then(function(location) {
      $scope.valueClone.description = location.formatted_address;
      angular.forEach(location.address_components, function(item) {
        var addressType = item.types[0];
        if (componentAddressForm[addressType]) {
          var val = item[componentAddressForm[addressType]];
          data[addressType] = val;
        }
      })
      if (type == 'addapp') {
        data['locality'] ? $scope.addAppointmentsData.jobsites.city = data['locality'] : $scope.addAppointmentsData.jobsites.city = '';
        data['administrative_area_level_1'] ? $scope.addAppointmentsData.jobsites.state = data['administrative_area_level_1'] : $scope.addAppointmentsData.jobsites.state = '';
        data['postal_code'] ? $scope.addAppointmentsData.jobsites.zipcode = data['postal_code'] : $scope.addAppointmentsData.jobsites.zipcode = '';
        $scope.addAppointmentsData.jobsites.street = location.formatted_address;
      }
      if (type == 'editapp') {
        data['locality'] ? $scope.editAppointmentsData.dataJobsite.city = data['locality'] : $scope.editAppointmentsData.dataJobsite.city = '';
        data['administrative_area_level_1'] ? $scope.editAppointmentsData.dataJobsite.state = data['administrative_area_level_1'] : $scope.editAppointmentsData.dataJobsite.state = '';
        data['postal_code'] ? $scope.editAppointmentsData.dataJobsite.zipcode = data['postal_code'] : $scope.editAppointmentsData.dataJobsite.zipcode = '';
        $scope.editAppointmentsData.dataJobsite.street = location.formatted_address;
      }
    })
  };
  $scope.removetagapp = function(value, type) {
    if (type == 'addapp') {
      $scope.addAppointmentsData.jobsites.city = '';
      $scope.addAppointmentsData.jobsites.state = '';
      $scope.addAppointmentsData.jobsites.zipcode = '';
      $scope.addAppointmentsData.jobsites.street = '';
      $scope.holdValueAddress.addAppointment = [];
    }
    if (type == 'editapp') {
      $scope.editAppointmentsData.dataJobsite.city = '';
      $scope.editAppointmentsData.dataJobsite.state = '';
      $scope.editAppointmentsData.dataJobsite.zipcode = '';
      $scope.editAppointmentsData.dataJobsite.street = '';
      $scope.holdValueAddress.editAppointment = [];
    }
  };
  $scope.deleteViewer = function(file, type) {
    $ionicLoading.show({
      template: templateLoading
    });
    Appointments.deleteFileOnViewer({
      file: file,
      type: type
    }).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $cordovaToast.showLongTop(data.msg)
        $scope.closeFileViewer();
        $('.appointment-history-item' + " " + '.appointment-detail').hide();
      } else {
        $cordovaToast.showLongTop(data.msg)
      }
    });
  };
  $scope.printPdf = function(order_id, pdf_mode, order_type) {
    if (order_type == 'est') {
      if (pdf_mode == 'LOW_DPI_PDF') {
        actions = 'update_printable_PDF_DPI';
      }
      if (pdf_mode == 'PDF') {
        actions = 'update_printable_PDF';
      }
      $scope.getDataToPrintPdfEstimate(order_id, actions);
    }
    if (order_type == 'inv') {
      if (pdf_mode == 'LOW_DPI_PDF') {
        actions = 'Generate_printable_PDF_DPI';
      }
      if (pdf_mode == 'PDF') {
        actions = 'Generate_printable_PDF';
      }
      $scope.getDataToPrintPdfInvoice(order_id, actions);
    }
  };
  $scope.getDataToPrintPdfEstimate = function(order_id, actions) {
    $ionicLoading.show({
      template: templateLoading
    });
    Orderstatuses.getPaging(order_id).success(function(data) {
      $scope.dataPrintPdf.Jobsite_id = data.jobsite_id;
      $scope.dataPrintPdf.coupon_id = data.coupon_id;
      $ionicLoading.hide();
      $scope.pricebookdata = data.data;
      for (var i = 0; i < $scope.pricebookdata.length; i++) {
        $scope.pricebookdata[i].priceshow = parseInt($scope.pricebookdata[i].price);
        if ($scope.pricebookdata[i].Measurements != undefined) {
          $scope.pricebookdata[i].Measurements.can_op_go_up == null ? $scope.pricebookdata[i].Measurements.can_op_go_up = 0 : '';
          $scope.pricebookdata[i].Measurements.can_op_go_up = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.can_op_go_up).toFixed(2));
          $scope.pricebookdata[i].Measurements.floor_to_ceiling_at_center_plate = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.floor_to_ceiling_at_center_plate).toFixed(2));
          $scope.pricebookdata[i].Measurements.floor_to_ceiling_at_drums = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.floor_to_ceiling_at_drums).toFixed(2));
          $scope.pricebookdata[i].Measurements.floor_to_hor_at_backhanger = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.floor_to_hor_at_backhanger).toFixed(2));
          $scope.pricebookdata[i].Measurements.floor_to_hor_at_radius = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.floor_to_hor_at_radius).toFixed(2));
          $scope.pricebookdata[i].Measurements.floor_to_op_rail_18 = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.floor_to_op_rail_18).toFixed(2));
          $scope.pricebookdata[i].Measurements.floor_to_op_rail_at_stop_bolt = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.floor_to_op_rail_at_stop_bolt).toFixed(2));
          $scope.pricebookdata[i].Measurements.opening_height_left = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.opening_height_left).toFixed(2));
          $scope.pricebookdata[i].Measurements.opening_height_middle = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.opening_height_middle).toFixed(2));
          $scope.pricebookdata[i].Measurements.opening_height_right = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.opening_height_right).toFixed(2));
          $scope.pricebookdata[i].Measurements.opening_width = parseFloat(parseFloat($scope.pricebookdata[i].Measurements.opening_width).toFixed(2));
        }
      }
      $scope.dataPrintPdf.data = $scope.pricebookdata;
      $scope.dataPrintPdf.Subtotal = parseInt(data.total);
      $scope.dataPrintPdf.Discount = parseInt(data.discount);
      $scope.dataPrintPdf.user_id = $scope.currentIdLogin;
      $scope.dataPrintPdf.action = actions;
      $scope.dataPrintPdf.Estimate_id = order_id;
      $scope.dataPrintPdf.comment = data.comment;
      $scope.dataPrintPdf.customer_id = data.customer_id;
      $scope.dataPrintPdf.appointment_id = data.appointment_id;
      $scope.dataPrintPdf.estimate_no = data.invoice_no;
      $scope.dataPrintPdf.coupon_value = parseInt(data.coupon);
      $scope.dataPrintPdf.service_id = data.service_id;
      $scope.dataPrintPdf.service_option = data.service_option;
      $scope.dataPrintPdf.Jobsite_id = data.jobsite_id;
      $ionicLoading.show({
        template: templateLoading
      });
      Orderstatuses.save($scope.dataPrintPdf).success(function(data) {
        $ionicLoading.hide();
        if (data.status && data.action == 'openpage') {
          $scope.cordovaBrowser(data.link);
        }
      })
    });
  };
  $scope.getDataToPrintPdfInvoice = function(order_id, actions) {
    $ionicLoading.show({
      template: templateLoading
    });
    Ordertypes.getPaging(order_id).success(function(data) {
      Ordertypes.export_file_pdf(order_id, actions, '', data.jobsite_id, $scope.currentIdLogin).success(function(data) {
        $ionicLoading.hide();
        if (data.status) {
          if (data.link) {
            $scope.cordovaBrowser(data.link);
          }
          $cordovaToast.showLongTop(data.msg);
        } else {
          $cordovaToast.showLongTop(data.msg);
        }
      });
    });
  };
  $scope.addUrl = function(formValidate) {
    if (formValidate.$invalid) {
      var handle = $ionicScrollDelegate.$getByHandle('scrollAddListView');
      handle.scrollTop();
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    };
    $ionicLoading.show({
      template: templateLoading
    });
    if ($scope.addUrlFrom == 'customer') {
      $scope.addUrlData.app_id = $scope.dataAppointmentHistoryFileItem.id;
    }
    if ($scope.addUrlFrom == 'schedule') {
      $scope.addUrlData.app_id = $scope.detailAppointmentData.id;
    }
    Appointments.fileAddUrl($scope.addUrlData).success(function(data) {
      $ionicLoading.hide();
      $cordovaToast.showLongTop(data.msg);
      if ($scope.addUrlFrom == 'customer') {
        $scope.getAllAppointmentHistoryByCustomer($scope.detailCustomerData.id);
        $scope.getFilesByAppid($scope.addUrlData.app_id);
      }
      if ($scope.addUrlFrom == 'schedule') {
        $scope.closeTarget('#popupAppointmentAddUrl')
        $scope.getAppUrlByAppid($scope.detailAppointmentData.id, 'reload');
      }
      $scope.addUrlData = {};
    });
  }
  $scope.getFilesByAppid = function(id) {
    Appointments.getFilesByAppid(id).success(function(data) {
      $scope.dataAppointmentHistoryFileItem.files = data;
      $scope.closeTarget('#popupAppointmentAddUrl');
    });
  }
  $scope.getAppUrlByAppid = function(id, type) {
    Appointments.getAppUrlByAppid(id).success(function(data) {
      $scope.dataAppUrl = data;
      if (type == 'openform') {
        $scope.openByGetTemplate('popupAppointmentUrl');
      }
    });
  }
  $scope.openFormAddUrl = function(type) {
    $scope.addUrlFrom = type;
    $scope.openByGetTemplate('popupAppointmentAddUrl');
  }
  $scope.openUrl = function(url) {
    console.log(url);
    window.open(url, '_system');
  };
  $scope.bindRotateEvent = function(val) {
    var _interval = setInterval(function() {
      if (angular.element('.lightbox .lb-outerContainer') && angular.element('.lightbox .lb-outerContainer').length == $scope.filesViewerSchedule.length) {
        $scope.$apply(function() {
          var deg = 0
          angular.element('.rt_right').unbind('click');
          angular.element('.rt_right').click(function() {
            deg += 90;
            var deafult_deg = 90;
            $scope.rotateImage(val.id, deafult_deg, deg, 'right');
          })
          angular.element('.rt_left').unbind('click');
          angular.element('.rt_left').click(function() {
            deg += -90;
            var deafult_deg = -90;
            $scope.rotateImage(val.id, deafult_deg, deg, 'left')
          })
        });
        clearInterval(_interval);
      }
    }, 1000)
  };
  $scope.rotateImage = function(id, deg, deg_show, type) {
    $ionicLoading.show({
      template: templateLoading
    });
    angular.element('.loading-container').css({
      opacity: 0.6
    })
    Customers.rotateImage({
      id: id,
      deg: deg
    }).success(function(data) {
      if (data.status) {
        angular.element('.loading-container').attr('style', '');
        $ionicLoading.hide();
        var src = $('#lgBox-' + id + ' img').attr('src') + "?time=" + new Date().getTime();
        $('#lgBox-' + id + ' img').attr('src', src);
      }
    });
  };
  $scope.rotateImageOnViewer = function(id, type) {
    var deg = 0
    if (type == "right") {
      deg += 90;
      var deafult_deg = 90;

    }
    if (type == "left") {
      deg += -90;
      var deafult_deg = -90;
    }
    $ionicLoading.show({
      template: templateLoading
    });
    angular.element('.loading-container').css({
      opacity: 0.6
    })
    Customers.rotateImage({
      id: id,
      deg: deg
    }).success(function(data) {
      if (data.status) {
        angular.element('.loading-container').attr('style', '');
        $ionicLoading.hide();
        var src = $('#lgBoxOnViewer-' + id + ' img').attr('src') + "?time=" + new Date().getTime();
        $('#lgBoxOnViewer-' + id + ' img').attr('src', src);
      }
    });

  };
  $scope.getImage = function(user_id) {
    var index = _.findIndex($scope.allUser , {
      id: parseInt(user_id)
    });
    if (index >= 0) {
      var currUser = $scope.allUser[index];
      return currUser.imgprofile;
    } else {
      return '';
    }
  }

  $scope.changeJobsiteAppDetail = function(id) {
    if(parseInt(id) > 0){
      $ionicLoading.show({template: templateLoading});
      Customers.jobsiteById(id).success(function(data) {
        $ionicLoading.hide();
        $scope.detailAppointmentData.appointmentjobsites = [];
        $scope.detailAppointmentData.appointmentjobsites = data;
        $scope.Input_value.jobsite = $scope.detailAppointmentData.appointmentjobsites.label;
      });
    }else{
      $scope.detailAppointmentData.appointmentjobsites = null;
      $scope.Input_value.jobsite = 'Select';
    }
    
  }

  $scope.$on('getJsonData', function(event, args) {
    var jsondata = args.data;
    switch (page) {
      case 'scheduleapp.html':
      var index = _.findIndex(jsondata, {
        roletree_id: '46'
      });
      var index1 = _.findIndex(jsondata[index].child, {
        roletree_id: '48'
      });
      var index2 = _.findIndex(jsondata[index].child, {
        roletree_id: '47'
      });
      var indexMap = _.findIndex(jsondata[index].child, {
        roletree_id: '49'
      });
      if (jsondata[index].check) {
        $scope.showSearchAppointment = jsondata[index].child[0].child[0].check;
        $scope.showAddnoteTask = jsondata[index].child[0].child[1].check;
        $scope.showAllUser = jsondata[index].child[0].child[2].check;
        $scope.showToSchedulePanel = jsondata[index].child[0].child[3].check;
        $scope.dragAndDropCell = jsondata[index].child[0].child[4].check;
        $scope.showAddListView = jsondata[index].child[0].child[5].check;
        $scope.showEditAppointment = jsondata[index].child[0].child[6].child[0].check;
        $scope.editCustomerInfo = jsondata[index].child[0].child[6].child[0].child[0].check;
        $scope.editAppointmentInfo = jsondata[index].child[0].child[6].child[0].child[1].check;
        $scope.editOfficeNote = jsondata[index].child[0].child[6].child[0].child[2].check;
        $scope.editFiedlWorkerNote = jsondata[index].child[0].child[6].child[0].child[3].check;
        $scope.showJobStatus = jsondata[index].child[0].child[6].child[1].check;
        $scope.showChangeJobStatus = jsondata[index].child[0].child[6].child[1].child[0].check;
        $scope.showRevertJobStatus = jsondata[index].child[0].child[6].child[1].child[1].check;
        $scope.showCheckList = jsondata[index].child[0].child[6].child[2].check;
        $scope.showCancelAppointment = jsondata[index].child[0].child[6].child[3].check;
        $scope.showReplaceLocation = jsondata[index].child[0].child[6].child[4].check;
        $scope.showMgmt = jsondata[index].child[0].child[6].child[5].check;
        $scope.showButtonEstimateInvoice = jsondata[index].child[0].child[6].child[6].check;
        $scope.viewListenAudio = jsondata[index].child[0].child[6].child[7].check;
        $scope.viewDispathLog = jsondata[index].child[0].child[6].child[8].check;
        $scope.showButtonMap = jsondata[index].child[indexMap].check;
        $scope.jobsiteARC = jsondata[index].child[0].child[6].child[0].child[6].check;

        $scope.viewDownload = true;
        $scope.renameDelete = true;
      } else {
        localStorage.setItem("login_status", "0");
        redirectTo('index.html');
      }
      if (page == 'scheduleapp.html') {
        $scope.renderTemplateData();
        $scope.backPage = 'schedule';
      } else {
        $scope.backPage = 'myschedule';
      }
      if (getParameterByName('appID')) {
        $scope.getSchedulesCustomerInfo(getParameterByName('appID'))
      }
      break;
      case 'map.html':
      var index = _.findIndex(jsondata, {
        roletree_id: '46'
      });
      var index1 = _.findIndex(jsondata[index].child, {
        roletree_id: '49'
      });
      if (jsondata[index].child[index1].check) {
        $scope.viewFilterApp = jsondata[index].child[index1].child[0].check;
        $scope.showEditAppointment = jsondata[index].child[0].child[6].child[0].check;
        $scope.editCustomerInfo = jsondata[index].child[0].child[6].child[0].child[0].check;
        $scope.editAppointmentInfo = jsondata[index].child[0].child[6].child[0].child[1].check;
        $scope.editOfficeNote = jsondata[index].child[0].child[6].child[0].child[2].check;
        $scope.editFiedlWorkerNote = jsondata[index].child[0].child[6].child[0].child[3].check;
        $scope.showJobStatus = jsondata[index].child[0].child[6].child[1].check;
        $scope.showChangeJobStatus = jsondata[index].child[0].child[6].child[1].child[0].check;
        $scope.showRevertJobStatus = jsondata[index].child[0].child[6].child[1].child[1].check;
        $scope.showCheckList = jsondata[index].child[0].child[6].child[2].check;
        $scope.showCancelAppointment = jsondata[index].child[0].child[6].child[3].check;
        $scope.showReplaceLocation = jsondata[index].child[0].child[6].child[4].check;
        $scope.showMgmt = jsondata[index].child[0].child[6].child[5].check;
        $scope.showButtonEstimateInvoice = jsondata[index].child[0].child[6].child[6].check;
        $scope.viewListenAudio = jsondata[index].child[0].child[6].child[7].check;
        $scope.viewDispathLog = jsondata[index].child[0].child[6].child[8].check;
        $scope.viewDownload = true;
        $scope.renameDelete = true;
      } else {
        localStorage.setItem("login_status", "0");
        redirectTo('index.html');
      }
      break;
      case 'myschedule.html':
      var index = _.findIndex(jsondata, {
        roletree_id: '68'
      });
      var indexMap = _.findIndex(jsondata[index].child, {
        roletree_id: '49'
      });
      if (jsondata[index].check) {
        $scope.showEditAppointment = jsondata[index].child[0].check;
        $scope.editCustomerInfo = jsondata[index].child[0].child[0].check;
        $scope.editAppointmentInfo = jsondata[index].child[0].child[1].check;
        $scope.editOfficeNote = jsondata[index].child[0].child[2].check;
        $scope.editFiedlWorkerNote = jsondata[index].child[0].child[3].check;
        $scope.showJobStatus = jsondata[index].child[1].check;
        $scope.showChangeJobStatus = jsondata[index].child[1].child[0].check;
        $scope.showRevertJobStatus = jsondata[index].child[1].child[1].check;
        $scope.showCheckList = jsondata[index].child[2].check;
        $scope.showCancelAppointment = jsondata[index].child[3].check;
        $scope.showReplaceLocation = jsondata[index].child[4].check;
        $scope.showMgmt = jsondata[index].child[5].check;
        $scope.showButtonEstimateInvoice = jsondata[index].child[6].check;
        $scope.viewListenAudio = jsondata[index].child[7].check;
        $scope.viewDispathLog = jsondata[index].child[8].check;
        $scope.jobsiteARC = jsondata[index].child[0].child[6].check;
        $scope.viewDownload = true;
        $scope.renameDelete = true;
      } else {
        localStorage.setItem("login_status", "0");
        redirectTo('index.html');
      }
      break;
      case 'opportunities.html':
      $scope.$emit('getJsonFromSchedule', {
        data: args.data
      });
      break;
    }
  });
});

function loadSelectApp(btnId, recordingfile, customer_type) {
  appScope.recordingfile = recordingfile;
  appScope.getAppointmentgroups();
  appScope.check_order = 0;
  if (parseInt(customer_type) > 0) {
    appScope.addAppointmentsData.customertype_id = customer_type;
  } else {
    appScope.addAppointmentsData.customertype_id = customer_type_new_customer_id;
  }
  if (appScope.customertypes != undefined) {
    for (var i = 0; i < appScope.customertypes.length; i++) {
      var row = appScope.customertypes[i];
      if (parseInt(row.id) == parseInt(appScope.addAppointmentsData.customertype_id)) {
        setTimeout(function() {
          $('input[name=selectedCusTypeName]').val(row.name);
        }, 1500);
      }
    }
  }
}

function addTaskDownTime(user_id) {
  appScope.getAssign(user_id);
}

function WorkingInvoice(check_order) {
  appScope.check_order = check_order;
}
// scheduleApp.controller('scheduleDetailCtrl', function($scope) {})
