var oppScopeMobile;
opportunityApp.controller('opportunityCtrl', function ($scope, $timeout, $ionicScrollDelegate, $interval, $ionicLoading,
    $location, $window, $ionicPopup, Customers, Leadsources, Opportunitytabs, Flags, Opportunities, Groups,
    Users, $cordovaToast, Orders, Tasks, dataHtml, $cordovaActionSheet, $cordovaFileTransfer, Appointments,
    $cordovaImagePicker, $cordovaFileTransfer, $cordovaFile, $cordovaImagePicker, $cordovaCamera, Login, Ordertypes,LocationService) {

    $scope.tier = tier;
    $scope.currentPage = 1;
    var pager = "10";
    $scope.itemsPerPage = pager ? pager : '5';
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchOpportunities = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: ""
    };
    $scope.backPage = 'opportunity';
    $scope.currentIdLogin = currentIdLogin;
    $scope.pathToPublic = pathToPublic;
    $scope.entryPageDefault = 25;
    $scope.itemsPerPagefolow = 5;
    $scope.currentPagefolow = 1;
    $scope.searchfollow = {
        rows: $scope.itemsPerPagefolow,
        current_page: $scope.currentPagefolow
    };
    // $scope.profile_default_img = profile_default_img;
    $scope.selectCustomer = true;
    $scope.customer_data = {};
    $scope.customerphone_data = '';
    $scope.check_action_followup = true;
    $scope.dispathroom = '';
    $scope.OpportunitiesActionData = {};
    $scope.addAppointmentsData = {};
    // old variable internal function
    $scope.failSubtabs = [];
    $scope.otherSubtabs = [];
    $scope.callListSubtabs = [];
    $scope.dataAddAppointmentHistory = {};
    $scope.OpportunitiesActionData.selectCustomer = {};
    $scope.failSubtabInConvert = {};
    $scope.dataConvertToFail = {};
    $scope.dataConvertToFailOther = {};
    $scope.dataConvertToFailOther.typeConvert = 'fail';
    $scope.dataFollowUpUpdate = {};
    $scope.dataAddAppointment = {};
    $scope.current_pagefolow = [];
    $scope.rowsfolow = [];
    $scope.current_pagefail = [];
    $scope.rowsfail = [];
    $scope.current_pageother = [];
    $scope.rowsother = [];
    $scope.current_pagecallinlist = [];
    $scope.rowscallinlist = [];
    $scope.totalItemsfolow = [];
    $scope.itemsPerPagefolow = [];
    $scope.currentPagefolow = [];
    $scope.totalItemsother = [];
    $scope.itemsPerPageother = [];
    $scope.currentPageother = [];
    $scope.totalItemsfail = [];
    $scope.itemsPerPagefail = [];
    $scope.currentPagefail = [];
    $scope.totalItemscallinlist = [];
    $scope.itemsPerPagecallinlist = [];
    $scope.currentPagecallinlist = [];
    $scope.addOpportunitiesData = {};
    $scope.editOpportunitiesData = {};
    $scope.deleteOpportunitiesData = {};
    $scope.addOpportunitiesData.selectCustomer = {};
    $scope.addOpportunitiesData.selectCustomer.addStreet = [];
    $scope.queryId = 'new';
    $scope.dataOfficeEmployeee = [];
    $scope.autocompleteList = {};
    $scope.autocompleteList.dataCustomer = [];
    $scope.autocompleteList.dataCustomerAction = [];
    $scope.autocompleteList.dataCustomerRef = [];
    $scope.autocompleteList.dataAssignUser = [];
    $scope.autocompleteList.dataAppType = [];
    $scope.autocompleteList.dataOrder = [];
    $scope.autocompleteList.dataUserAsign = [];
    $scope.autocompleteList.dataUserFollower = [];
    $scope.autocompleteList.oppfiltercity = [];
    $scope.autocompleteList.oppfilterzip = [];
    $scope.autocompleteList.oppfilterphone = [];
    $scope.autocompleteList.oppfilterleadsource = [];
    $scope.autocompleteList.oppfilterrep = [];
    $scope.autocompleteList.oppfilterassignee = [];
    $scope.autocompleteList.searchOpportunity = [];
    $scope.showTimetable = false;
    $scope.taskStartTime = '';
    $scope.taskEndTime = '';
    $scope.typeoftask = [{id: 'Incomplete', name: 'Standard'}, {id: 'Downtime', name: 'Downtime Task'}];
    $scope.fromFollowup = false;
    $scope.initToDay = moment().format('YYYY-MM-DD');
    $scope.addOppAble = true;
    $scope.dataOppHtml = {};
    $scope.files = [];
    $scope.assign = {};

    $scope.requiredFlag = false;
    $scope.jobsiteshow = false;
    $scope.data_customer = {};

    $scope.roleName = role;
    $scope.isAdmin = isAdmin;
    $scope.isManager = isManager;
    $scope.isReporter = isReporter;
    $scope.isScheduler = isScheduler;
    $scope.isFieldinstaller = isFieldinstaller;
    $scope.isSalesman = isSalesman;
    $scope.isWarehouse = isWarehouse;
    $scope.isStrategicDevelopment = isStrategicDevelopment;
    $scope.isSupportAssistant = isSupportAssistant;
    $scope.isOutsideSales = isOutsideSales;
    $scope.isInFieldSupervisor = isInFieldSupervisor;
    $scope.departmentId = departmentId;
    $scope.showdataautocomple = '';
    $scope.myFollowUpName = myFollowUpName;
    $scope.asapServiceName = asapServiceName;
    $scope.clickAddTaskLoadSubHeading = false;
    if (!$scope.dataViewAppNote) {
        $scope.dataViewAppNote = {};
    }
    $scope.checkLoadMore = false;
    $scope.checkLoadMorePending = false;
    $scope.checkLoadMoreSuccess = false;
    $scope.checkLoadMoreFollow = false;
    $scope.checkLoadMoreFail = false;
    $scope.checkLoadMoreOther = false;
    $scope.checkLoadMoreCalllist = false;
    $scope.checkLoadMoreDisplayFilter = false;
    $scope.loadedDataSelect = false;
    $scope.scheckPendingClicked = false;
    $scope.scheckSuccessClicked = false;
    $scope.rootUserAssign = [];
    $scope.inputValue = {};
    $scope.inputValue.filterSubStatus = 'All';
    $scope.inputValue.filterStatus = 'All';
    $scope.dataFilterOppotunities = {};
    oppScopeMobile = $scope;
    $scope.dataFilterCity = JSON.parse(dataCityFilter);
    $scope.dataFilterLeadsource = JSON.parse(dataLeadsourceFilter);
    $scope.dataFilterOppotunities.status = 'All';
    $scope.dataFilterOppotunities.subStatus = 'All';
    $scope.dataFilterOppotunities.customer = [];
    $scope.dataFilterOppotunities.objphone = [];
    $scope.dataFilterOppotunities.city = [];
    $scope.dataFilterOppotunities.zipcode = [];
    $scope.dataFilterOppotunities.leadsource = [];
    $scope.dataFilterOppotunities.rep = [];
    $scope.dataFilterOppotunities.assignee = [];
    $scope.dataFilterOppotunities.checkManualLeadSoure = false;
    $scope.dataFilterZipcode = JSON.parse(zipcodeFilter);
    $scope.dataFilterZipcodeDetail = [];
    $scope.arrPoscode = [];
    $scope.failfocus = 0;
    _.each($scope.dataFilterZipcode, function (row) {
        if ($scope.arrPoscode.indexOf(row.postal_code) < 0) {
            $scope.arrPoscode.push(row.postal_code);
            $scope.dataFilterZipcodeDetail.push(row);
        }
    });
    if ($scope.roleName == $scope.isReporter || $scope.roleName == $scope.isScheduler) {
        $scope.dataConvertToFailOther.typeConvert = 'other';
    }
    // end variable
    $scope.addAppointmentsData.jobsites = [{
        label: '',
        street: '',
        city: '',
        state: '',
        zipcode: '',
        contactperson: '',
        contactphone: '',
    }];
    $scope.viewInpuntManualLead = false;
    $scope.dataSetCustomerOpp = {};
    $scope.arrAddress = [];
    if(!$scope.AppointmentNoteData){
        $scope.AppointmentNoteData = {};
    }
    $scope.current_customer_id = 0;
    $scope.selectNewCus = false;
    $scope.clickFirstTimeAddphone = true;
    $scope.renderTemplateData = function () {
        dataHtml.getTemplate('templates/dashboard/opportunities/opportunityMenuHeader.tpl').success(function (results) {
            $scope.dataOppHtml.menuHeader = results;
            dataHtml.getTemplate('templates/dashboard/opportunities/opportunityMainContent.tpl').success(function (results) {
                $scope.dataOppHtml.mainContent = results;
                $timeout(function () {
                    setHeight("#main-content");
                }, 1)
                $scope.getOpportunitytabs();
                dataHtml.getTemplate('templates/dashboard/opportunities/opportunitySearch.tpl').success(function (results) {
                    $scope.dataOppHtml.searchOpp = results;
                })
            });
        });
    }
    $scope.openByGetTemplate = function (style) {
        $ionicLoading.show({template: templateLoading});
        $timeout(function () {
            switch (style) {
                case 'popupOpportunityFilterReport':
                dataHtml.getTemplate('templates/dashboard/opportunities/opportunityFilterReport.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityFilterReport = results;
                    $scope.showTarget('#popupOpportunityFilterReport');
                    $ionicLoading.hide();
                    $timeout(function () {
                        if (!$scope.filter_from_date)
                            $scope.filter_from_date = moment().format('MM/DD/YYYY');
                        if (!$scope.filter_to_date)
                            $scope.filter_to_date = moment().add(1, 'days').format('MM/DD/YYYY');
                    }, 1000)
                });
                break;
                case 'popupOpportunityFilterReportDisplay':
                dataHtml.getTemplate('templates/dashboard/opportunities/opportunityFilterReportDisplay.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityFilterReportDisplay = results;
                    $scope.showTarget('#popupOpportunityFilterReportDisplay');
                    $ionicLoading.hide();
                });
                break;
                case 'popupOpportunityImport':
                dataHtml.getTemplate('templates/dashboard/opportunities/opportunityImport.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityImport = results;
                    $scope.showTarget('#popupOpportunityImport');
                    $scope.files = [];
                    $scope.data_import_eror = [];
                    $ionicLoading.hide();
                });
                break;
                case 'addOpportunity':
                dataHtml.getTemplate('templates/dashboard/opportunities/form/addOpportunity.tpl').success(function (results) {
                    $scope.dataOppHtml.addOpportunity = results;
                    $scope.showTarget('#addOpportunity');
                    $ionicLoading.hide();
                });
                break;
                case 'popupOpportunityPending':
                dataHtml.getTemplate('templates/dashboard/opportunities/table/opportunityPending.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityPending = results;
                    $scope.showTarget('#popupOpportunityPending');
                });
                break;
                case 'popupOpportunityAction':
                dataHtml.getTemplate('templates/dashboard/opportunities/form/opportunityActionForm.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityAction = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityAction');
                        $ionicLoading.hide();
                    }, 500)
                    // dataHtml.getTemplate('templates/dashboard/opportunities/form/appointmentHistoryDetail.tpl').success(function(results) {
                    //     $scope.dataOppHtml.popupAppointmentHistory = results;
                    // });
                });
                break;
                case 'popupOpportunityActionFlagNote':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityActionFlagNote.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityActionFlagNote = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityActionFlagNote');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupOpportunityHistory':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityHistory.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityHistory = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityHistory');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupOpportunityHistoryFilter':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityHistoryFilter.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityHistoryFilter = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityHistoryFilter');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupOpportunityHistoryCustomerNote':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityHistoryCustomerNote.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityHistoryCustomerNote = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityHistoryCustomerNote');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupOpportunityHistoryEditCustomerNote':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityHistoryEditCustomerNote.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityHistoryEditCustomerNote = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityHistoryEditCustomerNote');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupOpportunityHistoryOrder':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityHistoryOrder.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityHistoryOrder = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityHistoryOrder');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'opportunityAppointmentSpecificInformation':
                dataHtml.getTemplate('templates/dashboard/opportunities/form/opportunityappointmentspecificInformation.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityAppointmentSpecificInformation = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityAppointmentSpecificInformation');
                        // $('#popupOpportunityAction').css('display', 'none');
                        $scope.setValueShowSelect('selectedCallAhead', 'seletedCallAheadName', '');
                        $ionicScrollDelegate.$getByHandle('scrollAppointmentSpecificInfor').scrollTop(true);
                        $ionicLoading.hide();
                    }, 1000)
                });
                break;

                case 'opportunityActionAddTask':
                dataHtml.getTemplate('templates/dashboard/opportunities/form/opportunityActionAddTask.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityActionAddTask = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityActionAddTask');
                        $scope.files = [];
                        $ionicScrollDelegate.$getByHandle('scrollOppAddTask').scrollTop(true);
                        $ionicLoading.hide();
                    }, 1000)
                });
                break;
                case 'opportunityActionOther':
                dataHtml.getTemplate('templates/dashboard/opportunities/form/opportunityActionOther.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityActionOther = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityActionOther')
                        $ionicScrollDelegate.$getByHandle('scrollConvertToFailOther').scrollTop(true);
                        $ionicLoading.hide();
                    }, 1000)
                });
                break;
                // follow up
                case 'opportunityFollowUpSubTab':
                dataHtml.getTemplate('templates/dashboard/opportunities/subtab/opportunityFollowUpSubtab.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityFollowUpSubTab = results;
                });
                break;
                case 'opportunityFollowUpContent':
                dataHtml.getTemplate('templates/dashboard/opportunities/table/opportunityFollowUpContent.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityFollowUpContent = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityFollowUpContent');
                        $ionicScrollDelegate.$getByHandle('scrollFollow').scrollTop(true);
                    }, 500)
                });
                break;
                case 'opportunityFollowUpFollowUp':
                dataHtml.getTemplate('templates/dashboard/opportunities/form/opportunityFollowUpFollowUp.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityFollowUpFollowUp = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityFollowUpFollowUp');
                    }, 500)
                });
                break;
                case 'opportunityFollowToFail':
                dataHtml.getTemplate('templates/dashboard/opportunities/form/opportunityFollowToFail.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityFollowToFail = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityFollowToFail');
                        $ionicLoading.hide();
                        $scope.setRequiredAddress();
                    }, 500)
                });
                break;
                // success
                case 'opportunitySuccessContent':
                dataHtml.getTemplate('templates/dashboard/opportunities/table/opportunitySuccessContent.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunitySuccessContent = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunitySuccessContent');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                // fail
                case 'opportunityFailSubTab':
                dataHtml.getTemplate('templates/dashboard/opportunities/subtab/opportunityFailSubtab.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityFailSubTab = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityFailSubTab');
                    }, 500)
                });
                break;
                case 'opportunityFailContents':
                dataHtml.getTemplate('templates/dashboard/opportunities/table/opportunityFailContents.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityFailContents = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityFailContents');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupOpportunityFailNote':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityFailNote.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityFailNote = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityFailNote');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                // other
                case 'opportunityOtherSubTab':
                dataHtml.getTemplate('templates/dashboard/opportunities/subtab/opportunityOtherSubtab.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityOtherSubTab = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityOtherSubTab');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'opportunityOtherContent':
                dataHtml.getTemplate('templates/dashboard/opportunities/table/opportunityOtherContent.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityOtherContent = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityOtherContent');
                    }, 500)
                });
                break;
                // call list
                case 'opportunityCallListSubTab':
                dataHtml.getTemplate('templates/dashboard/opportunities/subtab/opportunityCallListSubtab.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityCallListSubTab = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityCallListSubTab');
                    }, 500)
                });
                break;
                case 'opportunityCallListContent':
                dataHtml.getTemplate('templates/dashboard/opportunities/table/opportunityCallListContent.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityCallListContent = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityCallListContent');
                    }, 500)
                });
                break;
                case 'popupOpportunityViewDescriptionLog':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityViewDescriptionLog.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityViewDescriptionLog = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityViewDescriptionLog');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupOpportunityChangeCustomerNote':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityChangeCustomerNote.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityChangeCustomerNote = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityChangeCustomerNote');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'opptunityViewAppoimentNote':
                dataHtml.getTemplate('templates/dashboard/opportunities/opptunityViewAppoimentNote.tpl').success(function (results) {
                    $scope.dataOppHtml.opptunityViewAppoimentNote = results;
                    $timeout(function () {
                        $scope.showTarget('#opptunityViewAppoimentNote');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'opptunityViewNoteOfRecord':
                dataHtml.getTemplate('templates/dashboard/opportunities/opptunityViewFollowUpNote.tpl').success(function (results) {
                    $scope.dataOppHtml.opptunityViewNoteOfRecord = results;
                    $timeout(function () {
                        $scope.showTarget('#opptunityViewNoteOfRecord');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'opportunityduplicatecustomer':
                dataHtml.getTemplate('templates/dashboard/opportunities/form/opportunityduplicatecustomer.tpl').success(function (results) {
                    $scope.dataOppHtml.opportunityduplicatecustomer = results;
                    $timeout(function () {
                        $scope.showTarget('#opportunityduplicatecustomer');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupCheckAdditionalPhones':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupCheckAdditionalPhones.tpl').success(function (results) {
                    $scope.dataOppHtml.popupCheckAdditionalPhones = results;
                    $timeout(function () {
                        $scope.showTarget('#popupCheckAdditionalPhones');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupConfirmDeletePhones':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupConfirmDeletePhones.tpl').success(function (results) {
                    $scope.dataOppHtml.popupConfirmDeletePhones = results;
                    $timeout(function () {
                        $scope.showTarget('#popupConfirmDeletePhones');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupConfirmDeleteMail':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupConfirmDeleteMail.tpl').success(function (results) {
                    $scope.dataOppHtml.popupConfirmDeleteMail = results;
                    $timeout(function () {
                        $scope.showTarget('#popupConfirmDeleteMail');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupOpportunityHistoryAddCustomerNote':
                dataHtml.getTemplate('templates/dashboard/opportunities/popupOpportunityHistoryAddCustomerNote.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityHistoryAddCustomerNote = results;
                    $timeout(function () {
                        $scope.showTarget('#popupOpportunityHistoryAddCustomerNote');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupWarningAddPhoneEmail':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupWarningAddPhoneEmail.tpl').success(function (results) {
                    $scope.dataOppHtml.popupWarningAddPhoneEmail = results;
                    $timeout(function () {
                        $scope.showTarget('#popupWarningAddPhoneEmail');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;
                case 'popupWarningAddPhoneNumber':
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupWarningAddPhoneNumber.tpl').success(function (results) {
                    $scope.dataOppHtml.popupWarningAddPhoneNumber = results;
                    $timeout(function () {
                        $scope.showTarget('#popupWarningAddPhoneNumber');
                        $ionicLoading.hide();
                    }, 500)
                });
                break;  
            }
        }, 500);
}
$scope.getLeadsources = function () {
    $ionicLoading.show({template: templateLoading});
    Leadsources.getSelect().success(function (data) {
        if (!startpage)
            $ionicLoading.hide();
        $scope.leadsources = data;
        $scope.getFlags();
    });
}
$scope.getOpportunitytabs = function () {
    $ionicLoading.show({template: templateLoading});
    Opportunitytabs.getSelect().success(function (data) {
        if (!startpage)
            $ionicLoading.hide();
        $scope.opportunitytabs = data;
        $scope.pendingUpClick();
    });
}
$scope.getFlags = function () {
    $ionicLoading.show({template: templateLoading});
    Flags.getSelect().success(function (data) {
        if (!startpage)
            $ionicLoading.hide();
        $scope.flags = data;
        $scope.getUsers()
    });
}
$scope.getOpportunities = function () {
    $ionicLoading.show({template: templateLoading});
    Opportunities.getPaging($scope.searchOpportunities).success(function (data) {
        $scope.opportunities = data.data;
        $ionicLoading.hide();
        $scope.currentPage = data.page;
        $scope.itemsPerPage = $scope.searchOpportunities.rows;
        opportunities_pagesize.val($scope.itemsPerPage);
        $scope.totalItems = data.total_rows;
            //$('#tableOpportunities').tableRespondsive();
        });
};
$scope.searchChanged = function () {
    $scope.getOpportunities();
}
$scope.showHideTimeTable = function () {
    $scope.leadsource_id = $('#leadsource_id').val();
    if ($scope.leadsource_id == 2 || $scope.leadsource_id == 4) {
        $('.timetable-add-customer').show();
        $('.customer-comment-add-customer').show();
    }
}
$scope.showHideTimeTableEdit = function () {
    $scope.leadsource_id = $('#leadsource_idedit').val();
    if ($scope.leadsource_id == 2 || $scope.leadsource_id == 4) {
        $('.timetable-add-customer').show();
    }
}
$scope.isActive = function (id) {
    if (id == 2 || id == 4) {
        return true;
    } else {
        return false;
    }
}
$scope.setFollowUpIdConvertSuccess = function () {
    $scope.addAppointmentsData.followUpId = $scope.followUpId;
}
$scope.addRowJobsiteCreate = function () {
    if (!$scope.addAppointmentsData.jobsites) {
        $scope.addAppointmentsData.jobsites = [];
    }
    $scope.addAppointmentsData.jobsites.push({
        label: '',
        street: '',
        city: '',
        state: '',
        zipcode: '',
        contactperson: '',
        contactphone: '',
    });
}
$scope.removeItemJobsiteCreate = function (index) {
    if ($scope.addAppointmentsData.jobsites.length > 1) {
        $scope.addAppointmentsData.jobsites.splice(index, 1);
    }
}

$scope.requiredSendToDispath = function () {
    $scope.checkRequired = true;
    if ($scope.OpportunitiesActionData.customerType.length == 0)
        $scope.checkRequired = false;
    if ($scope.OpportunitiesActionData.issue.length == 0)
        $scope.checkRequired = false;
    if ($scope.OpportunitiesActionData.city.length == 0)
        $scope.checkRequired = false;
    if ($scope.OpportunitiesActionData.time.length == 0)
        $scope.checkRequired = false;

    if ($scope.checkRequired) {
        $scope.sendToDispath();
    } else {
        $cordovaToast.showLongTop('Please fill all information of dispath.!!!');
    }
}
$scope.sendToDispath = function () {
    socket.emit('new message', {
        from_user: $scope.currentIdLogin,
        room_id: '2',
        user_id: 0,
        contents: $scope.OpportunitiesActionData.city + ' - ' + $scope.OpportunitiesActionData.customerType + ' - ' + $scope.OpportunitiesActionData.issue + ' - ' + $scope.OpportunitiesActionData.time,
        content_raw: $scope.OpportunitiesActionData.city + ' - ' + $scope.OpportunitiesActionData.customerType + ' - ' + $scope.OpportunitiesActionData.issue + ' - ' + $scope.OpportunitiesActionData.time,
        hashtag: '',
        applicationtype: aplicationtype.text,
        opportunity_id: $scope.Opportunity_id
    });
    $scope.OpportunitiesActionData.customerType = '';
    $scope.OpportunitiesActionData.issue = '';
    $scope.OpportunitiesActionData.city = '';
    $scope.OpportunitiesActionData.time = '';
}
$scope.pendingClicked = function () {
    $scope.openByGetTemplate('popupOpportunityPending');
    if (!$scope.scheckPendingClicked) {
        $scope.pendingUpClick();
    }
    $timeout(function () {
        $scope.scheckPendingClicked = true;
        $ionicLoading.hide();
    }, 300);
}

$scope.pendingUpClick = function () {
    $scope.pendingContent = [];
    $scope.entrypage_action = 'pending';
    $scope.entryLimit = ($scope.rowspending ? $scope.rowspending : $scope.entryPageDefault).toString();
    $ionicLoading.show({template: templateLoading});
    Opportunities.pendingContent({
        rows: $scope.rowspending ? $scope.rowspending : $scope.entryPageDefault,
        current_page: $scope.current_pagepending ? $scope.current_pagepending : 1
    }).success(function (data) {
        if (!startpage) {
            $ionicLoading.hide();
            $ionicScrollDelegate.$getByHandle('scrollPending').scrollTop(true);
            $ionicScrollDelegate.$getByHandle('scrollPending').resize();
        }
        $scope.pendingContent = data.data;
        $scope.pendingContent = _.each($scope.pendingContent, function (value) {
            var array_time = value.start_time.split(' ');
            value.start_time = Date.parseDate(array_time[0] + ' ' + String(array_time[1]));
        });
        $scope.pendingContent = _.sortBy($scope.pendingContent, '-unique_id');
        $scope.currentPagepending = data.page;
        $scope.itemsPerPagepending = data.rows;
        $scope.totalItemspending = data.total_rows;
        $scope.totalItemssuccess = data.countsuccess;
        if (!$scope.loadedDataSelect) {
            $scope.getLeadsources();
        }
        if (data.data.length == $scope.entryPageDefault) {
            $timeout(function () {
                $scope.checkLoadMorePending = true;
            }, 2000);
        }
        $scope.$broadcast('scroll.refreshComplete');
    });
};

$scope.refreshPendingContent = function(){
    $scope.current_pagepending = 1;
    $scope.pendingUpClick();
}

$scope.markForward = function () {
    for (var i = 0; i < $scope.pendingContent.length; i++) {
        var item = $scope.pendingContent[i];
        if (item.unique_id) {
            if (i > 0 && i < $scope.pendingContent.length - 1) {
                if ($scope.pendingContent[i + 1].unique_id == item.unique_id ||
                    $scope.pendingContent[i - 1].unique_id == item.unique_id) {
                    item.forward = "blue";
            }

        }
        if (i == 0 || i == $scope.pendingContent.length - 1) {
            if (i == 0 && $scope.pendingContent[i + 1].unique_id == item.unique_id) {
                item.forward = "blue";
            }
            if ((i == $scope.pendingContent.length - 1) && $scope.pendingContent[i - 1].unique_id == item.unique_id) {
                item.forward = "blue";
            }
        }
    }
}
}

$scope.SuccessClick = function (oppId) {
    if ($scope.scheckSuccessClicked)
        return;
    $scope.scheckSuccessClicked = true;
    $scope.openByGetTemplate('opportunitySuccessContent');
    $scope.successcontent = [];
    $scope.entryLimit = ($scope.rowssuccess ? $scope.rowssuccess : $scope.entryPageDefault).toString();
    $scope.entrypage_action = 'success';
    $scope.successFocus = oppId;
    if ($scope.successcontent.length == 0) {
        $ionicLoading.show({template: templateLoading});
        Opportunities.SuccessContent({
            rows: $scope.entryPageDefault,
            current_page: 1,
            oppID: oppId
        }).success(function (data) {
            $ionicLoading.hide();
            $scope.successcontent = data.data;
            $scope.successcontent = _.each($scope.successcontent, function (value) {
                var array_time = value.start_time.split(' ');
                value.start_time = Date.parseDate(array_time[0] + ' ' + String(array_time[1]));
            });
            $scope.currentPagesuccess = data.page;
            $scope.itemsPerPagesuccess = data.rows;
            $scope.totalItemssuccess = data.total_rows;
            $scope.entrypage_datarowssuccess = data.rows;
            if (data.data.length == $scope.entryPageDefault) {
                $timeout(function () {
                    $scope.checkLoadMoreSuccess = true;
                }, 2000);
            }
            $scope.$broadcast('scroll.refreshComplete');
        });
    }
}

$scope.refreshSuccessContent = function(){
    $scope.scheckSuccessClicked = false;
    $scope.SuccessClick($scope.successFocus);
}

$scope.followUpClick = function (openListSubTab) {
    if (openListSubTab) {
        $scope.openByGetTemplate('opportunityFollowUpSubTab');
    }
    $scope.followUpSubtabs = [];
    $scope.entrypage_action = 'follow';
    $scope.entryLimit = ($scope.entrypage_datarowsfollow ? $scope.entrypage_datarowsfollow : $scope.entryPageDefault).toString();
    $scope.entryLimit = ($scope.rowssuccess ? $scope.rowssuccess : $scope.entryPageDefault).toString();
    if ($scope.followUpSubtabs.length == 0) {
        $ionicLoading.show({template: templateLoading})
        Opportunities.getFollowUpSubtab().success(function (data) {
            $ionicLoading.hide();
            $scope.followUpSubtabs = data.data;
            $scope.followUpSubtabNoMyFollow = data.subtabnofollowup;
        });
    } else {
        $ionicLoading.hide();
    }
}

$scope.subSabFollowContent = function (id, currentLocation) {
    $scope.openByGetTemplate('opportunityFollowUpContent');
    Opportunities.folowUpSubtabContent({
        id: id,
        rows: $scope.entryPageDefault,
        current_page: 1
    }).success(function (data) {
        $ionicLoading.hide();
        $scope.dataFollowUpSubtabContent = [];
        $scope.dataFollowUpSubtabContent = data.data;
        $scope.currentLocation = currentLocation;
        $scope.currentFollowSubtabId = id;

        $scope.currentPageFollowUp = data.page;
        $scope.itemsPerPageFollowUp = data.rows;
        if (data.data.length == $scope.entryPageDefault) {
            $timeout(function () {
                $scope.checkLoadMoreFollow = true;
            }, 2000)
        }
        $scope.$broadcast('scroll.refreshComplete');
    });
}
$scope.failClick = function (opid, tabid, userby) {
    $ionicLoading.show({template: templateLoading});
    if (userby == 'onUi') {
        $scope.openByGetTemplate('opportunityFailSubTab');
    }
    $scope.entrypage_action = 'fail';
    $scope.entryLimit = ($scope.entrypage_datarowsfail ? $scope.entrypage_datarowsfail : $scope.entryPageDefault).toString();
    Opportunities.getFailSubtab().success(function (data) {
        $ionicLoading.hide();
        $scope.failSubtabs = data.data;
        if (opid) {
            var tab = _.findIndex($scope.failSubtabs, {id: tabid});
            var tabcurr = $scope.failSubtabs[tab];
            if (tabcurr) {
                $scope.subtabFailContent(tabcurr.id, tab, tabcurr.name, opid);
            }

        }

    });
}
$scope.subtabFailContent = function (id, index, currentLocation, opid) {
    $scope.openByGetTemplate('opportunityFailContents');
    $('#failSubtabDisplay-' + index).parent().find('li').removeClass('actived');
    $('#failSubtabDisplay-' + index).addClass('actived');
    $('#failSubtabTable-' + index).parent().find('li').addClass('none');
    $('#failSubtabTable-' + index).removeClass('none');
    $('#failSubtabTable-' + index).find('li').removeClass('none');
    $scope.failfocus = opid;
    Opportunities.failSubtabContent({
        id: id,
        oppID: opid,
        rows: $scope.entryPageDefault,
        current_page: 1
    }).success(function (data) {
        $ionicLoading.hide();
        $scope.dataFailSubtabContent = [];
        $scope.dataFailSubtabContent = data.data;
        $scope.failCurrentLocation = currentLocation;
        $scope.currentFailtabId = id;
        $scope.indexFailSubTab = index;
        $scope.currentPageFail = data.page;
        if (data.position) {
            var page = Math.ceil(data.position / $scope.entryPageDefault);
                    //load page bi trung khi va bi highlight 2 record
                    // $scope.currentPageFail  = page-1;
                    $scope.currentPageFail = page;
                    $scope.loadMoreFail();
                }
                if (data.data.length == $scope.entryPageDefault) {
                    $timeout(function () {
                        $scope.checkLoadMoreFail = true;
                    }, 2000);
                }
                $scope.$broadcast('scroll.refreshComplete');
            });
}


$scope.viewFailNote = function (data) {
    $scope.openByGetTemplate('popupOpportunityFailNote');
    $scope.viewFailNoteData = data;
}
$scope.otherClick = function (userby, opid, tabid) {
    $ionicLoading.show({template: templateLoading});
    if (!startpage && userby == 'onUi') {
        $scope.openByGetTemplate('opportunityOtherSubTab');
    }
    if (!$scope.clickAddTaskLoadSubHeading) {
        $scope.entrypage_action = 'other';
    }
    $scope.otherFocus = opid;
    $scope.entryLimit = ($scope.entrypage_datarowsother ? $scope.entrypage_datarowsother : $scope.entryPageDefault).toString();
    Opportunities.getOtherSubtab().success(function (data) {
        if (!startpage)
            $ionicLoading.hide();
        $scope.otherSubtabs = data.data;
        $scope.clickAddTaskLoadSubHeading = false;
        if (opid) {
            var tab = _.findIndex($scope.otherSubtabs, {id: tabid});
            var tabcurr = $scope.otherSubtabs[tab];
            if (tabcurr) {
                $scope.subtabOtherContent(tabcurr.id, tab, tabcurr.name, opid);
            }
        }
    });
}
$scope.subtabOtherContent = function (id, index, currentLocation, oppId) {
    $scope.openByGetTemplate('opportunityOtherContent');
    $('#otherSubtabDisplay-' + index).parent().find('li').removeClass('actived');
    $('#otherSubtabDisplay-' + index).addClass('actived');
    $('#otherSubtabTable-' + index).parent().find('li').addClass('none');
    $('#otherSubtabTable-' + index).removeClass('none');
    $('#otherSubtabTable-' + index).find('li').removeClass('none');
    Opportunities.otherSubtabContent({
        id: id,
        rows: $scope.entryPageDefault,
        current_page: 1,
        oppID: oppId
    }).success(function (data) {
        $ionicLoading.hide();
        $scope.dataOtherSubtabContent = [];
        $scope.dataOtherSubtabContent = data.data;
        $scope.otherCurrentLocation = currentLocation;
        $scope.currentOthertabId = id;
        $scope.indexOtherSubtab = index;
        $scope.currentPageOther = data.page;
        if (data.position) {
            var page = Math.ceil(data.position / $scope.entryPageDefault);
            $scope.currentPageOther = page;
            $scope.loadMoreOther();
        }
        if (data.data.length == $scope.entryPageDefault) {
            $timeout(function () {
                $scope.checkLoadMoreOther = true;
            }, 2000);
        }
        $scope.$broadcast('scroll.refreshComplete');
    });
}
$scope.callListClick = function (oppId, tabid) {
    $scope.openByGetTemplate('opportunityCallListSubTab');
    $scope.entrypage_action = 'callinlist';
    $scope.callListFocus = oppId;
    $scope.entryLimit = ($scope.entrypage_datarowscallinlist ? $scope.entrypage_datarowscallinlist : $scope.entryPageDefault).toString();
    Opportunities.getCallListSubtab().success(function (data) {
        $ionicLoading.hide();
        $scope.callListSubtabs = data.data;
        if (oppId) {
            var tab = _.findIndex($scope.callListSubtabs, {id: tabid});
            var tabcurr = $scope.callListSubtabs[tab];
            if (tabcurr) {
                $scope.subtabCallListContent(tabcurr.id, tab, tabcurr.name, oppId);
            }
        }
    });
}
$scope.subtabCallListContent = function (id, index, currentLocation, oppId) {
    $scope.openByGetTemplate('opportunityCallListContent');
    Opportunities.callListSubtabContent({
        id: id,
        rows: $scope.entryPageDefault,
        current_page: 1,
        user_id: $scope.currentIdLogin,
        oppID: oppId
    }).success(function (data) {
        $ionicLoading.hide();
        $scope.dataCallListSubtabContent = [];
        $scope.dataCallListSubtabContent = data.data;
        $scope.callListCurrentLocation = currentLocation;
        $scope.currentCallListtabId = id;
        $scope.indexCallListSubTab = index;
        $scope.currentPageCallList = data.page;
        if (data.position) {
            var page = Math.ceil(data.position / $scope.entryPageDefault);
            $scope.currentPageCallList = page;
            $scope.loadMoreCallList();
        }
        if (data.data.length == $scope.entryPageDefault) {
            $scope.checkLoadMoreCalllist = true;
        }
        $ionicScrollDelegate.$getByHandle('scrollOpportunityCallListSubTab').resize();
        $ionicScrollDelegate.$getByHandle('scrollOpportunityCallListSubTab').scrollTop();
        $scope.$broadcast('scroll.refreshComplete');
    });
}
$scope.$watch('responsive', function (val) {
    $('.opportunity-list .tab-nav').each(function () {
        $(this).tabNavI();
    });
});
$scope.checkLoadMoreVal = function (data, perPage) {
    var checkLoadMore = true;
    if (data < perPage) {
        checkLoadMore = false;
    }
    return checkLoadMore;
}
$scope.LoadMoreOppotunities = function (tab) {
    switch (tab) {
        case 'pending':
        $scope.loadMorePending();
        break;
        case 'follow':
        $scope.loadMoreFollowUp();
        break;
        case 'success':
        $scope.loadMoreSuccess();
        break;
        case 'fail':
        $scope.loadMoreFail();
        break;
        case 'other':
        $scope.loadMoreOther();
        break;
        case 'calllist':
        $scope.loadMoreCallList();
        break;
    }
        // $timeout(function() {
        //     $scope.$broadcast('scroll.infiniteScrollComplete');
        // }, 1000);
    };
    $scope.loadMorePending = function () {
        if (!$scope.checkLoadMorePending)
            return;
        $scope.currentPagepending++;
        Opportunities.pendingContent({
            rows: $scope.entryPageDefault,
            current_page: $scope.currentPagepending
        }).success(function (data) {
            _.each(data.data, function (item) {
                $scope.pendingContent.push(item);
            })
            $scope.checkLoadMorePending = $scope.checkLoadMoreVal(data.data.length, $scope.entryPageDefault);
            $timeout(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 2000);
        });
    }
    $scope.loadMoreFollowUp = function () {
        if (!$scope.checkLoadMoreFollow)
            return;
        $scope.currentPageFollowUp++;
        Opportunities.folowUpSubtabContent({
            id: $scope.currentFollowSubtabId,
            rows: $scope.entryPageDefault,
            current_page: $scope.currentPageFollowUp
        }).success(function (data) {
            if (data.data.length) {
                _.each(data.data, function (item) {
                    $scope.dataFollowUpSubtabContent.push(item);
                })
            }
            $scope.checkLoadMoreFollow = $scope.checkLoadMoreVal(data.data.length, $scope.entryPageDefault);
            $timeout(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 2000);
        });
    }
    $scope.loadMoreSuccess = function () {
        if (!$scope.checkLoadMoreSuccess)
            return;
        $scope.currentPagesuccess++;
        Opportunities.SuccessContent({
            rows: $scope.entryPageDefault,
            current_page: $scope.currentPagesuccess
        }).success(function (data) {
            if (data.data.length) {
                _.each(data.data, function (item) {
                    $scope.successcontent.push(item);
                })
            }
            $scope.checkLoadMore = $scope.checkLoadMoreVal(data.data.length, $scope.entryPageDefault);
            $timeout(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 2000);
        });
    }
    $scope.loadMoreFail = function () {
        if (!$scope.checkLoadMoreFail)
            return;
        $scope.currentPageFail++;
        Opportunities.failSubtabContent({
            id: $scope.currentFailtabId,
            rows: $scope.entryPageDefault,
            current_page: $scope.currentPageFail
        }).success(function (data) {
            if (data.data.length) {
                _.each(data.data, function (item) {
                    $scope.dataFailSubtabContent.push(item);
                })
            }
            $scope.checkLoadMoreFail = $scope.checkLoadMoreVal(data.data.length, $scope.entryPageDefault);
            $timeout(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 2000);
        });

    }
    $scope.loadMoreOther = function () {
        if (!$scope.checkLoadMoreOther)
            return;
        $scope.currentPageOther++;
        Opportunities.otherSubtabContent({
            id: $scope.currentOthertabId,
            rows: $scope.entryPageDefault,
            current_page: $scope.currentPageOther
        }).success(function (data) {
            if (data.data.length) {
                _.each(data.data, function (item) {
                    $scope.dataOtherSubtabContent.push(item);
                })
            }
            $scope.checkLoadMoreOther = $scope.checkLoadMoreVal(data.data.length, $scope.entryPageDefault);
            $timeout(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 2000);
        });
    }
    $scope.loadMoreCallList = function () {
        if (!$scope.checkLoadMoreCalllist)
            return;
        $scope.currentPageCallList++;
        Opportunities.callListSubtabContent({
            id: $scope.currentCallListtabId,
            rows: $scope.entryPageDefault,
            current_page: $scope.currentPageCallList,
            user_id: $scope.currentIdLogin
        }).success(function (data) {
            if (data.data.length) {
                _.each(data.data, function (item) {
                    $scope.dataCallListSubtabContent.push(item);
                })
            }
            $scope.checkLoadMoreCalllist = $scope.checkLoadMoreVal(data.data.length, $scope.entryPageDefault);
            $timeout(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 2000);
        });
    }
    $scope.getAppointmentHistoryByCustomerId = function (customerId) {

        $scope.dataJobsiteToAutocomplete = [];
        $scope.showdataautocomple = $scope.OpportunitiesActionData.selectCustomer.first_name + ' ' + $scope.OpportunitiesActionData.selectCustomer.last_name;
        Customers.setCustomerId(customerId);
        $scope.customerId_Jobsite = customerId;
        $scope.selectCustomer = true;
        $scope.dataAddAppointmentHistory = {};
        if (customerId != "") {
            $ionicLoading.show({template: templateLoading})
            Customers.getappointmenthistory(customerId).success(function (data) {
                $ionicLoading.hide()
                $scope.customeraddress = data.customeraddress;
                $scope.dataJobsiteToAutocomplete = data.jobsitedata;
                $scope.jobsitedataView = [{id: '', name: 'All'}];
                if ($scope.noLoadAppHistory) {
                    $scope.dataAddAppointmentHistory = [];
                } else {
                    $scope.dataAddAppointmentHistory = data.data ? data.data : [];
                    if (data.data && data.data.length) {
                        $scope.setActionAddAppointmentHistory();
                    } else {
                        $scope.dataAddAppointmentHistory = {};
                    }
                }
                $scope.noLoadAppHistory = false;
                $scope.initialJobsiteFilter = [""];
            });
        }
    }
    $scope.autocomplete = {};
    $scope.filterAppoinmentHistory = function (query) {
        $scope.jobsitedata = [];
        $scope.jobsitedata.push({id: '', name: 'All'});
        $scope.jobsitedata.push({id: 'Billing Address', name: 'Billing Address | ' + $scope.customeraddress.street});
        _.each($scope.dataJobsiteToAutocomplete, function (item) {
            $scope.jobsitedata.push(item);
        })

        var returnValue = {
            items: []
        };
        $scope.jobsitedata.forEach(function (item) {
            if (item.id != $scope.autocomplete.jobsiteFilter && item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                returnValue.items.push(item);
            }
        });
        return returnValue;
    }
    $scope.onRemoveJobsite = function (callback) {
        $scope.initialJobsiteFilter = [""];
    }
    $scope.onSelectJobsite = function (callback) {
        $scope.jobsitedataView = [];
        $scope.jobsitedataView.push(callback.item);
        $ionicLoading.show({
            template: templateLoading
        });
        Customers.changeJobsite(callback.item.id, $scope.customerId_Jobsite).success(function (data) {
            $ionicLoading.hide();
            if ($scope.noLoadAppHistory) {
                $scope.dataAddAppointmentHistory = {};
            } else {
                $scope.dataAddAppointmentHistory = data;
                if (!data.length)
                    $scope.dataAddAppointmentHistory = {};
            }
            $scope.noLoadAppHistory = false;
            $ionicScrollDelegate.$getByHandle('scrollOppotunitiesAction').resize();
        });
    }
    $scope.modelToItemMethodJobsiterFilter = function (modelValue) {
        $scope.jobsitedata = [];
        $scope.jobsitedata.push({id: '', name: 'All'});
        $scope.jobsitedata.push({id: 'Billing Address', name: '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.getallcustomer = function () {
        var params = {
            first_name: $scope.OpportunitiesActionData.selectCustomer.first_name,
            last_name: $scope.OpportunitiesActionData.selectCustomer.last_name,
            phone: $scope.OpportunitiesActionData.selectCustomer.phone
        };
        !$scope.OpportunitiesActionData.selectCustomer.first_name ? $scope.OpportunitiesActionData.selectCustomer.first_name = '' : '';
        !$scope.OpportunitiesActionData.selectCustomer.last_name ? $scope.OpportunitiesActionData.selectCustomer.last_name = '' : '';
        Customers.getcustomerOpportunityAction(params).success(function (data) {
            $scope.allcustomerdata = data;
        })
    }
    $scope.getallcustomer();
    $scope.getcustomer = function ($item, $model, $label) { // change assign
        $scope.OpportunitiesActionData.selectCustomer.first_name = $item.first_name;
        $scope.OpportunitiesActionData.selectCustomer.last_name = $item.last_name;
        $scope.OpportunitiesActionData.selectCustomer.phone = $item.phone;
    }

    $scope.setActionAddAppointmentHistory = function () {
        setTimeout(function () {
            $scope.$apply(function (val) {
                if (val) {
                    $('.list-appointment-history > li .detail').click(function () {
                        $(this).closest('li').find('.note').slideToggle();
                    })
                }
            });
        }, 1);
    }
    $scope.uploadFile = function (file) {
        if (file.length < 1) {
            $cordovaToast.showLongTop("Please choose file.");
            return;
        }
        var ext = file[0].localURL.substring(file[0].localURL.lastIndexOf('.') + 1);
        ext = ext.toLowerCase();
        if (ext != 'xsl' && ext != 'xsls' && ext != 'csv' && ext != 'xlsx') {
            $cordovaToast.showLongTop("Please select .xsl, xsls, csv file.");
            return;
        }
        var options = {
            fileName: file[0].name,
            fileKey: "file",
            mimeType: file[0].type,
            chunkedMode: false
        }
        $cordovaFileTransfer.upload(url_server + 'opportunities/uploadFile', file[0].localURL, options).then(function (data) {
            Opportunities.import(data.response).success(function (data) {
                $ionicLoading.hide();
                if (data.status) {
                    $cordovaToast.showLongTop(data.msg);
                } else {
                    $scope.data_import_eror = data.data;
                    // if ($scope.data_import_eror.length > 0) {
                    //     openPopup('#import_error_opportunity');
                    // }
                    $scope.url_file = data.url;
                    $scope.Total_rows = data.Total_rows;
                    $scope.Valid_rows = data.Valid_rows;
                    $scope.Invalid_rows = data.Invalid_rows;
                    $cordovaToast.showLongTop(data.msg);
                }
            });
        }, function (err) {
            $ionicLoading.hide();
            console.log(err);
            console.log("ERROR: " + JSON.stringify(err));
        }, function (progress) {
            $ionicLoading.show({
                template: templateLoading
            });
        });
    };
    $scope.downloadFile = function () {
        var url = url_site + '/upload/storage/imports/template/Import Follow-Up File template.xlsx';
        var urlFile = decodeURIComponent(url);
        var arrData = urlFile.split("/");
        var fileName = arrData[arrData.length - 1];
        var trustHosts = true;
        var options = {};
        $ionicLoading.show({template: templateLoading});
        if (isiOs) {
            var targetPath = cordova.file.syncedDataDirectory + 'RGD/' + fileName;
            $cordovaFile.createDir(cordova.file.syncedDataDirectory, "RGD", false).then(function (success) {
                console.log(success);
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            }, function (error) {
                console.log(error);
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            });
        } else {
            var targetPath = cordova.file.externalRootDirectory + 'RGD/' + fileName;
            $cordovaFile.createDir(cordova.file.externalRootDirectory, "RGD", false).then(function (success) {
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            }, function (error) {
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            });
        }
    }
    $scope.cordovaDownload = function (urlFile, targetPath, options, trustHosts) {
        $cordovaFileTransfer.download(urlFile, targetPath, options, trustHosts).then(function (result) {
            $ionicLoading.hide();
            console.log(result);
            var path = result.fullPath;
            $cordovaToast.showLongTop('Download Successful!!! Path: ' + path);
        }, function (err) {
            $ionicLoading.hide();
            console.log(err);
        }, function (progress) {
            $ionicLoading.show({
                template: templateLoading
            });
        });
    }
    $scope.Import_anyway = function () {
        $('.import_error_opportunity').show();
        Opportunities.Import_anyway($scope.url_file).success(function (data) {
            if (data.status) {
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
            $('.import_error_opportunity').hide();
            closePopupById('import_error_opportunity');
        });
    }
    $scope.convertToFollowUp = function () {
        $scope.OpportunitiesActionData.pendingId = $scope.pendingId;
        $scope.OpportunitiesActionData.starttime = moment($scope.convertToFollowUp.from_date).format("MM/DD/YYYY");
        $scope.OpportunitiesActionData.endtime = moment($scope.OpportunitiesActionData.selectCustomer.to_date).format("MM/DD/YYYY");
        $scope.OpportunitiesActionData.selectCustomer.customercomment = $('#formOppotunitiesAction #customercomment').val();
        $scope.OpportunitiesActionDataCopy = angular.copy($scope.OpportunitiesActionData);
        delete $scope.OpportunitiesActionDataCopy.selectCustomer.addStreet;
        $ionicLoading.show({template: templateLoading});
        Opportunities.convertToFollowUp($scope.pendingId, $scope.OpportunitiesActionDataCopy).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.countAllTab('pending');
                $scope.closeTarget('#popupOpportunityAction');
                $scope.closeTarget('#opportunityActionFollowUp');
                $('input[name="subHeadingConvertToFollowName"]').val('');
                $('#opportunityAction').css('display', 'none');

            }
        });
    }

    $scope.getItemPending = function (id) {
        var rowData = _.where($scope.pendingContent, {id: id})[0];
        if(rowData.first_name == 'Duplicated' && rowData.last_name == 'Secondary Number'){
            $scope.getDuplicateCustomer(rowData);
        }
        else{
            $scope.closeTarget('#popupOpportunityActionConfirmOpen');
            $scope.openByGetTemplate('popupOpportunityAction');
            $scope.fromFollowup = false;
            $scope.OpportunitiesActionData = {};
            $scope.OpportunitiesActionData.issue = '';
            $scope.OpportunitiesActionData.customerType = '';
            $scope.OpportunitiesActionData.city = '';
            $scope.OpportunitiesActionData.time = '';
            $scope.initialSearchCustomer = [];
            $scope.pendingId = id;
            $scope.getOpportunitiesActionData($scope.pendingId);
            $scope.followUpClick(false);
        }
    }

    $scope.getDuplicateCustomer = function(rowData) {
        $scope.closeTarget('#popupOpportunityActionConfirmOpen');
        $scope.dataGetDuplicateCustomer = {};
        $scope.dataGetDuplicateCustomer = rowData;
        $scope.dataSetCustomerOpp.oppId = rowData.id;
        $ionicLoading.show({template: templateLoading});
        Opportunities.getDuplicateCustomer($scope.dataGetDuplicateCustomer).success(function(data) {
            $ionicLoading.hide();
            $scope.duplicateCustomer = data;
            $scope.openByGetTemplate('opportunityduplicatecustomer');
        });
    }

    $scope.setCustomerOpp = function() {
        if(!parseInt($scope.dataSetCustomerOpp.cusId)>0){
            $cordovaToast.showLongTop('Please select customer');
            return false;
        }
        $ionicLoading.show({template: templateLoading});
        Opportunities.setCustomerForOpp($scope.dataSetCustomerOpp).success(function(data) {
            if(data.status){
                $scope.pendingUpClick();
                $cordovaToast.showLongTop(data.msg);
                $scope.closeTarget('#opportunityduplicatecustomer');
                $scope.openByGetTemplate('popupOpportunityAction');
                $scope.fromFollowup = false;
                $scope.OpportunitiesActionData = {};
                $scope.OpportunitiesActionData.issue = '';
                $scope.OpportunitiesActionData.customerType = '';
                $scope.OpportunitiesActionData.city = '';
                $scope.OpportunitiesActionData.time = '';
                $scope.initialSearchCustomer = [];
                $scope.pendingId = $scope.dataSetCustomerOpp.oppId;
                $scope.getOpportunitiesActionData($scope.dataSetCustomerOpp.oppId);
                $scope.followUpClick(false);


            }
        });
    }

    $scope.ItemPendingId = '';
    $scope.getItemPenddingId = function (id, extOpp,caller_id) {
        $scope.selectNewCus = false;
        $scope.temp_phone = caller_id;
        if($scope.opportunityAction){
            if ($scope.currentExt == extOpp) {
                $scope.getItemPending(id);
            } else {
                $scope.ItemPendingId = id;
                dataHtml.getTemplate('templates/dashboard/opportunities/popup/popupOpportunityActionConfirmOpen.tpl').success(function (results) {
                    $scope.dataOppHtml.popupOpportunityActionConfirmOpen = results;
                    $scope.showTarget('#popupOpportunityActionConfirmOpen');
                    $ionicLoading.hide();
                });
            }
        }
        else{
            $cordovaToast.showLongCenter('No permissions !!!')
        }
        
    }

    $scope.setValueForDueDate = function (type) {
        switch (type) {
            case 'convertofollowup':
            $ionicLoading.show({template: templateLoading})
            dataHtml.getTemplate('templates/dashboard/opportunities/form/opportunityActionFollowUp.tpl').success(function (results) {
                $scope.dataOppHtml.opportunityActionFollowUp = results;
                $timeout(function () {
                    $scope.OpportunitiesActionData.selectCustomer.from_date = moment().format('MM/DD/YYYY');
                    $scope.OpportunitiesActionData.selectCustomer.to_date = moment().add(1, 'days').format('MM/DD/YYYY');
                    $scope.OpportunitiesActionData.selectCustomer.opportunitytab_id = '';
                    $('input[name="subHeadingConvertToFollowName"]').val('');
                    $scope.showTarget('#opportunityActionFollowUp');
                    $ionicLoading.hide();
                }, 500)
            });
            break;
        }
    }


    $scope.getOpportunitiesActionData = function (id , $callback) {
        $scope.idResetFormOpportunityAction = id;
        $scope.OpportunitiesActionData.selectCustomer = {};
        $scope.OpportunitiesActionData.selectCustomer.phone2 = [];
        var activeData = {};
        $ionicLoading.show({template: templateLoading});
        Opportunities.getDataFollowUp(id).success(function (data) {
            $scope.lastMessAndRoom = data.lastMessAndRoom;
            delete data.lastMessAndRoom;
            activeData = data;
            $scope.activeDataTemp = data;
            if(!$scope.reset_is_customer){
              $scope.is_customer = data.is_customer;
          }
          $scope.flagColor = data.flagColor;
          $scope.flagNote = data.flag_note;
          $scope.FilterOpportunitiesData = {'phone': 'all', 'recordtype': 'all', 'jobsite': 'none'};
          $scope.FilterOpportunitiesData.customerphone = data.phone;
          $scope.FilterOpportunitiesData.id = id;
          $scope.current_customer_id = data.customer_id;
          $scope.Opportunity_id = id;
          if (data.phone != '' && data.phone != null) {
            var checkResetForm = $scope.checkPhoneToResetForm(data.phone);
            if (checkResetForm) {
                $scope.noLoadAppHistory = true;
            } else {
                $scope.noLoadAppHistory = false;
            }
        }
        $scope.getAppointmentHistoryByCustomerId(data.customer_id);
        $scope.recordingfile = data.recordingfile;
        if (data.phone == '' || data.phone == null) {
            $scope.selectCustomer = false;
            $scope.OpportunitiesActionData.selectCustomer = activeData;
            if($scope.OpportunitiesActionData.selectCustomer.street.length>0){
                $scope.OpportunitiesActionData.selectCustomer.addStreet = [{place_id:'place_id',description:$scope.OpportunitiesActionData.selectCustomer.street}];
            }else{
                $scope.OpportunitiesActionData.selectCustomer.addStreet = [];
            }
            $scope.showdataautocomple = $scope.OpportunitiesActionData.selectCustomer.first_name + ' ' + $scope.OpportunitiesActionData.selectCustomer.last_name;
            $ionicLoading.hide();
        } else {
            if (checkResetForm) {
                $scope.selectCustomer = false;
                $scope.OpportunitiesActionData.selectCustomer = {};
                $scope.OpportunitiesActionData.selectCustomer.phone2 = [];
                $scope.estimate = [];
                $scope.saleorder = [];
                $scope.invoice = [];
                $scope.invoiceData = [];
                $scope.estimateData = [];
                $scope.saleorderData = [];
                $scope.incomingcalls = [];
                $scope.outgoingcalls = [];
                $scope.lastcontact = '';
                $scope.lastcontact_note = '';
                $scope.getallcustomer();
                $scope.showdataautocomple = '';
                $ionicLoading.hide();
            } else {
                $scope.getDataFilterOpportunities(id);
                if(parseInt($scope.current_customer_id) > 0){
                    Customers.getById($scope.current_customer_id).success(function (data) {
                        if (data[0] != null) {
                            $scope.estimate = data[0].estimate;
                            $scope.invoice = data[0].invoice;
                            $scope.saleorder = data[0].saleorder;
                            $scope.selectCustomer = true;
                            var temp_data = data[0];
                            temp_data = _.extend(temp_data, {
                                phone: temp_data.phone_number,
                                phone2: ''
                            });

                            $scope.estimate = data[0].estimate;
                            $scope.invoice = data[0].invoice;
                            $scope.invoiceData = [];
                            $scope.saleorderData = [];
                            $scope.estimateData = [];
                            for (var i = 0; i < $scope.invoice.length; i++) {
                                for (var j = 0; j < $scope.invoice[i].invoiceData.length; j++) {
                                    $scope.invoiceData.push($scope.invoice[i].invoiceData[j]);
                                }
                            }
                            for (var i = 0; i < $scope.saleorder.length; i++) {
                                for (var j = 0; j < $scope.saleorder[i].invoiceData.length; j++) {
                                    $scope.saleorderData.push($scope.saleorder[i].invoiceData[j]);
                                }
                            }
                            for (var i = 0; i < $scope.estimate.length; i++) {
                                for (var j = 0; j < $scope.estimate[i].estimateData.length; j++) {
                                    $scope.estimateData.push($scope.estimate[i].estimateData[j]);
                                }
                            }
                            $scope.incomingcalls = data[0].incoming;
                            $scope.outgoingcalls = data[0].outgoing;
                            $scope.jobsites = data[0].jobsites;
                            if (data[0].appointments.length > 0) {
                                $scope.getIconForAppointment(data[0].appointments);
                            } else {
                                $('.status-icon').removeAttr('style');
                                $scope.appointment = 'Null';
                                $scope.appointmentClass = 'null';
                                $scope.appointment_day = null;
                            }

                            Customers.show(data[0].id).success(function (res) {
                                if (res.phone.length > 0) {
                                    temp_data.phone2 = res.phone;
                                } else {
                                    temp_data.phone2 = [];
                                }
                                temp_data.email2 = res.email.slice(1)
                                $scope.OpportunitiesActionData.selectCustomer = temp_data;
                                if($scope.OpportunitiesActionData.selectCustomer.street.length>0){
                                    $scope.OpportunitiesActionData.selectCustomer.addStreet = [{place_id:'place_id',description:$scope.OpportunitiesActionData.selectCustomer.street}];
                                }else{
                                    $scope.OpportunitiesActionData.selectCustomer.addStreet = [];
                                }
                                $scope.getallcustomer();
                                $scope.showdataautocomple = $scope.OpportunitiesActionData.selectCustomer.first_name + ' ' + $scope.OpportunitiesActionData.selectCustomer.last_name;
                                $ionicLoading.hide();
                                if($callback) $callback();
                            });
                        } else {
                            $scope.estimate = [];
                            $scope.invoice = [];
                            $scope.saleorder = [];
                            $scope.invoiceData = [];
                            $scope.saleorderData = [];
                            $scope.estimateData = [];
                            $scope.incomingcalls = [];
                            $scope.outgoingcalls = [];
                            $scope.lastcontact = '';
                            $scope.lastcontact_note = '';
                            $scope.selectCustomer = false;
                            $scope.OpportunitiesActionData.selectCustomer = activeData;
                            if($scope.OpportunitiesActionData.selectCustomer.street && $scope.OpportunitiesActionData.selectCustomer.street.length>0){
                                $scope.OpportunitiesActionData.selectCustomer.addStreet = [{place_id:'place_id',description:$scope.OpportunitiesActionData.selectCustomer.street}];
                            }else{
                                $scope.OpportunitiesActionData.selectCustomer.addStreet = [];
                            }

                            $scope.OpportunitiesActionData.selectCustomer.phone2 = $scope.OpportunitiesActionData.selectCustomer.phone2 ? $scope.OpportunitiesActionData.selectCustomer.phone2 : [];
                            $scope.getallcustomer();
                            $scope.showdataautocomple = $scope.OpportunitiesActionData.selectCustomer.first_name + ' ' + $scope.OpportunitiesActionData.selectCustomer.last_name;
                            $ionicLoading.hide();
                        }
                    });
}else{
    $scope.estimate = [];
    $scope.saleorder = [];
    $scope.invoice = [];
    $scope.invoiceData = [];
    $scope.estimateData = [];
    $scope.saleorderData = [];
    $scope.incomingcalls = [];
    $scope.outgoingcalls = [];
    $scope.lastcontact = '';
    $scope.lastcontact_note = '';
    $scope.selectCustomer = false;
    $scope.OpportunitiesActionData.selectCustomer = activeData;
    if($scope.OpportunitiesActionData.selectCustomer.street && $scope.OpportunitiesActionData.selectCustomer.street.length>0){
        $scope.OpportunitiesActionData.selectCustomer.addStreet = [{place_id:'place_id',description:$scope.OpportunitiesActionData.selectCustomer.street}];
    }else{
        $scope.OpportunitiesActionData.selectCustomer.addStreet = [];
    }

    $scope.OpportunitiesActionData.selectCustomer.phone2 = $scope.OpportunitiesActionData.selectCustomer.phone2 ? $scope.OpportunitiesActionData.selectCustomer.phone2 : [];
    $scope.getallcustomer();
    $scope.showdataautocomple = $scope.OpportunitiesActionData.selectCustomer.first_name + ' ' + $scope.OpportunitiesActionData.selectCustomer.last_name;
    $ionicLoading.hide();
}

}
}
});
}
$scope.getOpportunitiesActionDataforCus = function(customerId){
    $scope.current_customer_id = customerId;
    Opportunities.actionSelectCustomer({customer_id:customerId,pending_id:$scope.pendingId}).success(function(res){
        if(res.status){
            $scope.selectNewCus = true;
            $scope.reset_is_customer = true;
            $scope.getOpportunitiesActionData($scope.pendingId,$scope.warningAddPhoneNumber());
        }
    });
}

$scope.DataFilterChanged = function () {
    $scope.getDataFilterOpportunities();
    $scope.closeTarget('#popupOpportunityHistoryFilter');
}
$scope.getDataFilterOpportunities = function (oppt_id) {
    $scope.currentOppId = oppt_id;
    $ionicLoading.show({
        template: templateLoading
    });
    $scope.items_filteroppt_perpage = 10;
    $scope.FilterOpportunitiesData['rows'] = $scope.items_filteroppt_perpage;
    $scope.FilterOpportunitiesData['current_page'] = 1;
    Customers.getDataFilterOpportunities($scope.FilterOpportunitiesData).success(function (data) {
        $ionicLoading.hide();
        if (data.data.length == $scope.items_filteroppt_perpage) {
            $timeout(function () {
                $scope.checkLoadMoreFilterHis = true;
            }, 1000)
        }
        $scope.current_filteroppt_page = data.current_page;
        $scope.items_filteroppt_perpage = $scope.FilterOpportunitiesData.rows;
        $scope.total_filteroppt_items = data.total_rows;
        $scope.lastcontact = data.lastcontact;
        if (data.data.length > 0) {
            $scope.DataFilterOpportunities = data.data;
            for (var i = 0; i < $scope.DataFilterOpportunities.length; i++) {
                var opportunitytab_id = $scope.DataFilterOpportunities[i].opportunitytab_id;
                $scope.DataFilterOpportunities[i].start_time = moment($scope.DataFilterOpportunities[i].start_time,'YYYY-MM-DD HH:mm:ss').format("MM/DD/YYYY");
                switch (opportunitytab_id) {
                    case '0':
                    $scope.DataFilterOpportunities[i].color = 'violet';
                    $scope.DataFilterOpportunities[i].title = 'Outgoing';
                    break;
                    case '10':
                    $scope.DataFilterOpportunities[i].color = 'green';
                    $scope.DataFilterOpportunities[i].title = 'Appointment';
                    break;
                    case '3':
                    case '5':
                    case '6':
                    case '7':
                    case '9':
                    case '27':
                    case '38':
                    $scope.DataFilterOpportunities[i].color = 'yellow';
                    $scope.DataFilterOpportunities[i].title = 'Active Follow up';
                    $scope.DataFilterOpportunities[i].oppt_id = oppt_id;
                    break;
                    case '12':
                    case '13':
                    case '14':
                    case '15':
                    $scope.DataFilterOpportunities[i].color = 'red';
                    $scope.DataFilterOpportunities[i].title = 'Fail';
                    break;
                    case '1':
                    $scope.DataFilterOpportunities[i].color = 'blue';
                    $scope.DataFilterOpportunities[i].title = 'Pending opportunity';
                    break;
                    case '18':
                    case '39':
                    $scope.DataFilterOpportunities[i].color = 'gray';
                    $scope.DataFilterOpportunities[i].title = 'AP/AR (billing)';
                    $scope.DataFilterOpportunities[i].othername = 'AP';
                    break;
                    case '20':
                    $scope.DataFilterOpportunities[i].color = 'gray';
                    $scope.DataFilterOpportunities[i].title = 'Dead/Spam';
                    $scope.DataFilterOpportunities[i].othername = 'D/S';
                    break;
                    case '21':
                    $scope.DataFilterOpportunities[i].color = 'gray';
                    $scope.DataFilterOpportunities[i].title = 'Customer Feedback';
                    $scope.DataFilterOpportunities[i].othername = 'CF';
                    break;
                    case '28':
                    $scope.DataFilterOpportunities[i].color = 'gray';
                    $scope.DataFilterOpportunities[i].title = 'Employee/Vendor';
                    $scope.DataFilterOpportunities[i].othername = 'EV';
                    break;
                    case '29':
                    $scope.DataFilterOpportunities[i].color = 'gray';
                    $scope.DataFilterOpportunities[i].title = 'Job Status';
                    $scope.DataFilterOpportunities[i].othername = 'JS';
                    break;
                    case '30':
                    $scope.DataFilterOpportunities[i].color = 'gray';
                    $scope.DataFilterOpportunities[i].title = 'N/A Service Scope';
                    $scope.DataFilterOpportunities[i].othername = 'N/A';
                    break;
                    case '31':
                    $scope.DataFilterOpportunities[i].color = 'gray';
                    $scope.DataFilterOpportunities[i].title = 'Task';
                    $scope.DataFilterOpportunities[i].othername = 'T';
                    break;
                    case '32':
                    $scope.DataFilterOpportunities[i].color = 'gray';
                    $scope.DataFilterOpportunities[i].title = 'Door Dept';
                    $scope.DataFilterOpportunities[i].othername = 'DD';
                    break;
                    case '33':
                    $scope.DataFilterOpportunities[i].color = 'gray';
                    $scope.DataFilterOpportunities[i].title = 'Walkin/Troubleshooting';
                    $scope.DataFilterOpportunities[i].othername = 'W/T';
                    break;
                }
            }
        } else {
            $scope.DataFilterOpportunities = [];
        }
        $('.tblloader.filter').hide();
            // console.log($scope.DataFilterOpportunities)
        });
}

$scope.loadMoreFilterOpportunities = function (oppt_id) {
    if (!$scope.checkLoadMoreFilterHis)
        return;
    $scope.items_filteroppt_perpage = 10;
    $scope.FilterOpportunitiesData['rows'] = $scope.items_filteroppt_perpage;
    $scope.FilterOpportunitiesData['current_page']++;
    Customers.getDataFilterOpportunities($scope.FilterOpportunitiesData).success(function (data) {
        $scope.current_filteroppt_page = data.current_page;
        $scope.items_filteroppt_perpage = $scope.FilterOpportunitiesData.rows;
        $scope.total_filteroppt_items = data.total_rows;
        $scope.lastcontact = data.lastcontact;
        if (data.data.length == 0) {
            $scope.checkLoadMoreFilterHis = false;
        }

        if (data.data.length > 0) {
            $scope.tempDataFilterOpportunities = data.data;
            for (var i = 0; i < $scope.tempDataFilterOpportunities.length; i++) {
                var opportunitytab_id = $scope.tempDataFilterOpportunities[i].opportunitytab_id;
                var date = new Date($scope.tempDataFilterOpportunities[i].start_time);
                var year = date.getFullYear();
                var month = (1 + date.getMonth()).toString();
                month = month.length > 1 ? month : '0' + month;
                var day = date.getDate().toString();
                day = day.length > 1 ? day : '0' + day;
                $scope.tempDataFilterOpportunities[i].start_time = month + '/' + day + '/' + year;
                switch (opportunitytab_id) {
                    case '0':
                    $scope.tempDataFilterOpportunities[i].color = 'violet';
                    $scope.tempDataFilterOpportunities[i].title = 'Outgoing';
                    break;
                    case '10':
                    $scope.tempDataFilterOpportunities[i].color = 'green';
                    $scope.tempDataFilterOpportunities[i].title = 'Appointment';
                    break;
                    case '3':
                    case '5':
                    case '6':
                    case '7':
                    case '9':
                    case '27':
                    case '38':
                    $scope.tempDataFilterOpportunities[i].color = 'yellow';
                    $scope.tempDataFilterOpportunities[i].title = 'Active Follow up';
                    $scope.tempDataFilterOpportunities[i].oppt_id = oppt_id;
                    break;
                    case '12':
                    case '13':
                    case '14':
                    case '15':
                    $scope.tempDataFilterOpportunities[i].color = 'red';
                    $scope.tempDataFilterOpportunities[i].title = 'Fail';
                    break;
                    case '1':
                    $scope.tempDataFilterOpportunities[i].color = 'blue';
                    $scope.tempDataFilterOpportunities[i].title = 'Pending opportunity';
                    break;
                    case '18':
                    case '39':
                    $scope.tempDataFilterOpportunities[i].color = 'gray';
                    $scope.tempDataFilterOpportunities[i].title = 'AP/AR (billing)';
                    $scope.tempDataFilterOpportunities[i].othername = 'AP';
                    break;
                    case '20':
                    $scope.tempDataFilterOpportunities[i].color = 'gray';
                    $scope.tempDataFilterOpportunities[i].title = 'Dead/Spam';
                    $scope.tempDataFilterOpportunities[i].othername = 'D/S';
                    break;
                    case '21':
                    $scope.tempDataFilterOpportunities[i].color = 'gray';
                    $scope.tempDataFilterOpportunities[i].title = 'Customer Feedback';
                    $scope.tempDataFilterOpportunities[i].othername = 'CF';
                    break;
                    case '28':
                    $scope.tempDataFilterOpportunities[i].color = 'gray';
                    $scope.tempDataFilterOpportunities[i].title = 'Employee/Vendor';
                    $scope.tempDataFilterOpportunities[i].othername = 'EV';
                    break;
                    case '29':
                    $scope.tempDataFilterOpportunities[i].color = 'gray';
                    $scope.tempDataFilterOpportunities[i].title = 'Job Status';
                    $scope.tempDataFilterOpportunities[i].othername = 'JS';
                    break;
                    case '30':
                    $scope.tempDataFilterOpportunities[i].color = 'gray';
                    $scope.tempDataFilterOpportunities[i].title = 'N/A Service Scope';
                    $scope.tempDataFilterOpportunities[i].othername = 'N/A';
                    break;
                    case '31':
                    $scope.tempDataFilterOpportunities[i].color = 'gray';
                    $scope.tempDataFilterOpportunities[i].title = 'Task';
                    $scope.tempDataFilterOpportunities[i].othername = 'T';
                    break;
                    case '32':
                    $scope.tempDataFilterOpportunities[i].color = 'gray';
                    $scope.tempDataFilterOpportunities[i].title = 'Door Dept';
                    $scope.tempDataFilterOpportunities[i].othername = 'DD';
                    break;
                    case '33':
                    $scope.tempDataFilterOpportunities[i].color = 'gray';
                    $scope.tempDataFilterOpportunities[i].title = 'Walkin/Troubleshooting';
                    $scope.tempDataFilterOpportunities[i].othername = 'W/T';
                    break;
                }
            }
            _.each($scope.tempDataFilterOpportunities, function (item) {
                $scope.DataFilterOpportunities.push(item);
            })

            $timeout(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 1000);
        }
    });
}
$scope.getIconForAppointment = function (appointments) {
    appointments = _.sortBy(appointments, function (node) {
        return -(new Date(node.dateofappt).getTime());
    });
    var today = new Date();
    var pre_appt = [];
    var post_appt = [];
    for (var i = 0; i < appointments.length; i++) {
        var date = new Date(appointments[i].dateofappt);
        var timeDiff = date.getTime() - today.getTime();
        var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
        if (diffDays == 0) {
            if (appointments[i].status == 'EnRoute' && appointments[i].callahead_id != NoCAId.toString()) {
                var jobstatus = differentNoCaAndRouteColor;
            } else {
                jobstatus = appointments[i].bgcolor;
            }
        } else if (diffDays > 0) {
            pre_appt.push(diffDays);
        } else {
            post_appt.push(Math.abs(diffDays));
        }
    }
    if (jobstatus) {
        $scope.appointmentClass = 'job-status';
        $scope.appointment = 'Jobstatus';
        $scope.appointment_day = null;
        $('.status-icon').css({'background-color': jobstatus});
    } else if (pre_appt.length) {
        $('.status-icon').removeAttr('style');
        $scope.appointmentClass = 'pre-appt';
        pre_appt.reverse();
        $scope.appointment = 'Pre Appt';
        $scope.appointment_day = pre_appt[0] + 'D';
    } else {
        $('.status-icon').removeAttr('style');
        $scope.appointmentClass = 'post-appt';
        if (post_appt[0] < 31) {
            $scope.appointment = 'Post Appt';
            $scope.appointment_day = post_appt[0] + 'D';
        } else if (post_appt[0] > 31 && post_appt[0] < 365) {
            $scope.appointment = 'Post Appt';
            $scope.appointment_day = Math.round(post_appt[0] / 31) + 'M';
        } else {
            var temp = Math.round((post_appt[0] / 365) * 10) / 10;
            var temp2 = temp.toString().split(".")[1];
            if (temp2 <= 5 || temp2 == undefined) {
                $scope.appointment = 'Post Appt';
                $scope.appointment_day = temp.toString().split(".")[0] + 'Y';
            } else {
                $scope.appointment = 'Post Appt';
                $scope.appointment_day = temp.toString().split(".")[0] + '.5Y';
            }
        }
    }
}
$scope.checkPhoneToResetForm = function (phone) {
    var trimPhone = $.trim(phone);
    trimPhone = trimPhone.replace(/-/g, '').replace(/\(/g, '').replace(/\)/g, '').replace(/\t/g, '').replace(/ /g, '');
    var phonelist = ['6126157339', '8667582786', '8779473639', '3203352120'];
    if (phonelist.indexOf(trimPhone) >= 0) {
        return true
    } else {
        return false;
    }
}
$scope.getItemFollowUpId = function (id, style) {
    if($scope.FollowUpdateBut){
        $scope.requiredFlag = false;
        $scope.followUpId = id;
        $scope.initialAssignItem = [];
        $ionicLoading.show({template: templateLoading});
        if (style == 'openForm') {
            $scope.openByGetTemplate('opportunityFollowUpFollowUp');
        }
        Opportunities.getDataFollowUp(id).success(function (data) {
            $scope.FilterOpportunitiesData = {'phone': 'all', 'recordtype': 'all', 'jobsite': 'none'};
            $scope.FilterOpportunitiesData.customerphone = data.phone;
            $scope.FilterOpportunitiesData.id = id;
            $scope.Opportunity_id = id;
            if (data.phone != '' && data.phone != null) {
                var checkResetForm = $scope.checkPhoneToResetForm(data.phone);
                if (checkResetForm) {
                    $scope.noLoadAppHistory = true;
                } else {
                    $scope.noLoadAppHistory = false;
                }
            }
            delete data.lastMessAndRoom;
            $ionicLoading.hide();
            $scope.dataFollowUpUpdate = data;
            $scope.recordingfile = data.recordingfile;
            $scope.setValueForSelectTitleInRootDataById($scope.dataFollowUpUpdate.opportunitytab_id, 'subheadingfollowup');
            if (data.assign) {
                $scope.initialAssignItem = data.assign.id;
            } else {
                $scope.initialAssignItem = '';
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
        if (!$scope.failSubtabInConvert.length > 0) {
            Opportunities.getFailSubtab().success(function (data) {
                $scope.failSubtabInConvert = data.data;
            }).error(function (data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        }
        $scope.$broadcast("reset");
    }
    else{
        $cordovaToast.showLongCenter('No permissions !!! ');
    }
}
$scope.convertToFail = function () {
    $scope.OpportunitiesActionData.pendingId = $scope.pendingId;
    $scope.dataConvertToFail.isfromPending = 0;
    $ionicLoading.show({
        template: templateLoading
    });
    Opportunities.convertToFail($scope.followUpId, $scope.dataConvertToFail).success(function (data) {
        if (data.status) {
            $ionicLoading.hide();
            $scope.followUpClick(false);
            $scope.subSabFollowContent($scope.currentFollowSubtabId, $scope.currentLocation);
            $scope.closeTarget('#opportunityFollowUpFollowUp');
            $scope.closeTarget('#opportunityFollowToFail');
            $scope.closeTarget('#opportunityFollowUpContent');
                    //$scope.followUpClick()
                    // $scope.countAllTab('follow');
                }
                else{
                    $cordovaToast.showLongCenter(data.msg)
                }
            });
}
$scope.convertToFailOther = function () {
    $scope.dataConvertToFailOther.isfromPending = 1;
    $ionicLoading.show({template: templateLoading})
    Opportunities.convertToFailOther($scope.pendingId, $scope.dataConvertToFailOther).success(function (data) {
        $ionicLoading.hide();
        if (data.status) {
            $scope.closeTarget('#popupOpportunityAction');
            $scope.closeTarget('#opportunityActionOther');
                    // $('#opportunityAction').css('display', 'none');
                    $scope.dataConvertToFailOther.description = '';
                    $scope.pendingUpClick();
                    $scope.countAllTab('pending');
                } else {
                }
            });
}
$scope.loadSelelectConvertFailOther = function () {
    $scope.openByGetTemplate('opportunityActionOther');
    $scope.dataConvertToFailOther = {};
    $scope.dataConvertToFailOther.typeConvert = 'fail';
    if ($scope.roleName == $scope.isReporter || $scope.roleName == $scope.isScheduler || $scope.roleName == $scope.isSupportAssistant || $scope.roleName == $scope.isOutsideSales) {
        $scope.dataConvertToFailOther.typeConvert = 'other';
    }
    $scope.failClick(false, '', 'onFunction');
    $scope.otherClick('onFunction');
}
$scope.followUpUpdate = function () {
    $scope.onFollowUpdate();
}
$scope.onFollowUpdate = function () {
    $scope.dataFollowUpUpdate.starttime = moment($scope.dataFollowUpUpdate.from_date).format("MM/DD/YYYY");
    $scope.dataFollowUpUpdate.endtime = moment($scope.dataFollowUpUpdate.to_date).format("MM/DD/YYYY");
    $scope.dataFollowUpUpdateCopy = angular.copy($scope.dataFollowUpUpdate);
    delete $scope.dataFollowUpUpdateCopy.addStreet;
    $ionicLoading.show({template: templateLoading});
    Opportunities.followUpUpdate($scope.followUpId, $scope.dataFollowUpUpdateCopy).success(function (data) {
        $ionicLoading.hide();
        if (data.status) {
            $timeout(function () {
                $scope.closeTarget('#opportunityFollowUpFollowUp');
            }, 2000);
            $scope.subSabFollowContent($scope.currentFollowSubtabId, $scope.currentLocation);
            $scope.checkCustomerOnFollow();
        } else {
            $cordovaToast.showLongTop(data.msg);
        }
    });
}

$scope.selectingFlag = function () {
    $scope.data_customer.flag_id = $scope.dataFollowUpUpdate.flag_id;
    $scope.data_customer.flag_note = $scope.dataFollowUpUpdate.flag_note;
    $scope.actionCustomerOnFollow($scope.data_customer, [], $scope.dataFollowUpUpdate.is_customer);
}

$scope.viewAppnote = function (dataOfficeNote, dataFieldWorkerNote) {
    openPopup('#popupviewappoimentlog');
    $scope.dataViewAppNote.office = dataOfficeNote;
    $scope.dataViewAppNote.fieldworker = dataFieldWorkerNote;
}
$scope.reOpenAppDetail = function () {
    openPopup('#popupAddopportunitiesAction');
}
$scope.actionCustomerOnFollow = function(data_customer, [], is_customer) {
    if (data_customer.email == null || data_customer.email == undefined || data_customer.email == '') {
        data_customer.email = 'none@none.com';
            // var confirm = $.confirm('Email Confirmation', '<div class="text-content baseline check_email">' + 'The customer email is blank, we will insert it as none@gmail.com. Are you sure to do it?' + '</div>', {
            //     messageType: 'warning',
            //     overlayTransparent: .75
            // }, function() {
            //     $scope.update_insert_customer_fromFollow(data_customer, [], is_customer);
            // });  
            // $('.check_email').parent().parent().parent().find('input[value="Cancel"]').click(function() {
            //     openPopup('#popupAddopportunitiesFollowUp');
            // });
            // $('.check_email').parent().parent().parent().find('.close-title-button').click(function() {
            //     openPopup('#popupAddopportunitiesFollowUp');
            // });

            var confirmPopup = $ionicPopup.confirm({
                title: 'Email Confirmation',
                template: '<div class="text-content baseline check_email">' + 'The customer email is blank, we will insert it as none@gmail.com. Are you sure to do it?' + '</div>'
            });

            confirmPopup.then(function (res) {
                if (res) {
                    $scope.update_insert_customer_fromFollow(data_customer, [], is_customer);
                } else {
                    $scope.showTarget('#opportunityFollowUpFollowUp');
                }
            });

        } else {
            $scope.update_insert_customer_fromFollow(data_customer, [], is_customer);
        }
    }

    $scope.update_insert_customer_fromFollow = function(data_customer, [], is_customer) {
        Opportunities.update_or_insert_customer(data_customer, [], is_customer).success(function (data) {
            if (data.status) {
                Customers.setCustomerId(data.id);
                $scope.customer_id = data.id;
                $scope.refreshOrders('');
                $scope.dataFollowUpUpdate.customer_id = data.id;
                $scope.dataFollowUpUpdate.is_customer = true;
                $scope.requiredFlag = false;
                $scope.setValBiginWatch(true);
                $scope.openByGetTemplate('opportunityAppointmentSpecificInformation');
                // showTarget('#opportunityAppointmentSpecificInformation');    
                $('#formAppointmentAdd input[name=seletedCallAheadName]').val('No CA');
                $scope.addAppointmentsData.callahead_id = '10';
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.checkCustomerOnFollow = function () {
        var data_customer = {};
        data_customer.first_name = $scope.dataFollowUpUpdate.first_name;
        data_customer.last_name = $scope.dataFollowUpUpdate.last_name;
        data_customer.middle_name = $scope.dataFollowUpUpdate.middle_name;
        data_customer.phone_number = $scope.dataFollowUpUpdate.phone;
        data_customer.email = $scope.dataFollowUpUpdate.email;
        data_customer.street = $scope.dataFollowUpUpdate.street;
        data_customer.city = $scope.dataFollowUpUpdate.city;
        data_customer.state = $scope.dataFollowUpUpdate.state;
        data_customer.zipcode = $scope.dataFollowUpUpdate.zipcode;
        data_customer.flag_id = $scope.dataFollowUpUpdate.flag_id;
        data_customer.flag_note = $scope.dataFollowUpUpdate.flag_note;
        data_customer.id = $scope.dataFollowUpUpdate.customer_id;
        data_customer.leadsource_id = $scope.dataFollowUpUpdate.leadsource_id;
        if ($scope.check_action_followup) {
            $scope.data_customer = data_customer;
            $scope.data_customer.note = $scope.dataFollowUpUpdate.customer_note;
            //!$scope.dataFollowUpUpdate.is_customer ? $scope.requiredFlag = false : $scope.actionCustomerOnFollow(data_customer, [], $scope.dataFollowUpUpdate.is_customer);
            if (!$scope.dataFollowUpUpdate.is_customer) {
                $scope.requiredFlag = false;
                $scope.actionCustomerOnFollow(data_customer, [], $scope.dataFollowUpUpdate.is_customer)
            } else {
                $scope.actionCustomerOnFollow(data_customer, [], $scope.dataFollowUpUpdate.is_customer)
            }
            // $('#frmpopupAddopportunitiesSelectFlag').find('.dismis-popup').unbind();
            // $('#frmpopupAddopportunitiesSelectFlag').find('.dismis-popup').click(function() {
            //     $scope.requiredFlag = false;
            // })

        } else {
            //closePopupById('popupAddopportunitiesFollowUp');
            $scope.dataFollowUpUpdate = {};
        }
    }
    $scope.$on('saveAppointment', function (e, data) {
        var params = data.data;
        params.order_id = $scope.addAppointmentsData.order_id;
        params.check_order = params.order_id ? 1 : 0;
        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) {
                if (!$scope.scheckPendingClicked) {
                    $scope.followUpClick(false);
                    $scope.subSabFollowContent($scope.currentFollowSubtabId, $scope.currentLocation);
                } else {
                    $scope.pendingUpClick();
                }
                $scope.closeTarget('#opportunityAppointmentSpecificInformation');
                $scope.closeTarget('#popupOpportunityAction');
                $("#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.addOpportunitiesData.selectCustomer = [];
                $scope.addAppointmentsData.order_id = [];
                $scope.initialDataOrder = [];
                $scope.initialDataCustomer = [];
                $scope.addAppointmentsData.appointmentgroup_id = '';
                $scope.totalItemspending--;
                $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.followUpUpdateSuccess = function () {
        _.each($scope.addAppointmentsData.jobsites, function (item) {
            item.customer_id = $scope.addAppointmentsData.customer_id;
            return item;
        })
        Appointments.save($scope.addAppointmentsData).success(function (data) {
            $scope.getAppointments();
            if (data.status) {
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.setPage = function (pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };
    $scope.createOpportunities = function () {
        if (!$scope.addOppAble) {
            return;
        }
        $scope.addOppAble = false;
        $scope.addOpportunitiesDataCopy = angular.copy($scope.addOpportunitiesData);
        delete $scope.addOpportunitiesDataCopy.selectCustomer.addStreet;
        if ($scope.tier.t2) {
            if (!$scope.addOpportunitiesDataCopy.selectCustomer.refferedcustomer) {
                $scope.addOpportunitiesDataCopy.selectCustomer.refferedcustomer = [];
            }
            $scope.addOpportunitiesDataCopy.selectCustomer.reffered_customer = $scope.addOpportunitiesDataCopy.selectCustomer.refferedcustomer.id;
            delete $scope.addOpportunitiesDataCopy.selectCustomer.refferedcustomer;
            delete $scope.addOpportunitiesDataCopy.selectCustomer.phone_raw;
        }
        delete $scope.addOpportunitiesDataCopy.selectCustomer.fullName;
        if (parseInt($scope.addOpportunitiesDataCopy.selectCustomer.leadsource_id) == 2 || parseInt($scope.addOpportunitiesDataCopy.selectCustomer.leadsource_id) == 4) {
            $scope.addOpportunitiesDataCopy.selectCustomer.timetable = moment($scope.addOpportunitiesDataCopy.selectCustomer.timetable).format("MM/DD/YYYY");
        }
        $ionicLoading.show({template: templateLoading});
        Opportunities.save($scope.addOpportunitiesDataCopy).success(function (data) {
            $ionicLoading.hide();
            $scope.closeTarget('#addOpportunity');
            if (data.status) {
                $scope.pendingUpClick();
                $scope.totalItemspending++;
                $scope.autocompleteList.dataCustomer = [];
                $scope.autocompleteList.dataCustomerRefer = [];
                $scope.addOpportunitiesData = {};
                $scope.addOppAble = true;
                $cordovaToast.showLongTop(data.msg);

            } else {
                $scope.addOppAble = true;
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.editOpportunities = function (id) {
        $('.loader').show();
        Opportunities.show(id).success(function (data) {
            $('.loader').hide();
            $scope.editOpportunitiesData = data;
        });
    }

    $scope.getCurrentHistory = function (index) {
        $scope.seletecdHistory = $scope.dataAddAppointmentHistory[index];
    }

    $scope.updateOpportunities = function () {
        var id = $scope.editOpportunitiesData.id;
        $('.loader').show();
        Opportunities.update(id, $scope.editOpportunitiesData).success(function (data) {
            $('.loader').hide();
            if (data.status) {
                $scope.editOpportunitiesData = {};
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
            $scope.getOpportunities();
        });
    }
    $scope.confrimOpportunities = function (id, title, content) {
        $scope.deleteOpportunitiesData = {
            id: id
        };
        var confirm = $.confirm(title, '<div class="text-content baseline">' + content + '</div>', {
            messageType: 'warning',
            titleIcon: 'remove',
            overlayTransparent: .75
        }, function () {
            $scope.deleteOpportunities(id, confirm);
        });
    }
    $scope.deleteOpportunities = function (id, confirm) {
        Opportunities.destroy(id).success(function (data) {
            $scope.deleteOpportunitiesData = {};
            if (data.status) {
                $.notification('<div class="text-content">' + data.msg + '</div>', {
                    messageType: 'message-success',
                    autoClose: true
                });
                confirm.switchStateDialog("close");
            } else {
                $.notification('<div class="text-content">' + data.msg + '</div>', {
                    messageType: 'message-success',
                    autoClose: true
                });
                confirm.switchStateDialog("close");
            }
            $scope.getOpportunities();
        });
    }

    $scope.refreshCustomers = function (customers) {
        if (customers.length > 0) {
            var params = {
                search: customers
            };
            Customers.getSelect2(params).success(function (data) {
                var diff = differentArray(data, $scope.addOpportunitiesData.selectCustomer);
                $scope.customerses = diff;
            })
        }
    };
    $scope.refreshOrders = function (search) {
        var params = {
            search: search,
            customer_id: $scope.customer_id
        };
        Orders.getSelect2(params).success(function (data) {
            var diff = differentArray(data);
            $scope.orderData = diff;
        })
    };
    $scope.changeOrder = function (orderData) {
        var path = window.location.href;
        var pathname = window.location.href.split('/');
        var pa = path.lastIndexOf('/' + pathname[pathname.length - 1]);
        if (orderData.ordertype_id == 4) {
            Orderstatuses.opportunitiesExport(orderData.id, orderData.name).success(function (data) {
                $scope.urlOrder = $sce.trustAsResourceUrl(data.link);
                openPopup('#pdfOrders');
            });
        } else {
            Ordertypes.export_file_pdf(orderData.id, 'opportunitiesExport', '').success(function (data) {
                $scope.urlOrder = $sce.trustAsResourceUrl(data.link);
                openPopup('#pdfOrders');
            });
        }
        //$scope.addOrder_idToAppointment = orderData.id;
        setTimeout(function () {
            $('#pdfOrders').parent().parent().find('.close-title-button').unbind();
            $('#pdfOrders').parent().parent().find('.close-title-button').click(function () {
                $('#shownameorder').hide();
                openPopup('#popupAddappointments');
            });
        }, 2000);
    }
    $scope.removedataautocomple = function () {
        $('#shownameorder').hide();
    }
    $scope.addAppointmentsData.checkorder = 0;
    $scope.addOrderToAppointment = function () {
        WorkingInvoice(1);
        $('#shownameorder').show();
        openPopup('#popupAddappointments');
    }
    $scope.showselect = 1;
    $scope.refreshCustomersAction = function (customers) {
        if (customers.length > 0) {
            var params = {
                search: customers
            };
            Customers.getSelect2(params).success(function (data) {
                var diff = differentArray(data, $scope.OpportunitiesActionData.selectCustomer);
                $scope.customerses = diff;
            })
        }
    };
    $scope.onSelectCreateAT = function ($item, $model, $label) {
        if (_.filter($scope.userFollow, function (val) {
            return parseInt(val.id) == parseInt($item.id);
        }).length > 0) {
            setTimeout(function () {
                $scope.$apply(function (val) {
                    $('#holdTCAssign').val('');
                    $cordovaToast.showLongTop('User exits in Follower');
                });
            }, 1);
            return;
        }
    }
    $scope.refreshAssign = function (search) {
        // var params = {
        //     search: search
        // };
        // Users.searchAssign(params).success(function(data) {
            $ionicLoading.show({template: templateLoading});
            Users.getSelect().success(function (data) {
                if (!startpage)
                    $ionicLoading.hide();
                data.forEach(function (item) {
                    var itm = {id: item.id.toString(), name: item.first_name + ' ' + item.last_name + ' - ' + item.positiontitles_name};
                    $scope.rootUserAssign.push(itm);
                })
                loadSelectApp('btnsucessaddappointment', $scope.recordingfile);
                $scope.otherClick();
            })
        };
        $scope.requiredEmail = function (addOpportunities) {
            switch (addOpportunities) {
                case 'pending':
                if ($scope.OpportunitiesActionData.selectCustomer.email == undefined || $scope.OpportunitiesActionData.selectCustomer.email == '') {
                    $('#emailaction').removeAttr('required');
                } else {
                    $('#emailaction').attr('required', 'required');
                }
                break;
                case 'addOpportunities':
                if ($scope.addOpportunitiesData.selectCustomer.email == undefined || $scope.addOpportunitiesData.selectCustomer.email == '') {
                    $('#emailaddOpportunities').removeAttr('required');
                } else {
                    $('#emailaddOpportunities').attr('required', 'required');
                }
                break;
                case 'follow':
                if ($scope.dataFollowUpUpdate.email == undefined || $scope.dataFollowUpUpdate.email == '') {
                    $('#emailfollow').removeAttr('required');
                } else {
                    $('#emailfollow').attr('required', 'required');
                }
                break;
                case 'convertToFollowUp':
                if ($scope.OpportunitiesActionData.selectCustomer.email == undefined || $scope.OpportunitiesActionData.selectCustomer.email == '') {
                    $('#convertToFollowUp').removeAttr('required');
                } else {
                    $('#convertToFollowUp').attr('required', 'required');
                }
                break;
            }
        }
        $scope.addRowPhoneEdit = function () {
            if($scope.clickFirstTimeAddphone){
                $scope.openByGetTemplate('popupWarningAddPhoneEmail');
                $scope.clickFirstTimeAddphone = false;
            }
            $scope.OpportunitiesActionData.selectCustomer.phone2.push({phone: '', phone_detail: ''});
        }

        $scope.addRowEmail = function() {
            if($scope.clickFirstTimeAddphone){
                $scope.openByGetTemplate('popupWarningAddPhoneEmail');
                $scope.clickFirstTimeAddphone = false;
            }
            if(!$scope.OpportunitiesActionData.selectCustomer.email2){
                $scope.OpportunitiesActionData.selectCustomer.email2 = [];
            }
            $scope.OpportunitiesActionData.selectCustomer.email2.push({
                email: '',
                email_detail : ''
            });
        }

        $scope.removeItemPhoneEdit = function (index) {
            if($scope.OpportunitiesActionData.selectCustomer.phone2[index].id && parseInt($scope.OpportunitiesActionData.selectCustomer.phone2[index].id) > 0){
                $scope.delelePhone = $scope.OpportunitiesActionData.selectCustomer.phone2[index].phone;
                $scope.indexPhoneDelete = index;
                $scope.openByGetTemplate('popupConfirmDeletePhones');
            }else{
                $scope.OpportunitiesActionData.selectCustomer.phone2.splice(index, 1);
            }
        }

        $scope.removeItemEmail = function (index) {
            if($scope.OpportunitiesActionData.selectCustomer.email2[index].id && parseInt($scope.OpportunitiesActionData.selectCustomer.email2[index].id) > 0){
                $scope.deleleMail = $scope.OpportunitiesActionData.selectCustomer.email2[index].email;
                $scope.indexMailDelete = index;
                $scope.openByGetTemplate('popupConfirmDeleteMail');
            }else{
                $scope.OpportunitiesActionData.selectCustomer.email2.splice(index, 1);
            }
        }

        $scope.deleteCustomersphone = function (index) {
            $scope.OpportunitiesActionData.selectCustomer.phone2.splice(index, 1);
            $scope.closeTarget('#popupConfirmDeletePhones');
        }
        $scope.deleteCustomerEmail = function (index) {
            $scope.OpportunitiesActionData.selectCustomer.email2.splice(index, 1);
            $scope.closeTarget('#popupConfirmDeleteMail');
        }
    //update or insert customer
    $scope.openPopupSpecific_Information = function ($query) {
        $scope.customer_data.first_name = $scope.OpportunitiesActionData.selectCustomer.first_name;
        $scope.customer_data.last_name = $scope.OpportunitiesActionData.selectCustomer.last_name;
        $scope.customer_data.middle_name = $scope.OpportunitiesActionData.selectCustomer.middle_name;
        $scope.customer_data.company_name = $scope.OpportunitiesActionData.selectCustomer.company_name;
        $scope.customer_data.street = $scope.OpportunitiesActionData.selectCustomer.street;
        $scope.customer_data.apt_unit = $scope.OpportunitiesActionData.selectCustomer.apt_unit;
        $scope.customer_data.city = $scope.OpportunitiesActionData.selectCustomer.city;
        $scope.customer_data.state = $scope.OpportunitiesActionData.selectCustomer.state;
        $scope.customer_data.zipcode = $scope.OpportunitiesActionData.selectCustomer.zipcode;
        $scope.customer_data.phone_number = $scope.OpportunitiesActionData.selectCustomer.phone;
        $scope.customer_data.email = $scope.OpportunitiesActionData.selectCustomer.email;
        $scope.customer_data.email_detail = $scope.OpportunitiesActionData.selectCustomer.email_detail;
        $scope.customer_data.customer_comment = $scope.OpportunitiesActionData.selectCustomer.customercomment;
        $scope.customer_data.flag_id = $scope.OpportunitiesActionData.selectCustomer.flag_id;
        $scope.customer_data.flag_note = $scope.OpportunitiesActionData.selectCustomer.flag_note;
        $scope.customer_data.id = $scope.OpportunitiesActionData.selectCustomer.id;
        $scope.customer_data.leadsource_id = $scope.OpportunitiesActionData.selectCustomer.leadsource_id;
        $scope.customer_data.email2 = $scope.OpportunitiesActionData.selectCustomer.email2;
        $scope.customer_data.phone_detail = $scope.OpportunitiesActionData.selectCustomer.phone_detail;
        if ($scope.tier.t2) {
            if (!$scope.OpportunitiesActionData.selectCustomer.refferedcustomer) {
                $scope.OpportunitiesActionData.selectCustomer.refferedcustomer = {};
            }
            $scope.customer_data.reffered_customer = $scope.OpportunitiesActionData.selectCustomer.refferedcustomer.id;
        }

        $scope.customer_phone = [];
        if ($scope.OpportunitiesActionData.selectCustomer.phone2) {
            for (var i = 0; i < $scope.OpportunitiesActionData.selectCustomer.phone2.length; i++) {
                var item = $scope.OpportunitiesActionData.selectCustomer.phone2[i];
                $scope.customer_phone.push({id: item.id, phone: item.phone, phone_detail: item.phone_detail});
            }
            ;
        }

        if ($scope.customer_data.email == null || $scope.customer_data.email == undefined || $scope.customer_data.email == '') {
            $scope.customer_data.email = 'none@none.com';
            var confirmPopup = $ionicPopup.confirm({
                title: 'Email Confirmation',
                template: '<div class="text-content baseline check_email">' + 'The customer email is blank, we will insert it as none@gmail.com. Are you sure to do it?' + '</div>'
            });
            confirmPopup.then(function (res) {
                if (res) {
                    $scope.closeTarget('#popupOpportunityAction');
                    // $('#popupOpportunityAction').css('display', 'none');
                    $scope.checkAdditionalPhoneCustomer();
                }
                // else {
                //     // $('#opportunityAction').css('display', 'block');
                //     // showTarget('#opportunityAction');
                // }
            });
        } else {
            $scope.checkAdditionalPhoneCustomer();
        }
    };
    $scope.update_insert_customer_fromPending = function () {
        $scope.closeTarget('#popupCheckAdditionalPhones');
        $ionicLoading.show({template: templateLoading});
        Opportunities.update_or_insert_customer($scope.customer_data, $scope.customer_phone, $scope.selectCustomer,$scope.pendingId).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.setValBiginWatch(true);
                Customers.setCustomerId(data.id);
                $scope.customer_id = data.id;
                $scope.refreshOrders('');
                setTimeout(function () {
                    $scope.$apply(function () {
                        loadSelectApp('btnappointment', $scope.recordingfile , data.customer_type);
                        $scope.openByGetTemplate('opportunityAppointmentSpecificInformation');
                        $('#formAppointmentAdd input[name=seletedCallAheadName]').val('No CA');
                        $scope.addAppointmentsData.callahead_id = '10';
                    });
                }, 1);
                $scope.selectCustomer = true;
                $scope.OpportunitiesActionData.selectCustomer.id = data.id;
                $scope.getAppointmentHistoryByCustomerId($scope.OpportunitiesActionData.selectCustomer.id);
                $scope.jobsitesByCustomerId(data.id);
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
            setTimeout(function () {
                $scope.$apply(function (val) {
                    $('.timepicker').attr('readonly', true);
                    $(".timepicker").keydown(function (event) {
                        event.preventDefault();
                    });
                });
            }, 100);
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }

    $scope.check_submitfrom = function (action) {
        action == "success" ? $scope.check_action_followup = true : $scope.check_action_followup = false;
        if (action == "success") {
            $scope.fromFollowup = true;
        } else {
            $scope.requireAddress = false;
        }
    };

    $scope.setRequiredAddress = function (action) {
        $scope.requireAddress = true;
    };

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

    // for task
    $scope.getUsers = function () {
        $scope.clickAddTaskLoadSubHeading = true;
        $scope.formData = {};
        $scope.formData.type = 'Incomplete';
        $scope.formData.pendingId = $scope.pendingId;
        $scope.grouptask = [];
        $scope.userFollow = [];
        $('input[name="starttime"]').val(moment().format(conFig.formatDate.toUpperCase()));
        $('input[name="endtime"]').val(moment().add(1, 'days').format(conFig.formatDate.toUpperCase()));
        var _param = {
            rows: 'All'
        }
        $ionicLoading.show({template: templateLoading});
        Groups.getSelect().success(function (data) {
            $scope.grouptask = data;
            if ($scope.allUser == undefined) {
                $scope.allUser = [];
                Users.getPaging(_param).success(function (data) {
                    if (!startpage)
                        $ionicLoading.hide();
                    _.each(data.data, function (val, index) {
                        nick_name = val.first_name + ' ' + val.last_name;
                        var _item = {
                            id: val.id,
                            screen_name: nick_name + ' - ' + val.positiontitles_name,
                            name: nick_name,
                            imgprofile: pathToPublic + val.image_pic,
                            email: val.email
                        }
                        $scope.allUser.push(_item);
                    });
                    $scope.refreshAssign();
                });
            }
            $scope.loadedDataSelect = true;
        });
    };
    $scope.setDatepicker = function () {
        $('input[name="starttime"]').val(moment().format(conFig.formatDate.toUpperCase()));
        $('input[name="endtime"]').val(moment().add(1, 'days').format(conFig.formatDate.toUpperCase()));
    }
    $scope.filterFollow = function ($query) {
        var qStringUser = [];
        ($scope.formData.assign == undefined || $scope.formData.assign == '') ? qStringUser = $scope.allUser : qStringUser = _.filter($scope.allUser, function (val) {
            return val.id != parseInt($scope.formData.assign.id);
        });
        return qStringUser.filter(function (user) {
            return user.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
        });
    };
    // change assign
    $scope.onSelectCreate = function ($item, $model, $label) {
        if (_.filter($scope.userFollow, function (val) {
            return parseInt(val.id) == parseInt($item.id);
        }).length > 0) {
            setTimeout(function () {
                $scope.$apply(function (val) {
                    $('#holdTCAssign').val('');
                    $cordovaToast.showLongTop('User exits in Follower');
                });
            }, 1);
            return;
        }
    }
    $scope.setdefaultAssign = function () {
        $scope.formData.assign = '';
        return $scope.formData.assign = {
            id: null
        };
    }
    $scope.beforeCreateTask = function () {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.formData.fileUploadded = [];
        if ($scope.files != undefined && $scope.files.length) {
            $scope.uploadAmazon($scope.files);
        } else {
            $scope.createTask();
        }
    }
    $scope.uploadAmazon = function (dataFiles) {
        countDataFiles = dataFiles.length;
        angular.forEach(dataFiles, function (item) {
            $scope.fileUploadData = {};
            $scope.fileUploadData.type = item.type;
            $scope.fileUploadData.name = item.name;
            $scope.fileUploadData.bucket = bucketName;
            $scope.fileUploadData.acl = aclConfig;
            $scope.fileUploadData.for = 'tasks';
            Login.getConfigFileUpload($scope.fileUploadData).success(function (data) {
                var Uoptions = {};
                Uoptions.fileKey = "file";
                Uoptions.fileName = data.folder + '/' + data.microtime + item.name;
                Uoptions.mimeType = item.type;
                Uoptions.chunkedMode = false;
                Uoptions.headers = {
                    connection: "close"
                };
                Uoptions.params = {
                    "Key": data.folder + '/' + data.microtime + item.name,
                    "AWSAccessKeyId": data.awsAccessKeyId,
                    "acl": data.acl,
                    "Policy": data.policy,
                    "Signature": data.signature,
                    "success_action_status": data.successActionStatus,
                    "Content-Type": item.type
                };
                $cordovaFileTransfer.upload('http://' + bucketName + '.s3.amazonaws.com/', item.localURL, Uoptions).then(function (return_data) {
                    try {
                        var fileLocation = return_data.headers.Location;
                    } catch (e) {
                        $scope.jsonObject = xml2json.parser(return_data.response);
                        var fileLocation = $scope.jsonObject.postresponse.location;
                    }
                    console.log(fileLocation, 'success');
                    var type = 'file';
                    var ext = fileLocation.substring(fileLocation.lastIndexOf('.') + 1);
                    if (ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "png" || ext == "PNG") {
                        var type = 'img';
                    }
                    $scope.formData.fileUploadded.push({
                        path: fileLocation,
                        type: type
                    });
                    console.log($scope.uploadType, $scope.formData.fileUploadded.length, dataFiles.length)
                    if ($scope.formData.fileUploadded.length == countDataFiles) {
                        $scope.formData.files = undefined;
                        console.log('create task');
                        $scope.createTask();
                    }
                }, function (err) {
                    countDataFiles--;
                    $ionicLoading.hide();
                    $cordovaToast.showLongTop('Can\'t upload ' + item.name);
                    console.log(err.body);
                });
            });
        })
    }
    // end edit

    $scope.createTask = function () {
        var start = $('#add_task_from_date').val();
        var end = $('#add_task_to_date').val()
        var objParam = {};
        var objParam = _.extend(this.formData, {
            usersfollow: $scope.userFollow,
            starttime: start,
            endtime: end,
            fdate: conFig.fDatetoServer
        });
        $scope.formData.pendingId = $scope.pendingId;
        $scope.formData.starttime = moment($scope.formData.starttime).format("MM/DD/YYYY");
        $scope.formData.endtime = moment($scope.formData.endtime).format("MM/DD/YYYY");
        $scope.formData.type == 'Downtime' ? objParam.usersfollow = _.filter(objParam.usersfollow, function (val) {
            return val.id != parseInt(currentIdLogin);
        }) : '';
        if ($scope.formData.assign != undefined) {
            objParam.usersfollow = _.filter(objParam.usersfollow, function (val) {
                return val.id != parseInt($scope.formData.assign.id);
            });
            if ($scope.formData.assign.id == undefined) {
                $scope.setdefaultAssign();
            }
        } else {
            $scope.setdefaultAssign;
        }
        // auto owner follow
        var ownerFollowing = _.where($scope.allUser, {id: currentIdLogin});
        if (($scope.formData.type == 'Incomplete' && ($scope.formData.assign == undefined || $scope.formData.assign == '')) || $scope.formData.type == 'Incomplete' && $scope.formData.assign != undefined && parseInt(currentIdLogin) != parseInt($scope.formData.assign.id)) {
            objParam.usersfollow = _.union(objParam.usersfollow, ownerFollowing);
        }
        $scope.countAllTab('pending');

        $ionicLoading.show({template: templateLoading});
        Opportunities.createTask(objParam, currentIdLogin).success(function (data) {
            if(data.status == false){
                $cordovaToast.showLongCenter(data.msg);
            }
            else{
                $ionicLoading.hide();
                $scope.closeTarget('#popupOpportunityAction');
                $scope.closeTarget('#opportunityActionAddTask');
                document.getElementById("oppotunitiesAddTask").reset();
                // $('#popupOpportunityAction').css('display', 'none');
                $scope.formData = {};

                if ($scope.tier.t1) {
                    Tasks.sendmail(data.id, 'createTask', parseInt(currentIdLogin), window.location.href.replace("opportunities.html", "tasks.html")).success(function (data) {
                        if (data.status) {
                            Tasks.createHistory(data.id, data.comments).success(function (data) {})
                        }
                    });
                } else {
                    Tasks.sendmail(data.id, 'createTask', parseInt(currentIdLogin)).success(function (data) {})
                }
            }
        });

    }
    $scope.getDataGroup = function (group_id) {
        $scope.formData.assign = [];
        $scope.userFollow = [];
        $scope.initialUserFollower = [];
        $scope.initialUserFollowerDataTemp = [];

        $scope.initialUserAssign = [];
        $scope.initialUserAssignDataTemp = [];

        if (group_id == '')
            return;
        Tasks.getDataGroup(group_id).success(function (data) {
            angular.forEach(data.follow, function (item) {
                $scope.initialUserFollowerDataTemp.push(item.id);
            });
            $scope.initialUserFollower = $scope.initialUserFollowerDataTemp;
            $scope.initialUserAssignDataTemp = [data.assige.id];
            $scope.initialUserAssign = $scope.initialUserAssignDataTemp;

        });
    }
    $scope.hover = function (id, content) {
        $('.res-newfeed').hide();
        if (content != '' && content != null) {
            $("[opp-id='" + id + "']").parent().find('.res-newfeed').show();
        }
    }
    $scope.leave = function () {
        $('.res-newfeed').hide();
    }

    $scope.searchAllOpportunities = function (search) {
        if ($scope.tier.t2) {
            if (search.length > 0) {
                var params = {
                    search: search
                };
                Opportunities.searchAllOpportunities(params).success(function (data) {
                    var diff = differentArray(data, $scope.assign);
                    $scope.allUserSelect = diff;
                })
            } else {
                $scope.allUserSelect = [];
            }
        }
    };

    $scope.opportunitiesClicked = function (action, id) {
        if ($scope.tier.t2) {
            if (action == 'Pending') {
                $scope.getItemPenddingId(id);
                openPopup('#popupAddopportunitiesAction');
            }
            if (action == 'Follow-Up') {
                $scope.getItemFollowUpId(id);
                openPopup('#popupAddopportunitiesFollowUp');
            }
        }
    };

    $scope.refreshReffereds = function (search) {
        if ($scope.tier.t2) {
            if (search.length > 0) {
                var params = {
                    search: search
                };
                Customers.getReffereds(params).success(function (res) {
                    var diff = differentArray(res.data, $scope.addOpportunitiesData.selectCustomer.refferedcustomer);
                    $scope.refferedsSelect = diff;
                })
            } else {
                $scope.refferedsSelect = [];
            }
        }
    };

    $scope.autoComplete = function (query, type) {
        var returnValue = {
            items: []
        };
        switch (type) {
            case 'search':
            if (query.length > 0) {
                $('#autocomplete-search-opp .none-result').css('display','none');
                var params = {
                    search: query
                };
                $scope.coundown = 10;
                if ($scope.myTime != null)
                    clearInterval($scope.myTime);
                $scope.myTime = setInterval(function () {
                    $scope.coundown--;
                    if ($scope.coundown <= 0) {
                        clearInterval($scope.myTime);
                        $ionicLoading.show({template: templateLoading});
                        Opportunities.searchAllOpportunities(params).success(function (data) {
                            $ionicLoading.hide();
                            if (data.length > 0) {
                                var grouptab = _.groupBy(data, function (item) {
                                    return item.tabCurrent;
                                })

                                data[0].fail = grouptab['Fail'] ? grouptab['Fail'].length : 0;
                                data[0].followup = grouptab['Follow-Up'] ? grouptab['Follow-Up'].length : 0;
                                data[0].pending = grouptab['Pending'] ? grouptab['Pending'].length : 0;
                                data[0].success = grouptab['Success'] ? grouptab['Success'].length : 0;
                                data[0].other = grouptab['Other'] ? grouptab['Other'].length : 0;
                            }
                            data.forEach(function (item) {
                                returnValue.items.push(item);
                            })
                            if(returnValue.items.length > 0){
                                $('#autocomplete-search-opp .none-result').css('display','none');
                            }
                            else{
                                $('#autocomplete-search-opp .none-result').css('display','block');
                            }
                        })
                    }
                }, 100);       
            }

            break;
            case 'cus':
            var params = {
                search: query
            };
            $('#temp-autocomplete .none-result').css('display','none');
            $scope.coundown = 10;
            if ($scope.myTime != null)
                clearInterval($scope.myTime);
            $scope.myTime = setInterval(function () {
                $scope.coundown--;
                if ($scope.coundown <= 0) {
                    clearInterval($scope.myTime);
                    $ionicLoading.show({template: templateLoading});
                    Customers.getSelect2(params).success(function (data) {
                        $ionicLoading.hide();
                        $scope.rootDataCustomer = data;
                        $scope.rootDataCustomer.forEach(function (item) {
                            item.fullName = item.first_name + ' ' + item.last_name + ' ' + item.street + ' ' + item.phone;
                        })
                        $scope.rootDataCustomer.forEach(function (item) {
                            if ($scope.autocompleteList.dataCustomer.indexOf(item.id) < 0) {
                                if (item.fullName.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                                    returnValue.items.push(item);
                                } else if (item.id.indexOf(query) > -1) {
                                    returnValue.items.push(item);
                                } else if (replaceAllPhone(item.phone).indexOf(replaceAllPhone(query)) > -1) {
                                    returnValue.items.push(item);
                                }
                            }
                        });
                        if(returnValue.items.length > 0){
                            $('#temp-autocomplete .none-result').css('display','none');
                        }
                        else{
                            $('#temp-autocomplete .none-result').css('display','block');
                        }
                    })
                }
            }, 100);
            break;

            case 'opp':
            $scope.rootUserAssign.forEach(function (item) {
                if ($scope.autocompleteList.dataAssignUser.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;

            case 'asg':
            var params = {
                search: query,
                from : 'oppotunity'
            };
            $ionicLoading.show({template: templateLoading});
            Users.searchAssign(params).success(function (data) {
                $ionicLoading.hide();
                $scope.rootUserAssign = data;
                $scope.rootUserAssign.forEach(function (item) {
                    if ($scope.autocompleteList.dataAssignUser.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;
            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;

            case 'order':
            var params = {
                search: query,
                customer_id: $scope.customer_id
            };
            $ionicLoading.show({template: templateLoading});
            Orders.getSelect2(params).success(function (data) {
                $ionicLoading.hide();
                $scope.rootDataOrder = data;
                $scope.rootDataOrder.forEach(function (item) {
                    if ($scope.autocompleteList.dataOrder.indexOf(item.id) < 0) {
                        if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                            returnValue.items.push(item);
                        } else if (item.id.indexOf(query) > -1) {
                            returnValue.items.push(item);
                        }
                    }
                });
            })
            // }
            break;

            case 'cusAction':
            // if (query.length > 0) {
                var params = {
                    search: query
                };
                $ionicLoading.show({
                    template: templateLoading
                });
                Customers.getSelect2(params).success(function (data) {
                    $ionicLoading.hide();
                    $scope.rootDataCustomerAction = data;
                    $scope.rootDataCustomerAction.forEach(function (item) {
                        if ($scope.autocompleteList.dataCustomerAction.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;

            case 'referonaction':
            if (query.length > 0) {
                var params = {
                    search: query
                };
                $ionicLoading.show({
                    template: templateLoading
                });
                Customers.getReffereds(params).success(function (res) {
                    $ionicLoading.hide();
                    $scope.rootDataRefferedCus = res.data;
                    $scope.rootDataRefferedCus.forEach(function (item) {
                        if ($scope.autocompleteList.dataCustomerRef.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);
                            } else if (replaceAllPhone(item.phone).indexOf(replaceAllPhone(query)) > -1) {
                                returnValue.items.push(item);
                            }
                        }
                    });
                })
            }
            break;

            case 'asgtask':
            $scope.allUser.forEach(function (item) {
                if ($scope.autocompleteList.dataUserAsign.indexOf(item.id) < 0) {
                    item.id = item.id.toString();
                    if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    } else if (item.id.indexOf(query) > -1) {
                        returnValue.items.push(item);
                    }
                }
            });
            break;

            case 'follower':
            $scope.allUser.forEach(function (item) {
                if ($scope.autocompleteList.dataUserFollower.indexOf(item.id) < 0) {
                    item.id = item.id.toString();
                    if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    } else if (item.id.indexOf(query) > -1) {
                        returnValue.items.push(item);
                    }
                }
            });
            break;
            case 'oppfiltercity':
            $scope.dataFilterCity.forEach(function (item) {
                if ($scope.autocompleteList.oppfiltercity.indexOf(item.city) < 0) {
                    if (item.city.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    } else if (item.city_state.indexOf(query) > -1) {
                        returnValue.items.push(item);
                    }
                }
            });
            break;
            case 'oppfilterzip':
            $scope.dataFilterZipcodeDetail.forEach(function (item) {
                if ($scope.autocompleteList.oppfilterzip.indexOf(item.city) < 0) {
                    if (item.postal_code.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    }
                }
            });
            break;
            case 'oppfilterphone':
            var params = {
                search: query
            };
            $ionicLoading.show({
                template: templateLoading
            });
            Opportunities.getPhoneOpp(params).success(function (data) {
                $ionicLoading.hide();
                var diff = differentArray(data, $scope.dataFilterOppotunities.objphone);
                $scope.phoneResultDataFilter = diff;
                $scope.phoneResultDataFilter.forEach(function (item) {
                    if ($scope.autocompleteList.oppfilterphone.indexOf(item.id) < 0) {
                        if (item.phone.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                            returnValue.items.push(item);
                        }
                    }
                });

            })
            break;
            case 'oppfilterleadsource':
            var params = {search: query};
            $scope.dataFilterLeadsource.forEach(function (item) {
                if ($scope.autocompleteList.oppfilterleadsource.indexOf(item.key) < 0) {
                    if (item.key.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    }
                }
            });
            break;
            case 'oppfilterrep':
            var params = {search: query};
            $scope.dataOfficeEmployeee.forEach(function (item) {
                if ($scope.autocompleteList.oppfilterrep.indexOf(item.id) < 0) {
                    if (item.id.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    } else if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    }
                }
            });
            break;
            case 'oppfilterassignee':
            var params = {search: query};
            $scope.dataOfficeAssignee.forEach(function (item) {
                if ($scope.autocompleteList.oppfilterassignee.indexOf(item.id) < 0) {
                    if (item.id.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    } else if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    }
                }
            });
            break;
        }
        return returnValue;
    };

    $scope.clickOnItem = function (callback, type) {
        switch (type) {
            case 'search':
            var tabid = parseInt(callback.item.opportunitytab_id);
            var failtab = [12, 13, 14, 15];
            if (tabid == 1) {
                $scope.getItemPenddingId(callback.item.id);
                $scope.initialOpportunityForSearch = [];
            } else if (tabid == 6) {
                var followdata = callback.item;
                $scope.openTabFollowup(followdata);
            } else if (failtab.indexOf(tabid) >= 0) {
                $scope.failClick(callback.item.id, tabid + '');
            }

            break
            case 'cus':
            $scope.addOpportunitiesData.selectCustomer = callback.item;
            $scope.addOpportunitiesData.selectCustomer.addStreet = [{place_id:'place_id',description:$scope.addOpportunitiesData.selectCustomer.street}];
            $scope.autocompleteList.dataCustomerRefer = $scope.addOpportunitiesData.selectCustomer.refferedcustomer;
            $scope.autocompleteViewCustomer = callback.item.first_name + ' ' + callback.item.last_name;
            var lead = _.where($scope.leadsources, {id: $scope.addOpportunitiesData.selectCustomer.leadsource_id});
            $('#formAddOppotunities input[name=leadsourcesName]').val(lead[0].name);
            if (parseInt($scope.addOpportunitiesData.selectCustomer.leadsource_id) == 2 || parseInt($scope.addOpportunitiesData.selectCustomer.leadsource_id) == 4) {
                $scope.showTimetable = true;
            } else {
                $scope.showTimetable = false;
            }
            break
            case 'ref':
            $scope.autocompleteList.dataCustomerRefer = callback.item;
            break
            case 'asg':
            $scope.dataFollowUpUpdate.assign = callback.item;
            break
            case 'apptype':
            appScopeMobile.fieldWorker(callback.item.id);
            appScopeMobile.addAppointmentsData.appointmentgroup_id = callback.item.id;
            break;
            case 'order':
            $scope.addAppointmentsData.order_id = callback.item;
            $ionicLoading.show({
                template: templateLoading
            });
            Ordertypes.export_file_pdf($scope.addAppointmentsData.order_id.id, 'opportunitiesExport', '').success(function (data) {
                $ionicLoading.hide();
                $scope.cordovaBrowser(data.link);
            });
            break;
            case 'cusAction':
            $scope.OpportunitiesActionData.selectCustomer = callback.item;
            $scope.OpportunitiesActionData.selectCustomer.phone2 = callback.item.dataPhone;
            $scope.getOpportunitiesActionDataforCus($scope.OpportunitiesActionData.selectCustomer.id);
            // $scope.getAppointmentHistoryByCustomerId($scope.OpportunitiesActionData.selectCustomer.id);
            // $scope.getCustomerLogs($scope.OpportunitiesActionData.selectCustomer.phone);
            break;
            case 'referonaction':
            $scope.OpportunitiesActionData.selectCustomer.refferedcustomer = callback.item;
            break;
            case 'asgconverttofollow':
            $scope.OpportunitiesActionData.selectCustomer.assign = callback.item;
            break;
            case 'asgtask':
            $scope.formData.assign = callback.item;
            break;
            case 'follower':
            if ($scope.userFollow.indexOf(callback.item) < 0)
                $scope.userFollow.push(callback.item);
            break;
            case 'oppfiltercus':
            $scope.dataFilterOppotunities.customer = [callback.item];
            break;
            case 'oppfiltercity':
            $scope.dataFilterOppotunities.city.push(callback.item);
            break;
            case 'oppfilterzip':
            $scope.dataFilterOppotunities.zipcode.push(callback.item);
            break;
            case 'oppfilterphone':
            $scope.dataFilterOppotunities.objphone = callback.item;
            break;
            case 'oppfilterleadsource':
            $scope.dataFilterOppotunities.leadsource.push(callback.item);
            break;
            case 'oppfilterrep':
            $scope.dataFilterOppotunities.rep.push(callback.item);
            break;
            case 'oppfilterassignee':
            $scope.dataFilterOppotunities.assignee.push(callback.item);
            break;
        }
    }

    $scope.removeItemsAutocomplete = function (callback, type) {
        switch (type) {
            case 'cus':
            $scope.addOpportunitiesData.selectCustomer = [];
            $scope.autocompleteViewCustomer = '';
            break;
            case 'ref':
            $scope.autocompleteList.dataCustomerRefer = [];
            break;
            case 'asg':
            $scope.dataFollowUpUpdate.assign = [];
            break;
            case 'order':
            $scope.addAppointmentsData.order_id = [];
            break;
            case 'order':
            $scope.addOpportunitiesActionData.selectCustomer = [];
            break;
            case 'referonaction':
            $scope.OpportunitiesActionData.selectCustomer.refferedcustomer = [];
            break;
            case 'asgconverttofollow':
            $scope.OpportunitiesActionData.selectCustomer.assign = [];
            break;
            case 'asgtask':
            var index = $scope.formData.assign.indexOf(callback.item);
            $scope.formData.assign.splice(index, 1);
            break;
            case 'follower':
            var index = $scope.userFollow.indexOf(callback.item);
            $scope.userFollow.splice(index, 1);
            break;
            case 'oppfiltercus':
            $scope.dataFilterOppotunities.customer = [];
            break;
            case 'oppfiltercity':
            var index = $scope.dataFilterOppotunities.city.indexOf(callback.item);
            $scope.dataFilterOppotunities.city.splice(index, 1);
            break;
            case 'oppfilterzip':
            var index = $scope.dataFilterOppotunities.zipcode.indexOf(callback.item);
            $scope.dataFilterOppotunities.zipcode.splice(index, 1);
            break;
            case 'oppfilterphone':
            $scope.dataFilterOppotunities.objphone = {};
            break;
            case 'oppfilterleadsource':
            var index = $scope.dataFilterOppotunities.leadsource.indexOf(callback.item);
            $scope.dataFilterOppotunities.leadsource.splice(index, 1);
            break;
            case 'oppfilterrep':
            var index = $scope.dataFilterOppotunities.rep.indexOf(callback.item);
            $scope.dataFilterOppotunities.rep.splice(index, 1);
            break;
            case 'oppfilterassignee':
            var index = $scope.dataFilterOppotunities.assignee.indexOf(callback.item);
            $scope.dataFilterOppotunities.assignee.splice(index, 1);
            break;
        }
    }

    $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.setValueForSelectTitleInRootDataById = function (id, type) {
        switch (type) {
            case 'subheadingfollowup':
            var item = _.where($scope.followUpSubtabNoMyFollow, {id: id});
            $('input[name=subHeadingNameOnFollowUpSelect]').val(item[0].name);
            break;
        }
    };

    $scope.validateForm = function (formValidate, style) {
        // $ionicLoading.show({
        //     template: templateLoading
        // });
        var exitLoop = false;
        if (formValidate.$invalid) {
            $ionicScrollDelegate.$getByHandle('scroll' + style).scrollTop();
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            // console.log(formValidate.$error.required[0].$name);
            // angular.forEach(formValidate.$error, function(item) {
            //     if (!exitLoop) {
            //         var id = item[0].$name;
            //         // console.log(id);
            //         $location.hash(id); //set the location hash
            //         var handle = $ionicScrollDelegate.$getByHandle('popup' + style);
            //         handle.anchorScroll(true);
            //         exitLoop = true;
            //         $timeout(function() {
            //             // console.log(handle.getScrollPosition());
            //             var top = handle.getScrollPosition().top - 170;
            //             // console.log(top);
            //             handle.scrollTo(0, top, true);
            //             $ionicLoading.hide();
            //             //$cordovaToast.showLongTop('Please fill all the required information.!!!');
            //         }, 1000);
            //     }
            // })
            return;
        }
        ;
        switch (style) {
            case 'Add':
            $scope.createOpportunities();
            break;
            case 'UpdateFollow':
            if (!$scope.dataFollowUpUpdate.assign || $scope.dataFollowUpUpdate.assign.length == 0) {
                $cordovaToast.showLongTop('Please fill all the required information.!!!');
                return;
            }
            $scope.followUpUpdate();
            break;
            case 'UpdateFollowToFail':
            $scope.convertToFail();
            break;
            case 'OppotunitiesAction':
            $scope.openPopupSpecific_Information()
            break;
            case 'ConvertToFollowUp':
            if (!$scope.OpportunitiesActionData.selectCustomer.assign || !$scope.OpportunitiesActionData.selectCustomer || $scope.OpportunitiesActionData.selectCustomer.assign.length == 0) {
                $cordovaToast.showLongTop('Please fill all the required information.!!!');
                return;
            }
            $scope.convertToFollowUp();
            break;
            case 'ConvertToFailOther':
            $scope.convertToFailOther();
            break;
            case 'OppAddTask':
            $scope.beforeCreateTask();
            break;
        }

    }
    $scope.initialSearchCustomer = [];
    $scope.setValueForInputSearchCustomer = function (modelValue) {
        return [];
    };
    $scope.initialOpportunityForSearch = [];
    $scope.setValueForInputSearchOpp = function (modelValue) {
        return [];
    };
    $scope.initialSearchCustomerOppFilter = [];
    $scope.setValueForInputSearchCustomerOppFilter = function (modelValue) {
        for (var i = 0; i < $scope.rootDataCustomer.length; i++) {
            if ($scope.rootDataCustomer[i].id == modelValue) {
                return $scope.rootDataCustomer[i];
            }
        }
        return {};
    };
    $scope.initialSearchCustomerOppFilterCity = [];
    $scope.setValueForInputSearchCustomerOppFilterCity = function (modelValue) {
        for (var i = 0; i < $scope.dataFilterCity.length; i++) {
            if ($scope.dataFilterCity[i].city == modelValue) {
                return $scope.dataFilterCity[i];
            }
        }
        return {};
    };
    $scope.initialSearchCustomerOppFilterZip = [];
    $scope.setValueForInputSearchCustomerOppFilterZip = function (modelValue) {
        for (var i = 0; i < $scope.dataFilterZipcodeDetail.length; i++) {
            if ($scope.dataFilterZipcodeDetail[i].postal_code == modelValue) {
                return $scope.dataFilterZipcodeDetail[i];
            }
        }
        return {};
    };
    $scope.initialSearchCustomerOppFilterPhone = [];
    $scope.setValueForInputSearchCustomerOppFilterPhone = function (modelValue) {
        for (var i = 0; i < $scope.phoneResultDataFilter.length; i++) {
            if ($scope.phoneResultDataFilter[i].phone == modelValue) {
                return $scope.phoneResultDataFilter[i];
            }
        }
        return {};
    };
    $scope.initialSearchCustomerOppFilterLeadsource = [];
    $scope.setValueForInputSearchCustomerOppFilterLeadsource = function (modelValue) {
        for (var i = 0; i < $scope.dataFilterLeadsource.length; i++) {
            if ($scope.dataFilterLeadsource[i].key == modelValue) {
                return $scope.dataFilterLeadsource[i];
            }
        }
        return {};
    };
    $scope.initialSearchCustomerOppFilterRep = [];
    $scope.setValueForInputSearchCustomerOppFilterRep = function (modelValue) {
        for (var i = 0; i < $scope.dataOfficeEmployeee.length; i++) {
            if ($scope.dataOfficeEmployeee[i].id == modelValue) {
                return $scope.dataOfficeEmployeee[i];
            }
        }
        return {};
    };
    $scope.initialSearchCustomerOppFilterAssignee = [];
    $scope.setValueForInputSearchCustomerOppFilterAssignee = function (modelValue) {
        for (var i = 0; i < $scope.dataOfficeAssignee.length; i++) {
            if ($scope.dataOfficeAssignee[i].id == modelValue) {
                return $scope.dataOfficeAssignee[i];
            }
        }
        return {};
    };
    $scope.setValueForInputAssignItemEdit = function (modelValue) {
        for (var i = 0; i < $scope.rootUserAssign.length; i++) {
            if ($scope.rootUserAssign[i].id == modelValue) {
                return $scope.rootUserAssign[i];
            }
        }
        return {};
    };
    $scope.setValueForInputTaskFollower = function (modelValue) {
        for (var i = 0; i < $scope.allUser.length; i++) {
            if ($scope.allUser[i].id == modelValue) {
                return $scope.allUser[i];
            }
        }
        return {};
    };
    $scope.setValueForInputTaskAssgin = function (modelValue) {
        for (var i = 0; i < $scope.allUser.length; i++) {
            if ($scope.allUser[i].id == modelValue) {
                return $scope.allUser[i];
            }
        }
        return {};
    };

    $scope.countAllTab = function (type) {
        if ($scope.roleName != isAdmin)
            return;
        Opportunities.countAllTab().success(function (data) {
            $scope.totalItemspending = data.pending;
            for (var i = 0; i < $scope.followUpSubtabs.length; i++) {
                $scope.followUpSubtabs[i].totalitems = data.followup[i].totalitems;
            }
            for (var i = 0; i < $scope.failSubtabs.length; i++) {
                $scope.failSubtabs[i].totalitems = data.fail[i].totalitems;
            }
            for (var i = 0; i < $scope.otherSubtabs.length; i++) {
                $scope.otherSubtabs[i].totalitems = data.other[i].totalitems;
            }
            $scope.totalItemssuccess = data.success;
            switch (type) {
                case 'pending':
                $scope.pendingUpClick();
                break;
                case 'follow':
                $scope.subSabFollowContent($scope.currentFollowSubtabId, $scope.currentLocation);
                break;
            }
        });
    };

    $scope.fromFollowup = function () {
        $scope.fromFollowup = true;
    };
    $scope.redirectTo = function (url) {
        $ionicLoading.show({template: templateLoading});
        $timeout(function () {
            redirectTo(url);
        }, 1000)
    }
    $scope.showAppointmentHistoryDetail = [];
    $scope.checkAppointmentHistoryDetail = function (idx) {
        $scope.showAppointmentHistoryDetail[idx] = $scope.showAppointmentHistoryDetail[idx] == 1 ? 0 : 1;
        $ionicScrollDelegate.$getByHandle('scrollOppotunitiesAction').resize();

    }
    $scope.openAutocomplete = function (className) {
        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);
        setTimeout(function () {
            $scope.$apply(function (val) {
                $('.ion-autocomplete-search').focus();
            });
        }, 1);
    }
    $scope.selectedOther = function () {
        switch ($scope.roleName) {

            //saleman
            case $scope.isSalesman:
            return false;
            break;

            //fieldinstaller
            case $scope.isFieldinstaller:
            return false;
            break;

            //admin
            case $scope.isAdmin:
            return false;
            break;

            case $scope.isStrategicDevelopment:
            return false;
            break;

            //manager
            case $scope.isManager:
            return false;
            break;

            //isReporter
            case $scope.isReporter:
            $scope.dataConvertToFailOther.typeConvert == 'other';
            return true;
            break;

            //isScheduler
            case $scope.isScheduler:
            $scope.dataConvertToFailOther.typeConvert == 'other';
            return true;
            break;

            case $scope.isSupportAssistant:
            $scope.dataConvertToFailOther.typeConvert == 'other';
            return true;
            break;
            case $scope.isOutsideSales:
            $scope.dataConvertToFailOther.typeConvert == 'other';
            return true;
            break;

        }

    }
    // if ((window.location.pathname).substring((window.location.pathname).lastIndexOf('/') + 1) == 'opportunities.html') {
    //     $scope.limitLoad = true;
    //     $scope.$on('$includeContentLoaded', function() {
    //         if ($scope.limitLoad) {
    //             $scope.checkLogin();
    //             $scope.limitLoad = false;
    //             stopTime = $interval($scope.checkLogin, time_refresh);
    //         }
    //     });
    // }

    $scope.scrollHandle = function (positionID, delegate) {
        // if (positionID=='Info'){
        //     $ionicScrollDelegate.$getByHandle(delegate).scrollTop();
        // }else{
        //     $ionicScrollDelegate.$getByHandle(delegate).scrollBottom();
        // }
        // $location.hash(positionID); //set the location hash
        // var handle = $ionicScrollDelegate.$getByHandle(delegate);
        // handle.anchorScroll(true);
        // $timeout(function() {
        //     var top = handle.getScrollPosition().top - 30;
        //     // console.log(top);
        //     handle.scrollTo(0, top, false);
        // }, 500);
    }
    $scope.openActionSheet = function (type) {
        $scope.uploadType = type;
        var options = {
            // title: 'What do you want with this image?',
            buttonLabels: ['Video', 'Camera', 'Photo', 'File'],
            addCancelButtonWithLabel: 'Cancel',
            androidEnableCancelButton: true,
        };
        $cordovaActionSheet.show(options).then(function (index) {
            if (index == 2) {
                $scope.takePicture();
            } else if (index == 3) {
                $scope.openPicker();
            } else if (index == 4) {
                $scope.filePicker();
            } else if (index == 1) {
                $scope.recordVideo();
            }
        });
    }
    $scope.recordVideo = function () {
        // capture callback
        var captureSuccess = function (mediaFiles) {
            if ($scope.uploadType == "addComment") {
                $ionicLoading.show({
                    template: templateLoading
                });
                $scope.uploadAmazon(mediaFiles);
                return;
            }
            mediaFiles.forEach(function (itm) {
                $scope.files.push(itm);
            });
        };
        // capture error callback
        var captureError = function (error) {
            navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
        };

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

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

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

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

    $scope.filterClick = function ($query) {
        $scope.inputValue.query = 'New Queries';
        $scope.queryId = 'new';
        $scope.openByGetTemplate('popupOpportunityFilterReport');
        $scope.getEmployeeOfficeDepartment();

    };
    $scope.getEmployeeOfficeDepartment = function () {
        if ($scope.dataOfficeEmployeee.length > 0)
            return;
        Users.getEmployeeOfficeDepartment().success(function (data) {
            $scope.dataOfficeEmployeee = data;
            $scope.dataOfficeAssignee = data;
            $scope.getopportunityqueries();
        })
    };
    $scope.getopportunityqueries = function () {
        Opportunities.getOpportunityQueries().success(function (data) {
            _.each(data, function (item) {
                var rowContent = JSON.parse(item.content);
                if (rowContent.checkManualLeadSoure) {
                    rowContent.leadsource = rowContent.leadsourceOrgin;
                    return item.content = JSON.stringify(rowContent);
                }
            });
            $scope.dataOppQuery = data;
        })
    };
    var queryID;
    $scope.fillFilterData = function (id) {
        $scope.viewInpuntManualLead = false;
        $scope.initialSearchCustomerOppFilter = [];
        $scope.initialSearchCustomerOppFilterCity = [];
        $scope.initialSearchCustomerOppFilterZip = [];
        $scope.initialSearchCustomerOppFilterPhone = [];
        $scope.initialSearchCustomerOppFilterLeadsource = [];
        $scope.initialSearchCustomerOppFilterRep = [];
        $scope.initialSearchCustomerOppFilterAssignee = [];
        if (id == 'new') {
            $scope.inputValue.query = 'New Queries';
            $scope.dataFilterOppotunities.manualLeadSoure = [];
            $scope.viewInpuntManualLead = true;
        } else {
            $scope.viewInpuntManualLead = true;
            var item = _.where($scope.dataOppQuery, {id: id});
            $scope.inputValue.query = item[0].name;
            queryID = id;
        }
        if (parseInt(id) > 0) {
            $scope.queryById = _.where($scope.dataOppQuery, {id: id});
            $scope.dataParseJson = JSON.parse($scope.queryById[0].content);
            if ($scope.dataParseJson.customer && $scope.dataParseJson.customer.length > 0) {
                var params = {search: $scope.dataParseJson.customer[0].first_name};
                Customers.getSelect2(params).success(function (data) {
                    $scope.rootDataCustomer = data;
                    $scope.rootDataCustomer.forEach(function (item) {
                        item.fullName = item.first_name + ' ' + item.last_name + ' ' + item.street + ' ' + item.phone;
                    })
                    $scope.initialSearchCustomerOppFilter = [$scope.dataParseJson.customer[0].id];
                })
            }

            if ($scope.dataParseJson.phone) {
                var params = {search: $scope.dataParseJson.phone};
                Opportunities.getPhoneOpp(params).success(function (data) {
                    var diff = differentArray(data, $scope.dataFilterOppotunities.objphone);
                    $scope.phoneResultDataFilter = diff;
                    $scope.initialSearchCustomerOppFilterPhone = [$scope.dataParseJson.phone];
                })
            }
            var tempData = {
                city: $scope.dataParseJson.city,
                zipcode: $scope.dataParseJson.zipcode,
                leadsource: $scope.dataParseJson.leadsource,
                rep: $scope.dataParseJson.rep,
                assignee: $scope.dataParseJson.assignee
            }
            $scope.dataFilterOppotunities = $scope.dataParseJson;
            if( $scope.dataFilterOppotunities.addrress.length > 0){
                $scope.arrAddress = [{place_id:'place_id',description:$scope.dataFilterOppotunities.addrress}];
            }
            else{
                $scope.arrAddress = [];
            }
            $scope.dataFilterOppotunities.objphone = {id: '', name: $scope.dataFilterOppotunities.phone};
            $scope.dataFilterOppotunities.city = [];
            $scope.dataFilterOppotunities.zipcode = [];
            $scope.dataFilterOppotunities.leadsource = [];
            $scope.dataFilterOppotunities.rep = [];
            $scope.dataFilterOppotunities.assignee = [];

            $scope.initialSearchCustomerOppFilterCity = _.pluck(tempData.city, 'city');
            $scope.initialSearchCustomerOppFilterZip = _.pluck(tempData.zipcode, 'postal_code');
            $scope.initialSearchCustomerOppFilterLeadsource = _.pluck(tempData.leadsource, 'key');
            $scope.initialSearchCustomerOppFilterRep = _.pluck(tempData.rep, 'id');
            $scope.initialSearchCustomerOppFilterAssignee = _.pluck(tempData.assignee, 'id');
            $scope.filter_from_date = $scope.dataParseJson.starttime;
            $scope.filter_to_date = $scope.dataParseJson.endtime;
            $scope.setValueForSubStatus($scope.dataParseJson.status.toString());
            $scope.setInputValueForSubStatus($scope.dataParseJson.subStatus.toString());
            if ($scope.dataFilterOppotunities.manualLeadSoure != undefined) {
                $scope.viewInpuntManualLead = true;
            } else {
                $scope.viewInpuntManualLead = false;
            }

        } else {
            $scope.queryId = id;
            $scope.dataFilterOppotunities = {};
            $scope.dataFilterOppotunities.status = 'All';
            $scope.dataFilterOppotunities.subStatus = 'All';
            $scope.inputValue.filterStatus = 'All';
            $scope.inputValue.filterSubStatus = 'All';
            $scope.dataFilterOppotunities.customer = [];
            $scope.dataFilterOppotunities.objphone = [];
            $scope.dataFilterOppotunities.city = [];
            $scope.dataFilterOppotunities.zipcode = [];
            $scope.dataFilterOppotunities.leadsource = [];
            $scope.dataFilterOppotunities.rep = [];
            $scope.dataFilterOppotunities.assignee = [];
            $scope.dataFilterOppotunities.searchByCreateDay = false;
            $scope.initialSearchCustomerOppFilter = [];
            $scope.initialSearchCustomerOppFilterCity = [];
            $scope.initialSearchCustomerOppFilterZip = [];
            $scope.initialSearchCustomerOppFilterLeadsource = [];
            $scope.initialSearchCustomerOppFilterRep = [];
            $scope.initialSearchCustomerOppFilterAssignee = [];
            initialSearchCustomerOppFilterPhone = [];
            $scope.filter_from_date = moment().add(-30, 'days').format('MM/DD/YYYY');
            $scope.filter_to_date = moment().format('MM/DD/YYYY');
        }
    };
    $scope.beforeSaveQuery = function () {
        var myPopup = $ionicPopup.show({
            template: '<input type = "text" ng-model="dataFilterOppotunities.queryname">',
            title: 'Save Query',
            subTitle: 'Please input the name of the saved query:',
            scope: $scope,
            buttons: [
            {text: 'Cancel'}, {
                text: '<b>Save</b>',
                type: 'button-positive',
                onTap: function (e) {
                    if (!$scope.dataFilterOppotunities.queryname) {
                        e.preventDefault();
                    } else {
                        $scope.filterOppotunities('Save');
                    }
                }
            }
            ]
        });
    };

    $scope.setvalManualLead = function (data) {
        //$scope.dataFilterOppotunities.manualLeadSoure = [{value:"dmvcl"}];

        $timeout(function () {
            $scope.dataFilterOppotunities.manualLeadSoure = data;
        }, 5000);
    };
    $scope.currentPageOppFilter = 1;
    $scope.itemsPerPageOppFilter = 50;
    $scope.filterOppotunities = function (action) {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.dataFilterOppotunities.actionType = action;
        if ($scope.dataFilterOppotunities.actionType == 'Delete') {
            $scope.dataFilterOppotunities = {};
            $scope.dataFilterOppotunities.actionType = 'Delete';
            $scope.dataFilterOppotunities.queryId = queryID;
        } else {
            if ($scope.dataFilterOppotunities.manualLeadSoure && $scope.dataFilterOppotunities.checkManualLeadSoure) {
                $scope.dataFilterOppotunities.leadsourceSum = [];
                $scope.dataFilterOppotunities.leadsourceOrgin = $scope.dataFilterOppotunities.leadsource;
                _.each($scope.dataFilterOppotunities.leadsource, function (item) {
                    $scope.dataFilterOppotunities.leadsourceSum.push(item);
                });
                _.each($scope.dataFilterOppotunities.manualLeadSoure, function (item) {
                    $scope.dataFilterOppotunities.leadsourceSum.push({key: item.value});
                });
                $scope.dataFilterOppotunities.leadsource = $scope.dataFilterOppotunities.leadsourceSum;
            }
            $scope.dataFilterOppotunities.starttime = $('#filter_from_date').val();
            $scope.dataFilterOppotunities.endtime = $('#filter_to_date').val();
            $scope.dataFilterOppotunities.starttimeFomat = moment($scope.dataFilterOppotunities.starttime, 'MM/DD/YYYY').format('YYYY-MM-DD');
            $scope.dataFilterOppotunities.endtimeFomat = moment($scope.dataFilterOppotunities.endtime, 'MM/DD/YYYY').format('YYYY-MM-DD');
            $scope.dataFilterOppotunities.addrress = $scope.dataFilterOppotunities.addrress ? $scope.dataFilterOppotunities.addrress : "";
            $scope.dataFilterOppotunities.searchByCreateDay = $scope.dataFilterOppotunities.searchByCreateDay ? $scope.dataFilterOppotunities.searchByCreateDay : false;
            $scope.dataFilterOppotunities.phone = '';
            if ($scope.dataFilterOppotunities.objphone.name) {
                $scope.dataFilterOppotunities.phone = $scope.dataFilterOppotunities.objphone.name;
            }
            if ($scope.dataFilterOppotunities.status != 'All') {
                if ($scope.dataFilterOppotunities.status == '1' || $scope.dataFilterOppotunities.status == '10') {
                    $scope.statusById = _.where($scope.opportunitytabs, {id: $scope.dataFilterOppotunities.status});
                    $scope.dataFilterOppotunities.statusShow = $scope.statusById[0].name;
                    $scope.dataFilterOppotunities.subStatusShow = '';
                } else {
                    $scope.statusById = _.where($scope.opportunitytabs, {id: $scope.dataFilterOppotunities.status});
                    $scope.dataFilterOppotunities.statusShow = $scope.statusById[0].name;
                    if ($scope.dataFilterOppotunities.subStatus != 'All') {
                        $scope.statusByIdParent = _.where($scope.opportunitytabs, {id: $scope.dataFilterOppotunities.subStatus});
                        $scope.dataFilterOppotunities.subStatusShow = $scope.statusByIdParent[0].name;
                    } else {
                        $scope.dataFilterOppotunities.subStatusShow = 'All';
                    }
                }
            } else {
                $scope.dataFilterOppotunities.statusShow = 'All';
                $scope.dataFilterOppotunities.subStatusShow = 'All';
            }
        }
        $scope.dataFilterOppotunities.rows = $scope.itemsPerPageOppFilter;
        $scope.dataFilterOppotunities.current_page = 1;
        Opportunities.filter($scope.dataFilterOppotunities).success(function (data) {
            if(data.status == false){
                $cordovaToast.showLongCenter(data.msg);
            }
            else{
                $ionicLoading.hide();
                switch (action) {
                    case 'Display':
                    $scope.closeTarget('#popupOpportunityFilterReport');
                    $scope.dataOppFilter = data.data;
                    $scope.totalItemsOppfilter = data.total_rows;
                    $scope.currentPageOppFilter = data.page;
                    if ($scope.currentPageOppFilter == 1) {
                        $scope.openByGetTemplate('popupOpportunityFilterReportDisplay')
                    }
                    if (data.data.length == $scope.itemsPerPageOppFilter) {
                        $timeout(function () {
                            $scope.checkLoadMoreDisplayFilter = true;
                        }, 2000);
                    }
                    break;
                    case 'Export':
                    $scope.cordovaBrowser(data.link);
                    break;
                    case 'Save':
                    $scope.inputValue.query = 'New Queries';
                    $scope.queryId = 'new';
                    // $scope.openByGetTemplate('popupOpportunityFilterReport');
                    $scope.closeTarget('#popupOpportunityFilterReport');
                    $scope.getopportunityqueries();
                    $cordovaToast.showLongTop(data.msg);
                    break;
                    case 'Delete':
                    $scope.inputValue.query = 'New Queries';
                    $scope.queryId = 'new';
                    $scope.openByGetTemplate('popupOpportunityFilterReport');
                    $scope.getopportunityqueries();
                    $cordovaToast.showLongTop(data.msg);
                    break;
                }
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    };
    $scope.LoadMoreDisplayFilter = function () {
        if (!$scope.checkLoadMoreDisplayFilter)
            return;
        $scope.dataFilterOppotunities.current_page++;
        Opportunities.filter($scope.dataFilterOppotunities).success(function (data) {
            _.each(data.data, function (item) {
                $scope.dataOppFilter.push(item);
            })
            $scope.checkLoadMoreDisplayFilter = $scope.checkLoadMoreVal(data.data.length, $scope.itemsPerPageOppFilter);
            $timeout(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 2000);
        });
    }
    $scope.addressPress = function (location) {
        $scope.cityvar = location['locality'];
        $scope.statevar = location['administrative_area_level_1'];
        $scope.tempCity = {"city": $scope.cityvar, "state": $scope.statevar, "city_state": $scope.cityvar + ' , ' + $scope.statevar};
        $scope.dataFilterOppotunities.city = [];
        $scope.dataFilterOppotunities.city.push($scope.tempCity);
        // var idx = $scope.dataFilterOppotunities.city.indexOf($scope.tempCity);
        // console.log(idx);
        // if (idx < 0) {
        //     $scope.initialSearchCustomerOppFilterCity=[];
        //     $scope.dataFilterOppotunities.city.push($scope.tempCity);
        //     $scope.initialSearchCustomerOppFilterCity=_.pluck($scope.dataFilterOppotunities.city, 'city');
        // }
        $scope.postcodevar = "";
        if (location['postal_code'])
            $scope.postcodevar = location['postal_code'];
        $scope.tempZip = {"postal_code": $scope.postcodevar};
        $scope.dataFilterOppotunities.zipcode = [];
        $scope.dataFilterOppotunities.zipcode.push($scope.tempZip);
    }
    $scope.setValueForSubStatus = function (value) {
        if (value == "All") {
            $scope.inputValue.filterStatus = "All";
        } else {
            $scope.inputValue.filterStatus = _.where($scope.opportunitytabs, {id: value})[0].name;
        }
        if (value == 'All') {
            $scope.dataFilterOppotunities.subStatus = value;
        }
        $ionicScrollDelegate.$getByHandle('scrollFilter').resize();
    };
    $scope.setInputValueForSubStatus = function (value) {
        if (value == "All") {
            $scope.inputValue.filterSubStatus = "All";

        } else {
            $scope.inputValue.filterSubStatus = _.where($scope.opportunitytabs, {id: value})[0].name;

        }
    }
    $scope.checkNumber = true;
    $scope.inputPhoneNumber = function (phone) {
        if (!$scope.checkNumber) {
            return;
        }
        if (!parseInt($scope.addOpportunitiesData.selectCustomer.id) > 0) {
            var phoneString = $('#selectCustomerPhone').val();
            var afterPhone = phoneString.replace('(', '').replace(')', '').replace('-', '').replace(' ', '').replace(' ', '');
            if (afterPhone.length == 10) {
                $scope.checkNumber = false;
                $timeout(function () {
                    Opportunities.chechInputPhone({number: afterPhone}).success(function (data) {
                        $scope.checkNumber = true;
                        if (data.status) {
                            $('#selectCustomerPhone').val('');
                            $scope.addOpportunitiesData.selectCustomer.phone = "";
                            $scope.dataOppHtml.titlePopup = "WARNING!!!";
                            $scope.dataOppHtml.contentPopup = "This phone number already exists, please use the search bar to confirm customer!";
                            $scope.showTarget("#popupAlertCheckPhonePrimary");
                        }
                    })
                }, 500);
            }
        }
    }
    var click = 0;
    $scope.oppFilterClick = function (data) {
        click++;
        $timeout(function () {
            click = 0;
        }, 500);
        if (click < 2)
            return;
        if (data.tabName == 'Follow-Up') {
            $scope.openTabFollowup(data);
        } else if (data.tabName == 'Pending') {
            $scope.getItemPenddingId(data.id, data.dst);
        } else {
            if (data.tabName == 'Success') {
                $scope.scheckSuccessClicked = false;
                $scope.SuccessClick(data.id)
            }
            if (data.tabName == 'Fail') {
                $scope.failClick(data.id, data.opportunitytab_id)
            }
            if (data.tabName == 'Other') {
                $scope.otherClick('', data.id, data.opportunitytab_id)
            }
            if (data.tabName == null || data.tabName == '0' || data.tabName == '') {
                if (data.direction == 'Incoming') {
                    $scope.callListClick(data.id, '23')
                }
                if (data.direction == 'Outcoming') {
                    $scope.callListClick(data.id, '24')
                }
                if (data.direction == 'Missed') {
                    $scope.callListClick(data.id, '25')
                }
            }






            //$scope.failClick
            //$scope.failClick(callback.item.id,tabid+'');
        }
    }
    $scope.openTabFollowup = function (data) {
        $ionicLoading.show({template: templateLoading});
        Opportunities.getFollowUpSubtab().success(function (result) {
            $ionicLoading.hide();
            $scope.followUpSubtabs = result.data;
            $scope.followUpSubtabNoMyFollow = result.subtabnofollowup;
            $scope.getItemFollowUpId(data.id, 'openForm');
        });
    }
    $scope.audioInformation = {};
    $scope.initPlayAudio = function (row) {
        $scope.audioInformation = row;
        var listTrack = [row.recordingfile];
        audioPlayerMultiTrack('#callRecordAudioArea', listTrack);
        $scope.showTarget('#popupCallRecord');
    }

    $scope.$on('getOppByPendingId', function (e, pendingIdParam) {
        $scope.pendingIdParam = pendingIdParam;
        $scope.checkGetOppByPendingId = true;
        $scope.getItemPending($scope.pendingIdParam);
        $scope.pendingClicked();
    })

    $scope.redirectToDispathRoom = function () {
        redirectTo('chat.html?room_id=2&pendingId=' + $scope.pendingId + '#/board/chat')
    }

    $scope.manualLeadSoureClick = function (val) {
        $scope.viewInpuntManualLead = val;
    }

    $scope.saveCustomernote = function(customer){
        if($scope.OpportunitiesActionData.selectCustomer.note != $scope.orgCustomerNote && $scope.OpportunitiesActionData.selectCustomer.is_customer == true){
            $ionicLoading.show({template: templateLoading});
            Customers.edit_customer_note(customer.id,customer.note).success(function(data) {
                $ionicLoading.hide();
                if (data.status) {
                    $cordovaToast.showLongTop(data.msg);
                    $scope.closeTarget('#popupOpportunityChangeCustomerNote');
                }
            });
        }else{
            $scope.closeTarget('#popupOpportunityChangeCustomerNote');
        }
    }

    $scope.openFormChangeCustomerNote = function(){
        $scope.orgCustomerNote = $scope.OpportunitiesActionData.selectCustomer.note;
        $scope.openByGetTemplate('popupOpportunityChangeCustomerNote');
    }


    $scope.closeFormChangeCustomerNote = function(){
        $scope.OpportunitiesActionData.selectCustomer.note = $scope.orgCustomerNote ;
        $scope.closeTarget('#popupOpportunityChangeCustomerNote');
    }

    $scope.openPopupAppNote = function(dataOfficeNote,dataFieldWorkerNote){
        $timeout(function(val) {
            $scope.openByGetTemplate('opptunityViewAppoimentNote');
            $scope.AppointmentNoteData.office = dataOfficeNote;
            $scope.AppointmentNoteData.fieldworker = dataFieldWorkerNote;
        }, 10);
    }

    $scope.openAppointmentDetail = function(id){
        $scope.paramsToApp = {};
        $scope.paramsToApp.id = id;
        $scope.$broadcast('openAppDetailFromMap',$scope.paramsToApp);
        $scope.openPopupAppointmentDetail=true;
    }

    $scope.openPopupNote = function(data){
        $scope.recordTypeNote=data;
        $scope.openByGetTemplate('opptunityViewNoteOfRecord');
    }

    $scope.OpenOpportunitiesFollowUp = function(data){
        if ($scope.check_action_followup){
            if(data.oppt_id){
                $scope.opptId_isActionForm=data.oppt_id;
            }
            else{
                $scope.opptId_isActionForm=$scope.FilterOpportunitiesData.id;
            }
        }   
        $scope.getItemFollowUpId(data.id);
        $scope.openByGetTemplate('opportunityFollowUpFollowUp');
        $scope.FollowUpInPending=true;
    }

    $scope.openOpportunitiesAction = function(data){
        $scope.getItemPenddingId(data.id);
    }


    $scope.formatForExtendPrice = function(price){
        if(price<0){
            return '- $'+Math.abs(price).toString();
        }
        else{
            return '$'+price.toString();
        }
    }

    $scope.checkAdditionalPhoneCustomer = function(){
        if($scope.selectCustomer){
            var customerId = $scope.OpportunitiesActionData.selectCustomer.id;
        }else{
            var customerId = 0;
        }
        var customerAdditionalPhones = $scope.OpportunitiesActionData.selectCustomer.phone2;

        if(customerAdditionalPhones && customerAdditionalPhones.length){
            var checkDuplicate = $scope.checkDuplicatePhone(customerAdditionalPhones);
            if(checkDuplicate){
                $cordovaToast.showLongTop('Additional Phone Number Duplicate !');
                return;
            }
        }

        if(customerAdditionalPhones.length > 0 && customerAdditionalPhones[0].phone != ''){
            Customers.checkAdditionalPhone(customerId,customerAdditionalPhones).success(function(result){
                if(result.status == false){
                    $cordovaToast.showLongTop(result.msg);
                }
                else{
                    if(result.data.length > 0){
                        $scope.listCustomersPhonesDup = result.data;
                        $scope.openByGetTemplate('popupCheckAdditionalPhones');
                    }else{
                        $scope.update_insert_customer_fromPending();
                    }
                }
            });
        }else{
          $scope.update_insert_customer_fromPending();
      }
  }

  $scope.checkDuplicatePhone = function(arrPhone) {
    var arr =  _.pluck(arrPhone, 'phone');
    return arr.length != _.uniq(arr).length;
};
$scope.setValBiginWatch = function(val) {
    $scope.$broadcast('beginScopeWatch',{value:val});
};
$scope.closeFornAction = function() {
    $scope.closeTarget('#popupOpportunityAction');
    if($scope.selectNewCus){
        $scope.scheckPendingClicked = false;
        $scope.pendingClicked();    
    }
};
$scope.$on('reciveLatestMessage',function(events,data){
    $scope.lastMessAndRoom.lastestMessage = data.content;
    $scope.lastMessAndRoom.sentFrom = _.where($scope.allUser, {id: data.from_user})[0].name;
    $scope.lastMessAndRoom.time = moment(data.time).format('MM/DD/YYYY h:mm:ss A');
});

$scope.warningAddPhoneNumber = function() {
    if(!$scope.is_customer){
    $scope.openByGetTemplate('popupWarningAddPhoneNumber');
    $scope.reset_is_customer = false;
}
};
$scope.acceptAddPhoneNumber = function() {
    $scope.OpportunitiesActionData.selectCustomer.phone2.push({phone:$scope.temp_phone});
};
$scope.selectAddress = function(value,type) {
    if(type == 'addopp'){
        if($scope.addOpportunitiesData.selectCustomer.addStreet && $scope.addOpportunitiesData.selectCustomer.addStreet.length>0){
         $scope.addOpportunitiesData.selectCustomer.addStreet.splice(0,1);
     }
 }
 if(type == 'oppaction'){
    if($scope.OpportunitiesActionData.selectCustomer.addStreet && $scope.OpportunitiesActionData.selectCustomer.addStreet.length>0){
        $scope.OpportunitiesActionData.selectCustomer.addStreet.splice(0,1);
    }
}
if(type == 'followup'){
    if($scope.dataFollowUpUpdate.addStreet && $scope.dataFollowUpUpdate.addStreet.length>0){
        $scope.dataFollowUpUpdate.addStreet.splice(0,1);
    }
}
if(type == 'filteropp'){
    if($scope.arrAddress && $scope.arrAddress.length>0){
        $scope.arrAddress.splice(0,1);
    }
}
$scope.valueClone = value;
var data = [];
var componentAddressForm = {
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    postal_code: 'short_name'
};
LocationService.getDetails(value.place_id).then(function(location) {
    $scope.valueClone.description = location.formatted_address;
    angular.forEach(location.address_components, function(item) {
        var addressType = item.types[0];
        if (componentAddressForm[addressType]) {
            var val = item[componentAddressForm[addressType]];
            data[addressType] = val;
        }
    })
    if(type == 'addopp'){
        data['locality'] ? $scope.addOpportunitiesData.selectCustomer.city = data['locality'] : $scope.addOpportunitiesData.selectCustomer.city = '';
        data['administrative_area_level_1'] ? $scope.addOpportunitiesData.selectCustomer.state = data['administrative_area_level_1'] : $scope.addOpportunitiesData.selectCustomer.state = '';
        data['postal_code'] ? $scope.addOpportunitiesData.selectCustomer.zipcode = data['postal_code'] : $scope.addOpportunitiesData.selectCustomer.zipcode = '' ;
        $scope.addOpportunitiesData.selectCustomer.street = location.formatted_address;
    }
    if(type == 'oppaction'){
        data['locality'] ? $scope.OpportunitiesActionData.selectCustomer.city = data['locality'] : $scope.OpportunitiesActionData.selectCustomer.city = '';
        data['administrative_area_level_1'] ? $scope.OpportunitiesActionData.selectCustomer.state = data['administrative_area_level_1'] : $scope.OpportunitiesActionData.selectCustomer.state = '';
        data['postal_code'] ? $scope.OpportunitiesActionData.selectCustomer.zipcode = data['postal_code'] : $scope.OpportunitiesActionData.selectCustomer.zipcode = '' ;
        $scope.OpportunitiesActionData.selectCustomer.street = location.formatted_address;
    }
    if(type == 'followup'){
        data['locality'] ? $scope.dataFollowUpUpdate.city = data['locality'] : $scope.dataFollowUpUpdate.city = '';
        data['administrative_area_level_1'] ? $scope.dataFollowUpUpdate.state = data['administrative_area_level_1'] : $scope.dataFollowUpUpdate.state = '';
        data['postal_code'] ? $scope.dataFollowUpUpdate.zipcode = data['postal_code'] : $scope.dataFollowUpUpdate.zipcode = '' ;
        $scope.dataFollowUpUpdate.street = location.formatted_address;
    }
    if(type == 'filteropp'){
        $scope.dataFilterOppotunities.addrress = location.formatted_address;
    }
})
};
$scope.removetag = function(value,type) {
    if(type == 'addopp'){
        $scope.addOpportunitiesData.selectCustomer.city = '';
        $scope.addOpportunitiesData.selectCustomer.state = '';
        $scope.addOpportunitiesData.selectCustomer.zipcode = '';
        $scope.addOpportunitiesData.selectCustomer.street = '';
        $scope.addOpportunitiesData.selectCustomer.addStreet = [];
    }
    if(type == 'oppaction'){
        $scope.OpportunitiesActionData.selectCustomer.city = '';
        $scope.OpportunitiesActionData.selectCustomer.state = '';
        $scope.OpportunitiesActionData.selectCustomer.zipcode = '';
        $scope.OpportunitiesActionData.selectCustomer.street = '';
        $scope.OpportunitiesActionData.selectCustomer.addStreet = [];
    }
    if(type == 'followup'){
        $scope.dataFollowUpUpdate.city = '';
        $scope.dataFollowUpUpdate.state = '';
        $scope.dataFollowUpUpdate.zipcode = '';
        $scope.dataFollowUpUpdate.street = '';
        $scope.dataFollowUpUpdate.addStreet = [];
    }
    if(type == 'filteropp'){
        $scope.dataFilterOppotunities.addrress = '';
        $scope.arrAddress = [];
    }
};

$scope.$on('getJsonFromSchedule', function (event, data) {
    var jsondata = data.data;
    var index = _.findIndex(jsondata,{roletree_id:'43'});
    if(jsondata[index].check){
        $scope.buttonAddOpportunity =    jsondata[index].child[0].check;
        $scope.clickToCall =             jsondata[index].child[1].check;
        $scope.fieldSearchOpp =          jsondata[index].child[2].check;
        $scope.canAssignFollowUp =       jsondata[index].child[3].check;
        $scope.showFilterOpp =           jsondata[index].child[4].check;
        $scope.showImportOpp =           jsondata[index].child[5].check;
        $scope.opportunityAction =       jsondata[index].child[6].check;
        $scope.convertAppointment =      jsondata[index].child[6].child[0].check;
        $scope.addTaskButton =           jsondata[index].child[6].child[1].check;
        $scope.convertToFailButton =     jsondata[index].child[6].child[2].check;
        $scope.convertToOtherButton =    jsondata[index].child[6].child[3].check;
        $scope.convertFollowButton =     jsondata[index].child[6].child[4].check;
        $scope.transferCallButton =      jsondata[index].child[6].child[5].check;
        $scope.sendDispathButton =       jsondata[index].child[6].child[6].check;
        if(!$scope.convertToFailButton && !$scope.convertToOtherButton){
            $scope.convertToFailOtherButton = true;
        }else if(!$scope.convertToFailButton && $scope.convertToOtherButton){
            $scope.dataConvertToFailOther.typeConvert = 'other';
        }else if($scope.convertToFailButton && !$scope.convertToOtherButton){
            $scope.dataConvertToFailOther.typeConvert = 'fail';
        }else{
            $scope.convertToFailOtherButton = false;
        }
        $scope.FollowUpdateBut =        jsondata[index].child[7].check;
        $scope.updateFollowUpBut =      jsondata[index].child[7].child[0].check;
        $scope.convertToFailButton2 =   jsondata[index].child[7].child[1].check;
        $scope.convertAppFromFollowup = jsondata[index].child[7].child[2].check;
    }else{
        localStorage.setItem("login_status", "0");
        redirectTo('index.html');
    }
})
if (page == "opportunities.html") {
    Login.checkLogin().success(function (data) {
        $scope.currentExt = data.status.extension_phone;
        $scope.currentIdLogin = parseInt(data.status.id);
    });
    $scope.renderTemplateData();
}

if (parseInt(getParameterByName('pendingId'))) {
    $scope.getItemPending(getParameterByName('pendingId'));
}
})
