var signaturePad;
var autocompleteClass;
orderApp.controller('orderCtrl', function($ionicActionSheet, $ionicHistory, $cordovaFile, $cordovaActionSheet, $cordovaCamera, //
  $cordovaFileTransfer, $cordovaImagePicker, $ionicScrollDelegate, $location, $timeout, $cordovaToast, $ionicLoading, $ionicPopup, //
  $scope, $http, $window, $interval, $sce, Login, Orders, Orderstatuses, Ordertypes, Services, Products, $stateParams, $cordovaInAppBrowser, //
  dataHtml, Users, Customers, Appointments, Appointmentstatuses, $cordovaKeyboard, Opportunities) {
  // Tab Order Handle
  $scope.tabOrderActive = 'Estimate';
  $scope.toggleTemplate = "appointment-history-item";
  $scope.setTabOrder = function(tab) {
    $scope.tabOrderActive = tab;
  }
  // Order Estimate Detail Option Handle
  orderEstimateDetailOptionHandle();

  function orderEstimateDetailOptionHandle() {
    toggleDelegateHandle('#order_page', '.link-order-estimate-detail-option', '.order-estimate-detail-option');
    closeOutsideHandle('.link-order-estimate-detail-option, .order-estimate-detail-option', '.order-estimate-detail-option');
  }
  // Order Invoice Detail Option Handle
  orderInvoiceDetailOptionHandle();

  function orderInvoiceDetailOptionHandle() {
    toggleDelegateHandle('#order_page', '.link-order-invoice-detail-option', '.order-invoice-detail-option');
    closeOutsideHandle('.link-order-invoice-detail-option, .order-invoice-detail-option', '.order-invoice-detail-option');
  }
  $scope.currentPage = 1;
  $scope.currentIdLogin = currentIdLogin;
  // var pager = localStorage.getItem('orders_pagesize');
  var pager = 200;
  $scope.itemsPerPage = pager ? pager : 5;
  $scope.entryLimit = $scope.itemsPerPage;
  // edit by haudao
  //  $scope.style_order="";
  // var currenURL = $ionicHistory.currentView().url;
  // var urlArray = currenURL.split("?");
  // if (urlArray) {
  //     var strParam = urlArray[urlArray.length - 1];
  //     var arrParam = strParam.split("&");
  //     $scope.customerId = parseInt(arrParam[0]);
  //     $scope.appointment_id = parseInt(arrParam[1]);
  //     if(arrParam[2]) $scope.style_order=arrParam[2];
  // }

  $scope.style_order = $stateParams.style;
  $scope.customerId = $stateParams.customersID;
  $scope.appointment_id = $stateParams.orderID;
  $scope.backPage = $stateParams.backPage;
  $scope.appID = $stateParams.appID;
  $scope.orgPage = getParameterByName('org_page');

  // end edit
  $scope.searchOrders = {
    rows: $scope.itemsPerPage,
    current_page: $scope.currentPage,
    search: "",
    customerId: $scope.customerId
  };
  $scope.roleName = role;
  $scope.isAdmin = isAdmin;
  $scope.isManager = isManager;
  $scope.isReporter = isReporter;
  $scope.isScheduler = isScheduler;
  $scope.isFieldinstaller = isFieldinstaller;
  $scope.isSalesman = isSalesman;
  $scope.isWarehouse = isWarehouse;
  $scope.departmentId = departmentId;
  $scope.check_init_product = false;
  $scope.dataOrderHtml = {};
  $scope.currentuserId = currentIdLogin;
  $scope.redirectFromAppointment = false;
  $scope.messageJobstatus = {};
  $scope.messageJobstatus.value = '';
  $scope.dataSendMail = {};
  $scope.dataSendMail.mail2 = '';
  $scope.dataCounterForAppDetail = {};
  $scope.tier = tier;
  $scope.NoCAIdString = NoCAId.toString();
  $scope.NoCaText = 'No CA';
  $scope.differentNoCaAndRouteColor = differentNoCaAndRouteColor;
  if ($scope.tier.t1) {
    $scope.NoCAIdString = NoCAId.toString();
    $scope.NoCaText = 'No CA';
    $scope.differentNoCaAndRouteColor = differentNoCaAndRouteColor;
  }
  $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.estimateCounterAppDetail = 0;
  $scope.invoiceCounterAppDetail = 0;
  $scope.dataCounterForAppDetail = {};
  $scope.selectJobIdArr = [];

  $scope.viewOfficeNoteAppHistory = false;
  $scope.viewFieldWorkerNotesAppHistory = false;
  $scope.officeNoteAppHistory = '';
  $scope.fieldWorkerNotesAppHistory = '';
  $scope.showNoAttacRecored = true;
  $scope.noAttackClicked = false;
  $scope.dataTypeFile = false;
  $scope.dataSlider = {};
  $scope.modePhotoView = 'hd';
  if (!$scope.dataViewAppNote) {
    $scope.dataViewAppNote = {};
  }
  $scope.dataViewAppNote = {};
  $scope.tempDataNote = {};
  $scope.dataSaveOfficeNote = {};
  $scope.dataSaveFieldWorkerNote = {};
  $scope.detailAppointmentData = "";
  $scope.autocompleteList = {};
  $scope.autocompleteList.dataAppType = [];
  $scope.invalid_card_number = false;

  $scope.monthNames = [{
    name: 'January',
    value: 1
  }, {
    name: 'February',
    value: 2
  }, {
    name: 'March',
    value: 3
  }, {
    name: 'April',
    value: 4
  }, {
    name: 'May',
    value: 5
  }, {
    name: 'June',
    value: 6
  }, {
    name: 'July',
    value: 7
  }, {
    name: 'August',
    value: 8
  }, {
    name: 'September',
    value: 9
  }, {
    name: 'October',
    value: 10
  }, {
    name: 'November',
    value: 11
  }, {
    name: 'December',
    value: 12
  }];
  var info_mail = 'info@reliablegaragedoor.com';

  $scope.year_select = function() {
    var year = [];
    min = parseInt(new Date().getFullYear()); //Make string input int
    max = min + 10;
    for (var i = min; i < max; i++) {
      year.push(i);
    }
    $scope.yearName = year;
  };
  $scope.year_select();

  $scope.renderTemplateData = function() {
    dataHtml.getTemplate('templates/dashboard/order/orderMenuHeadermodal.tpl').success(function(results) {
      $scope.dataOrderHtml.menuHeader = results;
      dataHtml.getTemplate('templates/dashboard/order/orderMenuTabmodal.tpl').success(function(results) {
        $scope.dataOrderHtml.menuTab = results;
        dataHtml.getTemplate('templates/dashboard/order/orderContentmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.orderContent = results;
          $timeout(function() {
            setHeight("#main-content");
          }, 1)
          $scope.getUsers();
        });
      });
    });
  }
  $scope.openByGetTemplate = function(style) {
    $ionicLoading.show({ template: templateLoading });
    $timeout(function() {
      switch (style) {
        case 'popupOrderEstimateDetail':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupDetailsmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateDetail = results;
          $scope.showTarget('#popupOrderEstimateDetail');
        });
        break;
        case 'popupOrderEstimateDetailOptions':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupOptionsmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateDetailOptions = results;
          $scope.showTarget('#popupOrderEstimateDetailOptions');
          $ionicLoading.hide();
        });
        break;
        case 'popupOrderEstimateDetailOptionsItems':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupOptionsItemsmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateDetailOptionsItems = results;
          $scope.showTarget('#popupOrderEstimateDetailOptionsItems');
          $ionicLoading.hide();
        });
        break;
        case 'popupOrderEstimateDetailEditMDAllItem':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupDetailEditMDAllItemmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateDetailEditMDAllItem = results;
          $scope.showTarget('#popupOrderEstimateDetailEditMDAllItem');
          $ionicLoading.hide();
        });
        break;
        case 'popupOrderEstimateDetailItemEdit':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupDetailItemEditmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateDetailItemEdit = results;
          $scope.showTarget('#popupOrderEstimateDetailItemEdit');
          $ionicLoading.hide();
        });
        break;
        case 'popupOrderEstimateDetailItemDelete':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupDetailItemDeletemodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateDetailItemDelete = results;
          $scope.showTarget('#popupOrderEstimateDetailItemDelete');
          $ionicLoading.hide();
        });
        break;
        case 'popupOrderEstimateDetailItemTransfer':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupDetailItemTransfermodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateDetailItemTransfer = results;
          $scope.showTarget('#popupOrderEstimateDetailItemTransfer');
          $ionicLoading.hide();
        });
        break;
        case 'popupOrderEstimateDoorFormProductTable':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupDoorFormProductTablesmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateDoorFormProductTable = results;
          $timeout(function() {
            $scope.showTarget('#popupOrderEstimateDoorFormProductTable');
            $ionicLoading.hide();
          }, 500);
        });
        break;
        case 'popupOrderEstimateMeasurements':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupMeasurementPagemodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateMeasurements = results;
          $timeout(function() {
            $scope.showTarget('#popupOrderEstimateMeasurements');
            $ionicLoading.hide();
          }, 500);
        });
        break;
        case 'popupOrderEstimateSendToDetail':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupSendToDetailmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateSendToDetail = results;
          $timeout(function() {
            $scope.showTarget('#popupOrderEstimateSendToDetail');
            $ionicLoading.hide();
          }, 500);
        });
        break;
        case 'popupOrderEstimateSendToOptions':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupSendToOptionsmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateSendToOptions = results;
          $timeout(function() {
            $scope.showTarget('#popupOrderEstimateSendToOptions');
            $ionicLoading.hide();
          }, 500);
        });
        break;
        case 'popupOrderEstimateDetailAddComment':
        dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupDetailAddCommentmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.popupOrderEstimateDetailAddComment = results;
          $timeout(function() {
            $scope.showTarget('#popupOrderEstimateDetailAddComment');
            $ionicLoading.hide();
          }, 500);
        });
        break;
          // invoice

          case 'popupOrderInvoiceDetail':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupDetailsmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetail = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceDetail');
            }, 500);
          });
          break;
          case 'popupOrderInvoiceDetailOptions':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupOptionsmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailOptions = results;
            $scope.showTarget('#popupOrderInvoiceDetailOptions');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailOptionsItems':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupOptionsItemsmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailOptionsItems = results;
            $scope.showTarget('#popupOrderInvoiceDetailOptionsItems');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailEditMDAllItem':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupDetailEditMDAllItemmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailEditMDAllItem = results;
            $scope.showTarget('#popupOrderInvoiceDetailEditMDAllItem');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailEditRefund':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupDetailEditRefundmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailEditRefund = results;
            $scope.showTarget('#popupOrderInvoiceDetailEditRefund');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailItemEdit':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupDetailItemEditmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailItemEdit = results;
            $scope.showTarget('#popupOrderInvoiceDetailItemEdit');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailItemDelete':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupDetailItemDeletemodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailItemDelete = results;
            $scope.showTarget('#popupOrderInvoiceDetailItemDelete');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDoorFormProductTable':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupDoorFormProductTablesmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDoorFormProductTable = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceDoorFormProductTable');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceMeasurements':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupMeasurementPagemodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceMeasurements = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceMeasurements');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceTermsOfConditions':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupPaymentTermsConditionsmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceTermsOfConditions = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceTermsOfConditions');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceAddPayment':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupPaymentAddmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceAddPayment = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceAddPayment');
              $ionicScrollDelegate.$getByHandle('scrollPaymentAdd').scrollTop(true);
              $ionicScrollDelegate.$getByHandle('scrollPaymentAdd').resize();
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceAddPaymentSignature':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupPaymentAddSignaturemodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceAddPaymentSignature = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceAddPaymentSignature');
              $ionicScrollDelegate.$getByHandle('scrollPaymentAdd').scrollTop(true);
              $ionicScrollDelegate.$getByHandle('scrollPaymentAdd').resize();
              $ionicLoading.hide();
              canvas = document.getElementById('signatureCanvas');
              signaturePad = new SignaturePad(canvas);
              var h = $('#signature_position .center').height();
              var w = $('#signature_position .center').width();
              var default_ratio = h / w;

              function resizeCanvas() {
                var new_h = $('#signature_position .center').height();
                var new_W = (new_h / default_ratio);
                $('#signature_position .center').width(new_W);
                $('#signature_position .center').height(new_h);
                var dataURL = signaturePad.toDataURL();
                var ratio = Math.max(window.devicePixelRatio || 1, 1);
                canvas.width = canvas.offsetWidth * ratio;
                canvas.height = canvas.offsetHeight * ratio;
                canvas.getContext("2d").scale(ratio, ratio);
                signaturePad.fromDataURL(dataURL);
              }
              window.addEventListener("resize", resizeCanvas);
              resizeCanvas();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceAddPaymentDetails':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupPaymentAddDetailsmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceAddPaymentDetails = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceAddPaymentDetails');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceSendToDetail':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupSendToDetailmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceSendToDetail = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceSendToDetail');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceSendToOptions':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupSendToOptionsmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceSendToOptions = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceSendToOptions');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceDetailAddComment':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupDetailAddCommentmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailAddComment = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceDetailAddComment');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          // all
          case 'popupOrderDisplayHeightToInchesTable':
          dataHtml.getTemplate('templates/dashboard/order/orderPopupDisplayHeightToInchesTablemodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderDisplayHeightToInchesTable = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderDisplayHeightToInchesTable');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceDetailAddPaymentWellFargoPlan':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupOrderInvoiceDetailAddPaymentWellFargoPlan.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailAddPaymentWellFargoPlan = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceDetailAddPaymentWellFargoPlan');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupConfirmAddPaymentInstoreCredit':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupConfirmAddPaymentInstoreCredit.tpl').success(function(results) {
            $scope.dataOrderHtml.popupConfirmAddPaymentInstoreCredit = results;
            $timeout(function() {
              $scope.showTarget('#popupConfirmAddPaymentInstoreCredit');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'confirmOverPayment':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupConfirmOverPayment.tpl').success(function(results) {
            $scope.dataOrderHtml.confirmOverPayment = results;
            $timeout(function() {
              $scope.showTarget('#confirmOverPayment');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupWarningAddUpdateCard':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupWarningAddUpdateCard.tpl').success(function(results) {
            $scope.dataOrderHtml.popupWarningAddUpdateCard = results;
            $timeout(function() {
              $scope.showTarget('#popupWarningAddUpdateCard');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceDetailPaymentInformation':
          dataHtml.getTemplate('templates/dashboard/order/invoice/InvoicePopupOrderInvoiceDetailPaymentInformation.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailPaymentInformation = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceDetailPaymentInformation');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'popupOrderInvoiceDetailPaymentInformationTranferPayment':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupOrderInvoiceDetailPaymentInformationTranferPayment.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailPaymentInformationTranferPayment = results;
            $timeout(function() {
              $scope.showTarget('#popupOrderInvoiceDetailPaymentInformationTranferPayment');
              $ionicLoading.hide();
            }, 500);
          });
          break;
          case 'photoViewer':
          dataHtml.getTemplate('templates/dashboard/schedules/appointment/photoViewer.tpl').success(function(results) {
            $scope.dataOrderHtml.photoViewer = results;
            $scope.showTarget('#photoViewer');
            $ionicLoading.hide();
          });
          break;
          case 'customerDetailPopupAppointmentHistoryViewLog':
          dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailPopupAppointmentHistoryViewLogmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.customerDetailPopupAppointmentHistoryViewLog = results;
            $scope.showTarget('#customerDetailPopupAppointmentHistoryViewLog');
            $ionicLoading.hide();
          });
          break;
          case 'popupPendingToEnroutemodal':
          dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupPendingToEnroutemodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupPendingToEnroutemodal = results;
            $scope.showTarget('#popupPendingToEnroutemodal');
            $ionicLoading.hide();
          });
          break;
          case 'popupEnrouteToArivemodal':
          dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupEnrouteToArivemodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupEnrouteToArivemodal = results;
            $scope.showTarget('#popupEnrouteToArivemodal');
            $ionicLoading.hide();
          });
          break;
          case 'popupAriveToWorkingmodal':
          dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupAriveToWorkingmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupAriveToWorkingmodal = results;
            $scope.showTarget('#popupAriveToWorkingmodal');
            $ionicLoading.hide();
          });
          break;
          case 'popupWorkingToFinishmodal':
          dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupWorkingToFinishmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupWorkingToFinishmodal = results;
            $scope.showTarget('#popupWorkingToFinishmodal');
            $ionicLoading.hide();
          });
          break;
          case 'popupPendingToEnrouteCAmodal':
          dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupPendingToEnrouteCAmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupPendingToEnrouteCAmodal = results;
            $scope.showTarget('#popupPendingToEnrouteCAmodal');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderDetailMessageJobStatus':
          dataHtml.getTemplate('templates/dashboard/order/popupOrderDetailMessageJobStatus.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderDetailMessageJobStatus = results;
            $scope.showTarget('#popupOrderDetailMessageJobStatus');
            $ionicLoading.hide();
          });
          break;
          case 'invoicePopupDetailEditMDInstalledItem':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupDetailEditMDInstalledItemmodal.tpl').success(function(results) {
            $scope.dataOrderHtml.invoicePopupDetailEditMDInstalledItem = results;
            $scope.showTarget('#invoicePopupDetailEditMDInstalledItem');
            $ionicLoading.hide();
          });
          break;
          case 'popupOdersSendEmail':
          dataHtml.getTemplate('templates/dashboard/order/popupOdersSendEmail.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOdersSendEmail = results;
            $scope.showTarget('#popupOdersSendEmail');
            $timeout(function(val) {
              $('#inputagarea input').attr('readonly', 'readonly');
            }, 10);
            $ionicLoading.hide();
          });
          break;
          case 'estimatePopupReminder':
          dataHtml.getTemplate('templates/dashboard/order/estimate/estimatePopupReminder.tpl').success(function(results) {
            $scope.dataOrderHtml.estimatePopupReminder = results;
            $scope.showTarget('#estimatePopupReminder');
            $ionicLoading.hide();
          });
          break;
          case 'invoicePopupReminder':
          dataHtml.getTemplate('templates/dashboard/order/invoice/invoicePopupReminder.tpl').success(function(results) {
            $scope.dataOrderHtml.invoicePopupReminder = results;
            $scope.showTarget('#invoicePopupReminder');
            $ionicLoading.hide();
          });
          break;
          case 'orderPopupProductMessage':
          dataHtml.getTemplate('templates/dashboard/order/popupProductMessage.tpl').success(function(results) {
            $scope.dataOrderHtml.orderPopupProductMessage = results;
            $scope.showTarget('#orderPopupProductMessage');
            $ionicLoading.hide();
          });
          break;
          case 'orderInvoicePopupProductMessage':
          dataHtml.getTemplate('templates/dashboard/order/popupProductMessage.tpl').success(function(results) {
            $scope.dataOrderHtml.orderInvoicePopupProductMessage = results;
            $scope.showTarget('#orderInvoicePopupProductMessage');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderEstimateDetailComment':
          dataHtml.getTemplate('templates/dashboard/order/estimate/popupOrderEstimateDetailComment.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderEstimateDetailComment = results;
            $scope.showTarget('#popupOrderEstimateDetailComment');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderEstimateDetailDiscountCoupon':
          dataHtml.getTemplate('templates/dashboard/order/estimate/popupOrderEstimateDetailDiscountCoupon.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderEstimateDetailDiscountCoupon = results;
            $scope.showTarget('#popupOrderEstimateDetailDiscountCoupon');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderEstimateDetailServiceLocation':
          dataHtml.getTemplate('templates/dashboard/order/estimate/popupOrderEstimateDetailServiceLocation.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderEstimateDetailServiceLocation = results;
            $scope.showTarget('#popupOrderEstimateDetailServiceLocation');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderEstimateDetailEstimateInvoice':
          dataHtml.getTemplate('templates/dashboard/order/estimate/popupOrderEstimateDetailEstimateInvoice.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderEstimateDetailEstimateInvoice = results;
            $scope.showTarget('#popupOrderEstimateDetailEstimateInvoice');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderEstimateDetailSaleDetailOption':
          dataHtml.getTemplate('templates/dashboard/order/estimate/popupOrderEstimateDetailSaleDetailOption.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderEstimateDetailSaleDetailOption = results;
            $scope.showTarget('#popupOrderEstimateDetailSaleDetailOption');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDoorFormProductTable':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupOrderInvoiceDoorFormProductTable.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDoorFormProductTable = results;
            $scope.showTarget('#popupOrderInvoiceDoorFormProductTable');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailAddPayment':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupOrderInvoiceDetailAddPayment.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailAddPayment = results;
            $scope.showTarget('#popupOrderInvoiceDetailAddPayment');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetail50PercentTotalBill':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupOrderInvoiceDetail50PercentTotalBill.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetail50PercentTotalBill = results;
            $scope.showTarget('#popupOrderInvoiceDetail50PercentTotalBill');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailComment':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupOrderInvoiceDetailComment.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailComment = results;
            $scope.showTarget('#popupOrderInvoiceDetailComment');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailDiscountCoupon':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupOrderInvoiceDetailDiscountCoupon.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailDiscountCoupon = results;
            $scope.showTarget('#popupOrderInvoiceDetailDiscountCoupon');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailServiceLocation':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupOrderInvoiceDetailServiceLocation.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailServiceLocation = results;
            $scope.showTarget('#popupOrderInvoiceDetailServiceLocation');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailEstimateInvoice':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupOrderInvoiceDetailEstimateInvoice.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailEstimateInvoice = results;
            $scope.showTarget('#popupOrderInvoiceDetailEstimateInvoice');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailSaleDetailOption':
          dataHtml.getTemplate('templates/dashboard/order/invoice/popupOrderInvoiceDetailSaleDetailOption.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailSaleDetailOption = results;
            $scope.showTarget('#popupOrderInvoiceDetailSaleDetailOption');
            $ionicLoading.hide();
          });
          break;
          case 'popupCustomerPhonesList':
          dataHtml.getTemplate('templates/dashboard/order/popupCustomerPhonesList.tpl').success(function(results) {
            $scope.dataOrderHtml.popupCustomerPhonesList = results;
            $scope.showTarget('#popupCustomerPhonesList');
            $ionicLoading.hide();
          });
          break;
          case 'popupOrderInvoiceDetailAppointmentHistory':
          dataHtml.getTemplate('templates/dashboard/order/popupOrderInvoiceDetailAppointmentHistory.tpl').success(function(results) {
            $scope.dataOrderHtml.popupOrderInvoiceDetailAppointmentHistory = results;
            $scope.showTarget('#popupOrderInvoiceDetailAppointmentHistory');
            $ionicLoading.hide();
          });
          break;
          case 'popupSelectAllItemEstimate':
          dataHtml.getTemplate('templates/dashboard/order/popupSelectAllItemEstimate.tpl').success(function(results) {
            $scope.dataOrderHtml.popupSelectAllItemEstimate = results;
            $scope.showTarget('#popupSelectAllItemEstimate');
            $ionicLoading.hide();
          });
          break;
          case 'popupSelectAllItemInvoice':
          dataHtml.getTemplate('templates/dashboard/order/popupSelectAllItemInvoice.tpl').success(function(results) {
            $scope.dataOrderHtml.popupSelectAllItemInvoice = results;
            $scope.showTarget('#popupSelectAllItemInvoice');
            $ionicLoading.hide();
          });
          break;
          case 'popupRetrySentMessegemodal':
          dataHtml.getTemplate('templates/dashboard/schedules/appointment/popupRetrySentMessegemodal.tpl').success(function(results) {
            $scope.dataOrderHtml.popupRetrySentMessegemodal = results;
            $scope.showTarget('#popupRetrySentMessegemodal');
            $ionicLoading.hide();
          });
          break;
          case 'popupConvertToSaleOrder':
          dataHtml.getTemplate('templates/dashboard/order/estimate/popupConvertToSaleOrder.tpl').success(function(results) {
            $scope.dataOrderHtml.popupConvertToSaleOrder = results;
            $scope.showTarget('#popupConvertToSaleOrder');
            $ionicLoading.hide();
          });
          break;
          case 'popupAddApp':
          dataHtml.getTemplate('templates/dashboard/order/estimate/popupAddApp.tpl').success(function(results) {
            $scope.dataOrderHtml.popupAddApp = results;
            $scope.showTarget('#popupAddApp');
            $ionicLoading.hide();
          });
          break;
          case 'popupCheckContractorAndPricing':
          dataHtml.getTemplate('templates/dashboard/order/estimate/popupCheckContractorAndPricing.tpl').success(function(results) {
            $scope.dataOrderHtml.popupCheckContractorAndPricing = results;
            $scope.showTarget('#popupCheckContractorAndPricing');
            $ionicLoading.hide();
          });
          break;
          case 'opportunityAppointmentSpecificInformation':
          dataHtml.getTemplate('templates/dashboard/opportunities/form/opportunityappointmentspecificInformation.tpl').success(function(results) {
            $scope.dataOrderHtml.opportunityAppointmentSpecificInformation = results;
            $timeout(function() {
              $scope.showTarget('#opportunityAppointmentSpecificInformation');
              $scope.setValueShowSelect('selectedCallAhead', 'seletedCallAheadName', '');
              $ionicScrollDelegate.$getByHandle('scrollAppointmentSpecificInfor').scrollTop(true);
              $ionicLoading.hide();
            }, 1000)
          });
          break;
          case 'popupSplitPayment':
          dataHtml.getTemplate('templates/dashboard/order/popupSplitPayment.tpl').success(function(results) {
            $scope.dataOrderHtml.popupSplitPayment = results;
            $scope.showTarget('#popupSplitPayment');
            $ionicLoading.hide();
          });
          break;
          case 'popupAddPaymentMulti':
          dataHtml.getTemplate('templates/dashboard/order/popupAddPaymentMulti.tpl').success(function(results) {
            $scope.dataOrderHtml.popupAddPaymentMulti = results;
            $scope.showTarget('#popupAddPaymentMulti');
            $ionicLoading.hide();
          });
          break;
          case 'confirmOverSplitPayment':
          dataHtml.getTemplate('templates/dashboard/order/popupConfirmOverSplitPayment.tpl').success(function(results) {
            $scope.dataOrderHtml.confirmOverSplitPayment = results;
            $scope.showTarget('#confirmOverSplitPayment');
            $ionicLoading.hide();
          });
          break;
          case 'popupCornerstyles':
          case 'popupCornerstylesInv':
            dataHtml.getTemplate('templates/dashboard/order/estimate/cornerstylesPopup.tpl').success(function(results) {
              $scope.dataOrderHtml.popupCornerstyles = results;
              $scope.showTarget(style == 'popupCornerstyles'? '#popupCornerstyles':'#popupCornerstylesInv');
              $ionicLoading.hide();
            });
            break;
       

        }
      }, 500);
}

$scope.getUsers = function() {
  $scope.userFollow = [];
  $ionicLoading.show({ template: templateLoading });
  Users.getSelect().success(function(data) {
    if (!startpage)
      $ionicLoading.hide();
    $scope.allUser = [];
    _.each(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,
        cell_phone: val.cell_phone,
        office_phone: val.office_phone
      }
      $scope.allUser.push(_item);
    });
    $scope.getWarranty();
  });
};
var start = true;
$scope.getOrders = function() {
  $ionicLoading.show({
    template: templateLoading
  });
  Orders.getPaging($scope.searchOrders).success(function(data) {
    $scope.dataJobsite = data.jobsite;
    $scope.coupon = data.coupon;
    if (start === true) {
      start = false;
      if ($scope.style_order == "new") {
        parseInt($scope.appointment_id) > 0 ? $scope.redirectFromAppointment = true : $scope.redirectFromAppointment = false;
        $scope.newEstimate($scope.appointment_id);
        console.log($scope.appointment_id);
        $scope.getDetailAppointment($scope.appointment_id);
      }
      if ($scope.style_order == 'estimate') {
        var estimate_id = $scope.appointment_id;
        parseInt(estimate_id) > 0 ? $scope.redirectFromAppointment = true : $scope.redirectFromAppointment = false;
        $scope.appointment_id = 0;
        $scope.goToEstimateDetails(estimate_id, 0);
      }
      if ($scope.style_order == 'invoice') {
        var invoice_id = $scope.appointment_id;
        parseInt(invoice_id) > 0 ? $scope.redirectFromAppointment = true : $scope.redirectFromAppointment = false;
        $scope.appointment_id = 0;
        $scope.goToInvoiceDetails(invoice_id, 0);
      }
      if ($scope.style_order == 'saleorder') {
        var saleorder_id = $scope.appointment_id;
        parseInt(saleorder_id) > 0 ? $scope.redirectFromAppointment = true : $scope.redirectFromAppointment = false;
        $scope.appointment_id = 0;
        $scope.goToSaleorderDetails(saleorder_id, 0);
      }
    }

    $scope.Estimate = data.Estimate;
    $scope.Invoice = data.Invoice;
    $scope.SaleOrder = data.SaleOrder;
    $scope.customername = data.customer_data;
    $scope.primaryphone = data.primaryphone;
    $scope.additionalphones = data.additionalphones;
    $scope.detailCustomerData = data.customer_info;
    $scope.customer_info = data.customer_info;
    $scope.usercredentials = data.usercredentials;
    $scope.credittermplans = data.credittermplans;
    $scope.resetSplitPayment();
    if ($scope.Invoice.length == 0) {
      $scope.Invoice = [{}];
    }
    if ($scope.Estimate.length == 0) {
      $scope.Estimate = [{}];
    }
    $scope.total_instore_credit = data.total_instore_credit;
    $scope.InvoiceCanBePaid = _.filter(data.Invoice_SalesOrder, function(item, index) {
      return parseFloat(item.balanceDue) > 0;
    });
    $ionicLoading.hide();
    startpage = false;
    $scope.replaceRes();
    !$scope.check_init_product ? $interval($scope.checkLogin, time_refresh) : '';
    request_notify_get_chat = true;
    $scope.check_init_product = true;
    $scope.getAllAppointmentHistoryByCustomer($scope.customerId);
  });
};
$scope.checkToCall = function() {
  if ($scope.additionalphones.length > 0) {
    $scope.openByGetTemplate('popupCustomerPhonesList');
  } else {
    $scope.clickToCall($scope.primaryphone);
  }
}
$scope.clickToCall = function(phone_number) {
  $scope.$emit('clickToCallNumber', {
    phone_number: phone_number
  });
}
$scope.searchChanged = function() {
  $scope.getOrders();
}
$scope.sizeChanged = function() {
  $scope.searchOrders.rows = $scope.entryLimit;
  orders_pagesize.val($scope.searchOrders.rows);
  localStorage.setItem('orders_pagesize', $scope.searchOrders.rows);
  $scope.searchOrders.current_page = 1;
  $scope.getOrders();
}
$scope.pageChanged = function() {
  console.log($scope.currentPage);
  $scope.searchOrders.current_page = $scope.currentPage;
  $scope.getOrders();
};
$scope.setPage = function(pageNo) {
  $scope.currentPage = pageNo;
  console.log('doi page');
};

$scope.replaceRes = function() {
  setTimeout(function() {
    $scope.$apply(function(val) {
      if (val) {
        if ($scope.Invoice.length > 0) {
          if ($scope.Invoice[0].invoice_no == undefined && $scope.Invoice[0].id == undefined) {
            $scope.Invoice = [];
          }
        }
        if ($scope.Estimate.length > 0) {
          if ($scope.Estimate[0].invoice_no == undefined && $scope.Estimate[0].id == undefined) {
            $scope.Estimate = [];
          }
        }
      }
    });
  }, 1);
}

$scope.dataChangePassword = {};

  // edit by haudao
  $scope.typeOfService = [{ id: "0", name: "Repair" }, { id: "-1", name: "Installation" }, { id: "4", name: "Contractor" }, { id: "6", name: "Walk In" }, { id: "2", name: "Commercial" }, { id: "1", name: "Wholesale" }];
  $scope.optionOfService = [{ id: "5", name: "Retail" }, { id: "7", name: "Customer Aquisition" }];


  $scope.getWarranty = function() {
    $ionicLoading.show({ template: templateLoading });
    Products.getWarranty().success(function(data) {
      if (!startpage)
        $ionicLoading.hide();
      $scope.Warrantydata = data;
      $scope.getOrders();
    });
  }
  $scope.Input_value = {};
  $scope.setValueInput = function(id, arrData) {
    var index = _.findLastIndex(arrData, {
      id: id
    });
    if (index >= 0)
      return arrData[index].name;
  }


  $scope.goToEstimateDetails = function(id, order_no) {
    $scope.openByGetTemplate('popupOrderEstimateDetail');
    $timeout(function() {
      $scope.$broadcast('estimateDetail', {
        estimate_id: id,
        customer_id: $scope.customerId,
        appointment_id: $scope.appointment_id,
        redirectFromAppointment: $scope.redirectFromAppointment,
        countAppHistories: $scope.allAppointmentHistoryData.length
      });
      $scope.order_no = order_no;
      $scope.order_id = id;
    }, 500);
  }
  $scope.newEstimate = function(app_id) {
    $scope.detailAppointmentData = null;
    var appointment_id = 0;
    if (app_id > 0){
      appointment_id = app_id;
    }
    $scope.$broadcast('newEstimate', {
      customer_id: $scope.customerId,
      jobsite: $scope.dataJobsite,
      appointment_id: appointment_id,
    });
    $scope.openByGetTemplate('orderEstimateDetail');
  }
  $scope.goToInvoiceDetails = function(id, order_no) {
    $scope.openByGetTemplate('popupOrderInvoiceDetail');
    $timeout(function() {
      $scope.$broadcast('invoiceDetail', {
        invoice_id: id,
        redirectFromAppointment: $scope.redirectFromAppointment,
        countAppHistories: $scope.allAppointmentHistoryData.length
      });
      $scope.order_no = order_no;
      $scope.order_id = id;
    }, 500);
  }
  $scope.goToSaleorderDetails = function(id, order_no) {
    $scope.openByGetTemplate('popupOrderInvoiceDetail');
    $timeout(function() {
      $scope.$broadcast('saleorderDetail', {
        saleorder_id: id,
        redirectFromAppointment: $scope.redirectFromAppointment,
        countAppHistories: $scope.allAppointmentHistoryData.length
      });
      $scope.order_no = order_no;
      $scope.order_id = id;
    }, 500);
  }
  $scope.openAutocomplete = function(className) {
    if (autocompleteClass != undefined) {
      $('.' + autocompleteClass).css('display', 'block');
    }
    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.resizeScroll = function(id) {
    $ionicScrollDelegate.$getByHandle(id).resize();
  }
  $scope.$on('sendtotal', function(event, args) {
    $scope.Total = args.total;
    $scope.pushChatRoom = args.pushchatroom;
    $scope.order_jobsite = args.order_jobsite;
    $scope.detailAppointmentData = args.appointment;
    $scope.customertype_id = args.customertype_id;
    $scope.order_id = args.order_id;
    $scope.$apply(function(val) {
      $scope.order_no = args.order_no;
      if ($scope.detailAppointmentData != '') {
        $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.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.countOther = item.files.length - (item.countPhoto + item.countPdf);
          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.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 ($scope.selectJobIdArr.indexOf(item.id) < 0 && item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        returnValue.items.push(item);
      }
    });
    return returnValue;
  }
  $scope.onRemoveJobsite = function(callback) {
    //$scope.initialJobsiteFilter = [""];
    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 = $scope.filterJobsiteArr.indexOf(callback.item);
    $scope.filterJobsiteArr.splice(indexA, 1);
  }
  $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);
        }
      }
    }
  }

  $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];
      }
    }
    return {};
  };

  $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.initialJobsiteFilter = $scope.selectJobIdArr;
  }

  $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.customerId }).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.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.viewEstimateCounter = 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.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.openPhotoViewer = function(type) {
    if ($scope.noAttackClicked) {
      if (type == 'estimate') {
        $scope.indexSlide = 0;
      }
      if (type == 'invoice') {
        $scope.indexSlide = $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.activeIndex = $scope.indexSlide;

    $scope.openByGetTemplate('photoViewer');
    $timeout(function(val) {
      if ($scope.selectedApp) {
        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.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.closeFileViewer = function(date) {
    if ($('.video-area video')[0] != undefined) {
      $('.video-area video')[0].pause();
    }
    $scope.closeTarget('#photoViewer');
  };

  $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.trustSrc = function(src, isview) {
    if (isview) {
      src = 'http://docs.google.com/gview?url=' + src + '&embedded=true#:0.page.20';
    }
    return $sce.trustAsResourceUrl(src);
  }
  $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.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.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);
      break;
    }
  }

  $scope.openFormSendMail = function(type) {
    if (type == "invoice") {
      $scope.$broadcast('updateinvoicebeforesentmail', {
        type: type
      });
    } else {
      $scope.$broadcast('updateestimatebeforesentmail', {
        type: type
      });
    }
  }

  $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.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 || ($scope.dataSendMail.mail1.length == 0 && $scope.dataSendMail.mail2.length == 0)) {
      $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('#popupOdersSendEmail');
      }
    });
  };


  $scope.pushJobstatusMessage = function() {
    socket.emit('new message', {
      from_user: $scope.currentIdLogin,
      room_id: $scope.pushChatRoom,
      user_id: 0,
      contents: $scope.messageJobstatus.value,
      hashtag: '',
      content_raw: $scope.messageJobstatus.value,
      applicationtype: aplicationtype.text
    });
    $scope.messageJobstatus.value = '';
    $scope.closeTarget('#popupOrderDetailMessageJobStatus');
  }
  $scope.openPopupETA = function(status) {
    if (status == 'to_enroute') {
      $scope.openByGetTemplate('popupPendingToEnroutemodal');
    }
    if (status == 'to_working') {
      $scope.openByGetTemplate('popupAriveToWorkingmodal');
    }
    $scope.currentStatusApp = status;
  }
  $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":
      $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('popupWorkingToFinishmodal');
      $scope.currentStatusApp = 'to_finish';
      break;
      case "Finishing": // Finishing to Complete
      $ionicLoading.show({ template: templateLoading });
      dataHtml.getTemplate('templates/dashboard/checklist/checklistPopupConfirmmodal.tpl').success(function(results) {
        $scope.dataOrderHtml.checklistPopupConfirm = results;
        dataHtml.getTemplate('templates/dashboard/checklist/checklistPopupmodal.tpl').success(function(results) {
          $scope.dataOrderHtml.checklistPopup = results;
          dataHtml.getTemplate('templates/dashboard/checklist/selectinvoice.tpl').success(function(results) {
            $scope.dataOrderHtml.selectInvoice = results;
            dataHtml.getTemplate('templates/dashboard/checklist/addpayment.tpl').success(function(results) {
              $scope.dataOrderHtml.addpayment = results;
              $ionicLoading.hide();
              $scope.$broadcast('checklist-popup', {
                appointment_id: $scope.detailAppointmentData.id,
                customer_id: $scope.detailAppointmentData.customer_id,
                from_order: true
              });
            });
          });
        })
      })

      break;
        // case "Complete":
        // 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 (status == 'to_finish' && $('#statusworkingPopupETA').val() == '') {
        $cordovaToast.showLongTop('Please insert required fill!!!');
        return;
      }
      $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.infor_attached = '';
      if (status == 'to_finish') {
        var inputValue = $('#statusworkingPopupETA').val();
        $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.infor_attached = inputValue;
      } else {
        if (status == 'to_enroute') {
          if(($('#etatimePopupETA').val()).length < 1){
            $cordovaToast.showLongTop('Invalid Time !');
            return false;
          }
          var inputValue = moment($('#etatimePopupETA').val(), 'hh:mmA').format('h:mm a');
          $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.infor_attached = inputValue;
        } else if (status == 'to_working') {
          if(($('#etatimePopupETC').val()).length < 1){
            $cordovaToast.showLongTop('Invalid Time !');
            return false;
          }
          var inputValue = moment($('#etatimePopupETC').val(), 'hh:mmA').format('h:mm a');
          $scope.detailAppointmentData.jobstatusCurrent.jobstatusNext.infor_attached = inputValue;
        }
      }
      $ionicLoading.show({ template: templateLoading });
      Appointmentstatuses.save($scope.detailAppointmentData.jobstatusCurrent.jobstatusNext).success(function(data) {
        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;
          }
          setTimeout(function() {
            $scope.sendPushRoom(status, inputValue);
          }, 1500);
          $scope.getDetailAppointment($scope.detailAppointmentData.id);
        } else {
          $cordovaToast.showLongTop(data.msg);
        }
      });
    }
    $scope.getDetailAppointment = function(id) {
      Appointments.show(id).success(function(data) {
        $ionicLoading.hide();
        $scope.detailAppointmentData = data;
        $scope.current_customertype_id = $scope.detailAppointmentData.customertype_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.sendPushRoom = function(status, inputValue) {
      var self_app = $scope.detailAppointmentData;
      var date = String(new Date(_.now()).dateFormat('MM/DD/YYYY')) + ' ';
      var name = _.where(self_app._userss, {
        id: self_app.fieldworker
      })[0];
      var strMsg = '';
      if (self_app.appointmentjobsites && parseInt(self_app.appointmentjobsites.id) > 0) {
        var cityInMsg = self_app.appointmentjobsites.city
      } else {
        var cityInMsg = $scope.detailCustomerData.city;
      }
      switch (status) {
        case 'to_enroute':
        date = inputValue;
        strMsg += (name.first_name + ' ' + name.last_name + "'s ETA to ");
        strMsg += (cityInMsg + ' is ');
        strMsg += date;
        $scope.socketImit(name.pushchatroom, strMsg);
        break;
        case 'to_arrived_on_site':
        // notthing
        break;
        case 'to_working':
        date = inputValue;
        strMsg += (name.first_name + ' ' + name.last_name + "'s ETC at ");
        strMsg += (cityInMsg + ' is ');
        strMsg += date;
        $scope.socketImit(name.pushchatroom, strMsg);
        break;
        case 'to_finish':
        // Field Worker Name' + â€œisâ€ + Warping Up + input message;
        strMsg += (name.first_name + ' ' + name.last_name + "'s finishing up at ");
        strMsg += (cityInMsg + ' and Completion in ');
        strMsg += inputValue;
        $scope.socketImit(name.pushchatroom, strMsg);
        break;
        case 'to_complete':
        // notthing
        break;
        default:
        break;
      }
    }
    $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.beforeAddAppointment = function() {
      $scope.addAppointmentsData = {};
      Customers.setCustomerId($scope.customer_id);
      if (!appScopeMobile.appointmentgroups) {
        appScopeMobile.getAppointmentgroups();
      }
      $scope.setValBiginWatch(true);
      if (!$scope.jobsitesByCustomer) {
        $scope.jobsitesByCustomerId($scope.customerId);
      }
      appScopeMobile.customer_id = $scope.customerId;
      appScopeMobile.addAppointmentsData.check_order = 1;
      appScopeMobile.addAppointmentsData.order_id = {
        id: $scope.order_id
      };
      if (parseInt($scope.customertype_id) > 0) {
        appScopeMobile.addAppointmentsData.customertype_id = $scope.customertype_id;
      } else {
        appScopeMobile.addAppointmentsData.customertype_id = customer_type_new_customer_id;
      }
      appScopeMobile.hideWorkingInvoice = true;
      $scope.openByGetTemplate('opportunityAppointmentSpecificInformation');
    };

    $scope.jobsitesByCustomerId = function(customerId) {
      Customers.jobsiteByCustomerId(customerId).success(function(data) {
        $scope.jobsitesByCustomer = data.data;
        $ionicLoading.hide();
      });
    }

    $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 'leadsource':
        if (parseInt($scope.addOpportunitiesData.selectCustomer.leadsource_id) == 2 || parseInt($scope.addOpportunitiesData.selectCustomer.leadsource_id) == 4) {
          $scope.showTimetable = true;
        } else {
          $scope.showTimetable = false;
        }
        break;
        case 'jobsites':
        valueData == 'Select' ? valueData = '' : valueData;
        appScopeMobile.changeJobsite(valueData);
        break;
        case 'groupfortask':
        $scope.getDataGroup($('#groupForTask').val().substring(7, $('#groupForTask').val().length));
        break;
      }
    }

    $scope.autoComplete = function(query, type) {
      var returnValue = {
        items: []
      };
      switch (type) {
        case 'appType':
        var params = {
          search: query
        };
        $ionicLoading.show({ template: templateLoading });
        Opportunities.getAppointmentType(params).success(function(data) {
          $ionicLoading.hide();
          $scope.rootDataAppointmentType = data;
          $scope.rootDataAppointmentType.forEach(function(item) {
            if ($scope.autocompleteList.dataAppType.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);
              }
            }
          });
        })
        break;
      }
      return returnValue;
    };

    $scope.clickOnItem = function(callback, type) {
      switch (type) {
        case 'apptype':
        appScopeMobile.fieldWorker(callback.item.id);
        appScopeMobile.addAppointmentsData.appointmentgroup_id = callback.item.id;
        break;
      }
    }

    $scope.setValBiginWatch = function(val) {
      $scope.$broadcast('beginScopeWatch', { value: val });
    };
    $scope.socketImit = function(room, msg_content) {
      if (socket) {
        socket.emit('new message', {
          from_user: $scope.currentIdLogin,
          room_id: room,
          user_id: 0,
          contents: msg_content,
          content_raw: msg_content,
          hashtag: '',
          applicationtype: aplicationtype.text
        });
      }
    }
    $scope.filterInvoiceCanBePaidChecked = function() {
      $scope.amount_remaining = 0;
      $scope.total_amount = 0;
      $scope.InvoiceCanBePaidChecked = _.filter($scope.InvoiceCanBePaid, function(item, index) {
        return item.is_check;
      });
      _.each($scope.InvoiceCanBePaidChecked, function(item, index) {
        $scope.total_amount += parseFloat(item.balanceDue);
        item.amount_applied = undefined;
        item.remaining_balance = item.balanceDue;
      });
      $scope.amount_remaining = 0;
    };

    $scope.resetSplitPayment = function() {
      $scope.payment_type = '';
      $scope.Cash = {};
      $scope.Check = {};
      $scope.CC_Manual = {
        first_name: $scope.customer_info.first_name,
        last_name: $scope.customer_info.last_name,
        street: $scope.customer_info.street,
        city: $scope.customer_info.city,
        state: $scope.customer_info.state,
        zipcode: $scope.customer_info.zipcode
      };
      $scope.WellFargoPlan = { credit_term_plan_number: '1148 | 6 month' };
      $scope.Credit_Memo = {};
      $scope.Manager_Credit = {};
      $scope.Instore_Credit = {};
      $scope.stateApply50 = true;
    };
    $scope.requirednumber = function(value) {
      if (!value)
        return 0;
      if (value.length == 0) {
        value = 0;
      }
      value = parseInt(value.toString().replace(/[^0-9]/g, ''));
      if (isNaN(value) == true) {
        value = 0;
      }
      return value;
    };
    $scope.requiredAmount = function(value, action, index) {
      $scope.CC_Manual.card_number = $scope.requirednumber(value);
      angular.element('#CC_Manual_card_number').validateCreditCard(function(result) {
        if (result.valid == true && result.length_valid == true && result.luhn_valid == true) {
          $scope.CC_Manual.Card_Type_cc = result.card_type.name;
          $('.logs').html(result.card_type.name + '<img class="icon_opportunities" src="resources/images/icons/checked-form-2-green.png" style="width:20px" />');
          $scope.invalid_card_number = false;
        //$('#required_CC_Manual').val(1);
      } else {
        $scope.invalid_card_number = true;
        //$('#required_CC_Manual').val(0);
        $('.logs').html('Please input card number.');
      }
    });
    }
    $scope.changePaymentType = function(payment_type) {
      if (payment_type == '' || payment_type == undefined) {
        $scope.Input_value.payment_type = 'Select Payment Type';
      } else {
        $scope.Input_value.payment_type = payment_type;
      }
      $scope.resetSplitPayment();
      $scope.payment_type = payment_type;
      if (payment_type == 'CC Manual') {
        setTimeout(function() {
          $scope.$apply(function(val) {
            addEventScan('CC_ManualScanBtn', 'autoScanManual');

          });
        }, 0);
      }
    };

    $scope.changePaymentAmount = function(index, amount_applied) {
      if (parseFloat(amount_applied) > parseFloat($scope.InvoiceCanBePaidChecked[index].balanceDue)) {
        $scope.InvoiceCanBePaidChecked[index].amount_applied = undefined;
      }
      $scope.calculatePayment(index);
    };
    $scope.calculatePayment = function(index) {
      $scope.required_form(function(amount, object_payment) {
        if (!amount) {
          return;
        }
        $scope.show100percent = amount < $scope.total_amount ? false : true;
        var total_amount = 0;
        _.each($scope.InvoiceCanBePaidChecked, function(item, index) {
          if (item.amount_applied) {
            total_amount += parseFloat(item.amount_applied);
            item.remaining_balance = parseFloat(item.balanceDue) - parseFloat(item.amount_applied);
          } else {
            item.remaining_balance = item.balanceDue;
          }
        });
        $scope.total_amount_applied = parseFloat(total_amount).toFixed(2);
        if ($scope.payment_type == 'In Store Credit' && amount > $scope.total_instore_credit) {
          $scope.Instore_Credit.Amount = 0;
          $scope.filterInvoiceCanBePaidChecked();
          return;
        }
        if (total_amount < $scope.total_amount) {
          if (total_amount >= 0 && amount >= total_amount) {
            $scope.amount_remaining = parseFloat(amount - total_amount).toFixed(2);
          } else {
            if (index) $scope.InvoiceCanBePaidChecked[index].amount_applied = undefined;
          }
        } else {
          if (amount >= total_amount) {
            $scope.amount_remaining = parseFloat(amount - total_amount).toFixed(2);
          } else {
            $scope.filterInvoiceCanBePaidChecked();
          }
        }
      });
    };

    $scope.required_form = function($callback) {
      if ($scope.payment_type == '') {
        return false;
      }
      var object_payment = { method: $scope.payment_type }
      switch ($scope.payment_type) {
        case 'Cash':
        var amount = $scope.Cash.Amount;
        object_payment.amount = amount;
        break;
        case 'Check':
        var amount = $scope.Check.Amount;
        object_payment.amount = amount;
        object_payment.check = $scope.Check.Check;
        object_payment.authorization = $scope.Check.Authorization;
        break;
        case 'CC Manual':
        var amount = $scope.CC_Manual.Amount;
        object_payment.amount = amount;
        object_payment.cardtype = $scope.CC_Manual.Card_Type_cc;
        object_payment.cardnumber = $scope.CC_Manual.card_number;
        object_payment.customerInfo = $scope.CC_Manual;
        break;
        case 'Wells Fargo Plan':
        var amount = $scope.WellFargoPlan.Amount;
        object_payment.amount = amount;
        object_payment.authorization_number = $scope.WellFargoPlan.authorization_number;
        object_payment.credit_term_plan_number = $scope.WellFargoPlan.credit_term_plan_number;
        break;
        case 'Credit Memo':
        var amount = $scope.Credit_Memo.Amount;
        object_payment.amount = amount;
        object_payment.note = $scope.Credit_Memo.note;
        break;
        case 'Manager Credit':
        var amount = $scope.Manager_Credit.Amount;
        object_payment.amount = amount;
        object_payment.note = $scope.Manager_Credit.note;
        break;
        case 'In Store Credit':
        var amount = $scope.Instore_Credit.Amount;
        object_payment.amount = amount;
        break;
      }
      $scope.payment_amount = amount;
      return $callback(amount, object_payment);
    };

    $scope.TotalBill = function(divide) {
      $scope.required_form(function(amount, payment_type, object_payment) {
        if (!amount) {
          return;
        }
        if (amount != '' && amount >= $scope.total_amount / divide) {
          var total_amount = 0;
          $scope.total_amount_applied = 0;
          _.each($scope.InvoiceCanBePaidChecked, function(item, index) {
            item.amount_applied = parseFloat(item.balanceDue) / divide;
            item.remaining_balance = parseFloat(item.balanceDue) - parseFloat(item.amount_applied);
            total_amount += parseFloat(item.amount_applied);
          });
          $scope.total_amount_applied = parseFloat(total_amount).toFixed(2);
          $scope.amount_remaining = parseFloat(parseFloat(amount) - total_amount).toFixed(2);
        }
      });
    };

    $scope.Add_Payment_Multi = function() {
      $scope.required_form(function(amount, object_payment) {
        if (!amount) {
          return;
        }
        if (parseFloat($scope.amount_remaining) > 0) {
          if ($scope.payment_type == 'Wells Fargo Plan' || $scope.payment_type == 'CC Manual' || $scope.payment_type == 'In Store Credit') {
            $cordovaToast.showLongTop('The paid amount (history and new added) is larger than the total of the invoice. Please check the numbers again.');
            return;
          } else {
            $scope.openByGetTemplate('confirmOverSplitPayment');
          }
        } else {
          $scope.Create_Payment_Multi();
        }
      });
    };
    $scope.Create_Payment_Multi = function() {
      $scope.required_form(function(amount, object_payment) {
        var _object = {
          method: $scope.payment_type,
          amount: amount,
          payment_data: object_payment,
          invoice_data: $scope.InvoiceCanBePaidChecked,
          amount_remaining: $scope.amount_remaining
        };
        if (_object.method == 'CC Manual' && $scope.invalid_card_number == true) {
          $cordovaToast.showLongTop('Invalid Card Number');
          return;
        }
        Ordertypes.createSplitPayment(_object).success(function(data) {
          if (data.status) {
            $scope.payment_success = data.success;
            $scope.payment_error = data.error;
            $scope.list_paymenthistory = data.arrIdHistory;
            $scope.invalid_card_number = false;
            if (data.arrIdHistory.length > 0) {
              $cordovaToast.showLongTop(data.msg);
              if (data.error.length > 0) {} else {
                $scope.openByGetTemplate('popupOrderInvoiceAddPaymentSignature');
              }
            } else {
              if (data.error.length) {
                $cordovaToast.showLongTop(data.error[0].error);
              }
            }
            $scope.getOrders();
          } else {
            $cordovaToast.showLongTop(data.msg);
          }
          $scope.onsubmitPayment = true;
        });
      });
    };

    $scope.validateFormSplitPayment = function(formValidate) {
      if (formValidate.$invalid) {
        $ionicScrollDelegate.$getByHandle('scrollPopupSplitPayment').scrollTop();
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
      }
      $scope.Add_Payment_Multi();
    }

    $scope.set_month = function(value, type) {
      var index = _.findLastIndex($scope.monthNames, {
        value: parseInt(value)
      });
      if (index >= 0) {
        if (type == 'manual') {
          $scope.Input_value.CC_Manual_month_cc = $scope.monthNames[index].name;
        }
        if (type == 'plan') {
          $scope.Input_value.Payment_Plan_month = $scope.monthNames[index].name;
        }
      }
    }


    $scope.$on('saveAppointment', function(e, data) {
      var params = data.data;
      params.check_order = 1;
      if (params.nothomeutil == "Invalid date")
        params.nothomeutil = "00:00:00";
      $ionicLoading.show({
        template: templateLoading
      });
      Appointments.save(params).success(function(data) {
        $ionicLoading.hide();
        if (data.status) {
          $scope.closeTarget('#opportunityAppointmentSpecificInformation');
          $("#formAppointmentAdd input[type='text']").val('');
          $("#formAppointmentAdd select").val('');
          $("#formAppointmentAdd textarea").val('');
          $scope.setValBiginWatch(false);
          $scope.addAppointmentsData = {};
          $scope.addAppointmentsData.fieldworker = '';
          $scope.addAppointmentsData.prefieldworker = '';
          $scope.addAppointmentsData.callahead_id = '';
          $scope.addAppointmentsData.customertype_id = '';
          $scope.addAppointmentsData.flexiblecustomer_id = '';
          $scope.addAppointmentsData.addby_id = '';
          $scope.addAppointmentsData.order_id = [];
          $scope.addAppointmentsData.appointmentgroup_id = '';
          $scope.$broadcast('resetValue', {});
          $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.$on('estimateinvoiceupdatesuccess', function(event, args) {
      $scope.dataSendMail.order_id = args.order_id;
      $scope.dataSendMail.type = args.type;
      $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.dataSendMail.sendFrom = [{ text: info_mail }];
      $scope.dataSendMail.mail1 = [{ text: $scope.detailCustomerData.email }];
      $scope.openByGetTemplate('popupOdersSendEmail');
    });

    $scope.$on('order_load_app', function(event, args) {
      console.log($scope.detailAppointmentData.id)
      $scope.getDetailAppointment($scope.detailAppointmentData.id);
    });

    if (page == 'order.html')
      $scope.renderTemplateData();

    $scope.$on('getJsonData', function(event, args) {
      var jsondata = args.data;
      var index = _.findIndex(jsondata, { roletree_id: '96' });
      var splitpayemnt = _.find(jsondata[index].child,{roletree_id:"511"});
      $scope.permissionSpitPayment = splitpayemnt.check;
      if (!jsondata[index].check) {
        localStorage.setItem("login_status", "0");
        redirectTo('index.html');
      }

    });

  })
