var customers_pagesize = $('#customers_pagesize');
angular.module('customerController', []).controller('customerCtrl', function ($ionicPopup, $scope, $http, $ionicLoading, //
        $timeout, $cordovaToast, $location, $window, $interval, $filter, Customeraddresses, Login, Leadsources, $cordovaKeyboard, //
        $ionicScrollDelegate, Reviews, Customers, Customertypes, Leadsources, Users, Flags, dataHtml, $state, $stateParams, Customereviews, //\
        Reviews, $sce, Jobsites, ivhTreeviewMgr,LocationService) { //
// edit by ToanLam
// searchUserHandle();

// function searchUserHandle() {
//     toggleDelegateHandle('#customer_page', '.link-customer-search', '.customer-search');
//     toggleDelegateHandle('#customer_page', '.customer-search .search-type .btn-close', '.customer-search');
//     toggleDelegateHandle('#customer_page', '.customer-search .search-content .btn-close', '.customer-search');
//     closeOutsideHandle('.link-customer-search, .customer-search', '.customer-search');
// }
// filterChatHandle();
function filterChatHandle() {
    toggleDelegateHandle('#customer_page', '.link-employee-filter', '.employee-filter');
    closeOutsideHandle('.link-employee-filter, .employee-filter', '.employee-filter');
}

$scope.search = {};
$scope.clearSearch = function () {
    $scope.searchCustomers.search = '';
    $scope.getCustomers();
}
$scope.itemEmployeeHandle = function (e) {
    $(e.currentTarget).toggleClass('selected').siblings().removeClass('selected');
    $(e.currentTarget).find('> .info-more').stop(true, true).slideDown(0).closest('.itm-employee').siblings().find('> .info-more').stop(true, true).slideUp(0);
}
// end editCustomers
$ionicLoading.show({
    template: templateLoading
});
withoutPopup = $scope;
$scope.backPage = 'customers';
$scope.currentPage = 1;
$scope.loaded = 0;
var pager = '50';
$scope.itemsPerPage = pager ? pager : 50;
$scope.entryLimit = $scope.itemsPerPage;
$scope.searchCustomers = {
    rows: $scope.itemsPerPage,
    current_page: $scope.currentPage,
    search: "",
    showCustomer: 'active'

};
$scope.currentIdLogin = currentIdLogin;
$scope.coundown = 10;
$scope.myTime = null;
$scope.employeeReview = {};
$scope.employeeReviewEdit = {};
$scope.readonly = "true";
//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;
// sinh dang
$scope.fdate = conFig.formatDate;
$scope.onMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(andRoid)|(Linux)|(webOS)/i) != null;
// something
$scope.addCustomersData = {};
$scope.addCustomersData.street = [];
$scope.editCustomersData = {};
$scope.deleteCustomersData = {};
$scope.addCustomersData.refferedcustomer = [];
$scope.editCustomersData.refferedcustomer = [];
/**filter area**/
$scope.addresschecked = [];
$scope.fieldworkderchecked = [];
$scope.servicedatechecked = [];
$scope.isbuildtree = false;
$scope.checkaddress = false;
$scope.checkservicedate = false;
$scope.checkfieldworker = false;
$scope.isFilterCusomer=false;
$scope.sortby = '';
$scope.Input_value = {};
$scope.autocompleteList = {};
$scope.autocompleteList.refferedcustomerAdd = [];
$scope.autocompleteList.refferedcustomerEdit = [];
$scope.autocompleteList.refferedEmployeeAdd = [];
$scope.autocompleteList.refferedEmployeeEdit = [];
$scope.autocompleteList.customerReviewCustomerAdd = [];
$scope.autocompleteList.customerReviewCustomerEdit = [];
$scope.autocompleteList.customerReviewEmployeeAdd = [];
$scope.autocompleteList.customerReviewEmployeeEdit = [];
$scope.dataViewAppNote = {};
$scope.dataHtml = {};
$scope.dataAppHtml = {};
$scope.inDetail = false;
$scope.customerDetail = {};
$scope.dataHtml.showCustomer = 0;
$scope.reviewFilter = {};
$scope.dataFilterCity = JSON.parse(dataCityFilter);
$scope.dataFilterZipcode = JSON.parse(zipcodeFilter);
$scope.dataFilterZipcodeDetail = [];
$scope.arrPoscode = [];
$scope.customerShow = 'Active';
$scope.autocompleteListData = {};
$scope.autocompleteListData.fieldworker = [];
$scope.autocompleteListData.appointmentType = [];
$scope.continueFilter = true;

$scope.backToAppId = parseInt($stateParams.param);

_.each($scope.dataFilterZipcode, function (row) {
    if ($scope.arrPoscode.indexOf(row.postal_code) < 0) {
        $scope.arrPoscode.push(row.postal_code);
        $scope.dataFilterZipcodeDetail.push(row);
    }
});
$scope.addCustomersData.addStreet = [];
$scope.deleleEmail = '';
$scope.indexEmailDelete = -1;
$scope.delelePhone = '';
$scope.indexPhoneDelete = -1;
$scope.tableJobsiter = {};
$scope.dataEditJobsite = {};
$scope.searchCustomerJobsite = {};
$scope.searchCustomerJobsite.show = 'active';
$scope.customerJobsiteShow = 'Active';
$scope.monthNames = [{
    name: 'January',
    value: 1
}, {
    name: 'February',
    value: 2
}, {
    name: 'March',
    value: 3
}, {
    name: 'April',
    value: 4
}, {
    name: 'May',
    value: 5
}, {
    name: 'June',
    value: 6
}, {
    name: 'July',
    value: 7
}, {
    name: 'August',
    value: 8
}, {
    name: 'September',
    value: 9
}, {
    name: 'October',
    value: 10
}, {
    name: 'November',
    value: 11
}, {
    name: 'December',
    value: 12
}];

$scope.accept_this_card_add = false;
$scope.accept_this_card_edit = false;

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

    $scope.getCustomertypes = function () {
        Customertypes.getSelect().success(function (data) {
            $scope.customertypes = data.customer_relation;
        });
    }
//$scope.getLeadsources();
$scope.getFlags = function () {
    Flags.getSelect().success(function (data) {
        $scope.flags = data;
        $scope.getReviews();
    });
}
//$scope.getFlags();
$scope.getReffered = function () {
    Users.getSelect().success(function (data) {
        $scope.reffered = data;
    });
}
//$scope.getReffered();
$scope.getLeadsources = function () {
    Leadsources.getSelect().success(function (data) {
        $scope.leadsources = data;
        $scope.getFlags();
    });
}
//$scope.getLeadsources();
$scope.autocompleteUser = [];
$scope.getLastFieldwors = function () {
    Users.getSelect().success(function (data) {
    //$scope.lastfieldwors = data;
    var lastfieldwors = [];
    _.each(data, function (val) {
        if (val.role_id == 6 || val.role_id == 7 || val.role_id == 8) {
            lastfieldwors.push(_.extend(val, {
                name: val.first_name + ' ' + val.last_name + ' - ' + val.positiontitles_name
            }));
        }
        $scope.autocompleteUser.push({
            id: val.id.toString(),
            name: val.first_name + ' ' + val.last_name + ' - ' + val.positiontitles_name
        });
    })
    $scope.lastfieldwors = lastfieldwors;
    $scope.getLeadsources();
});
}
// $scope.getLastFieldwors();
$scope.getReviews = function () {
    Reviews.getSelect().success(function (data) {
        $scope.reviews = data;
    });
}
//$scope.getReviews();
$scope.Export = function () {
    $('#document .tblloader').show();
    Customers.exportCustomers($scope.customers).success(function (data) {
        if (data.status) {
            window.location.href = data.link;
            $('#document .tblloader').hide();
        } else {
            $('#document .tblloader').hide();
            toastr.error(data.msg);
        }
    });
}
$scope.exportdata = {};
$scope.exportfilter = function () {
    console.log($scope.exportdata);
    Customers.exportfilterCustomers($scope.exportdata, $scope.searchCustomers).success(function (data) {
        $scope.customers = $scope.parseDate(data.data);
        $scope.exportdata = {};
        $scope.currentPage = data.page;
        $scope.itemsPerPage = $scope.searchCustomers.rows;
        customers_pagesize.val($scope.itemsPerPage);
        $scope.totalItems = data.total_rows;
        $('#document .tblloader').hide();
    // $scope.repalaceres();
});
}
$scope.allCustomers = {};
$scope.autocompleteCustomer = [];
$scope.getCustomers = function () {
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.getPaging($scope.searchCustomers).success(function (data) {
        if(data.status == false){
            $cordovaToast.showLongCenter(data.msg);
        }
        else{
            $ionicLoading.hide();
            $scope.customers = $scope.parseDate(data.data);
            _.each($scope.customers, function (val) {
                var f = Date.parseDate(val.lastservicedate);
                val.lastservicedate = globalParseDate(f);
                val.customer_name = val.first_name + ' ' + val.last_name;
                $scope.autocompleteCustomer.push({
                    id: val.id,
                    name: val.customer_name
                });
            })
            $scope.customersSearch = $scope.customers;
            $scope.currentPage = data.page;
            $scope.itemsPerPage = $scope.searchCustomers.rows;
            customers_pagesize.val($scope.itemsPerPage);
            $scope.totalItems = data.total_rows;
            $scope.filterClientdata = $scope.customers;
            $scope.cusaddressescheck = data.addresses;
            $scope.lastservicedate_datacheck = data.lastservicedate;
            $scope.LastFieldWorker_datacheck = data.lastdieldworker;
            $scope.addCustomersData.phone = [{
                phone: ''
            }];
            $scope.addCustomersData.email = [{
                email: ''
            }];
            $scope.addCustomersData.reviews = [{
                review_id: '',
                comment: '',
                user: {
                    id: '',
                    name: ''
                },
                date: ''
            }];
            if ($scope.loaded == 0) {
                $scope.getLastFieldwors();
                $scope.loaded = 1;
            }
            $scope.isbuildtree = true;
            if ($scope.isbuildtree) {
                $scope.createStructTreeAddress();
                $scope.createStructFieldworker();
                $scope.createStructTreeLastService();
                $scope.isbuildtree = false;
                $scope.checkaddress = false;
                $scope.checkservicedate = false;
                $scope.checkfieldworker = false;
            }
            request_notify_get_chat = true;
            $timeout(function () {
                if (data.data.length != 0)
                    $scope.checkLoadMore = true;
            }, 5000);
            $scope.closeTarget(".customer-search");
            $("#searchInput").blur();
            $timeout(function () {
                $ionicScrollDelegate.$getByHandle('scrollCustomerContent').scrollTop(true);
                $ionicScrollDelegate.$getByHandle('scrollCustomerContent').resize();
            }, 500)
        }
        
    });
};
$scope.checkLoadMore = false;
$scope.LoadMoreCustomer = function () {
    if (!$scope.checkLoadMore)
        return;
    if($scope.isFilterCusomer){
        $scope.exportdata.actionType == 'Display';
        $scope.exportdata.current_page ++ ;
        $scope.customerFilterData($scope.exportdata);
    }else{
        $scope.searchCustomers.current_page++;
        Customers.getPaging($scope.searchCustomers).success(function (data) {
            if (data.data.length < $scope.itemsPerPage)
                $scope.checkLoadMore = false;
            var dataCustomers = $scope.parseDate(data.data)
            _.each(dataCustomers, function (val) {
                var f = Date.parseDate(val.lastservicedate);
                val.lastservicedate = globalParseDate(f);
                val.customer_name = val.first_name + ' ' + val.last_name;
                $scope.autocompleteCustomer.push({
                    id: val.id,
                    name: val.customer_name
                });
            })
            $scope.customers = arrayUnion($scope.customers, dataCustomers, function (item1, item2) {
                return item1.id == item2.id;
            });
        })
    }
    $timeout(function () {
        $scope.$broadcast('scroll.infiniteScrollComplete');
    }, 2000);
};
$scope.searchCustomer = function () {
    $scope.searchCustomers.current_page = 1;
    $scope.checkLoadMore = false;
    $scope.getCustomers();
}
$scope.keypress = function (delegate) {
    var keysByCode = [9, 16, 17, 18, 20, 27, 32, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 144];
    if ($scope.searchCustomers.search.keyCode >= 112 && $scope.searchCustomers.search.keyCode <= 123)
        return;
    if (keysByCode.indexOf($scope.searchCustomers.search.keyCode) > -1)
        return;
    $scope.coundown = 10;
    if ($scope.myTime != null)
        clearInterval($scope.myTime);
    $scope.downTimer();
};
$scope.downTimer = function (delegate) {
    $scope.myTime = setInterval(function () {
        $scope.coundown--;
        if ($scope.coundown <= 0) {
            $ionicLoading.show({
                template: templateLoading
            });
            $scope.searchCustomer();
            $ionicScrollDelegate.$getByHandle(delegate).scrollTop();
            clearInterval($scope.myTime);
        }
    }, 100);
}
$scope.parseDate = function (data) {
    _.each(data, function (item) {
        var a = moment(item.lastservicedate);
        item.year = a.year();
        item.month = a.months() + 1;
        item.date = a.date();
    });
    return data;
}
$scope.callphone = function (phonenumber) {
    $scope.callphone = phonenumber;
    Users.callphones($scope.callphone).success(function (data) { });
}
$scope.checkbox_all = {
    allstate: []
};
$scope.getcustomer_note = function (id) {
    Customers.getcustomer_note(id).success(function (data) {
        $scope.customer_notes = data;
        setTimeout(function () {
            $scope.$apply(function () {
                $('.customer_notes-' + id).html($scope.customer_notes);
            });
        }, 100);
    });
}
$scope.edit_customer_note = function (id) {
    Customers.edit_customer_note(id, $scope.customer_notes).success(function (data) {
        if (data.status) {
            toastr.success(data.msg);
        }
    });
}
$scope.searchChanged = function () {
    $scope.getCustomers();
}
$scope.addRowPhoneCreate = function () {
    $scope.addCustomersData.phone.push({
        phone: ''
    });
}
$scope.removeItemPhoneCreate = function (index) {
    if ($scope.addCustomersData.phone.length > 1) {
        $scope.addCustomersData.phone.splice(index, 1);
    }else{
        $scope.addCustomersData.phone[index].phone = '';
        $scope.addCustomersData.phone[index].phone_detail = '';
    }
}
$scope.addRowPhoneEdit = function () {
    $scope.editCustomersData.phone.push({
        phone: ''
    });
}
$scope.removeItemPhoneEdit = function (index) {
    if($scope.editCustomersData.phone[index].id && parseInt($scope.editCustomersData.phone[index].id) > 0){
        $scope.delelePhone = $scope.editCustomersData.phone[index].phone;
        $scope.indexPhoneDelete = index;
        $scope.openByGetTemplate('customerConfirmDeletePhonemodal');
    }else{
        if ($scope.editCustomersData.phone.length > 1 ) {
            $scope.editCustomersData.phone.splice(index, 1);
        }
    }

}
$scope.addRowEmailCreate = function () {
    $scope.addCustomersData.email.push({
        email: '',
        email_detail : ''
    });
}
$scope.removeItemEmailCreate = function (index) {
    if ($scope.addCustomersData.email.length > 1) {
        $scope.addCustomersData.email.splice(index, 1);
    }
}
$scope.addRowEmailEdit = function () {
    $scope.editCustomersData.email.push({
        email: '',
        email_detail : ''
    });
}

$scope.removeItemEmailEdit = function (index) {
    if($scope.editCustomersData.email[index].id && parseInt($scope.editCustomersData.email[index].id) > 0){
        $scope.deleleEmail = $scope.editCustomersData.email[index].email;
        $scope.indexEmailDelete = index;
        $scope.openByGetTemplate('customerConfirmDeleteMailmodal');
    }else{
        if ($scope.editCustomersData.email.length > 1 ) {
            $scope.editCustomersData.email.splice(index, 1);
        }
    }
}

$scope.deleteCustomersMail = function (index) {
    if ($scope.editCustomersData.email.length > 1) {
        $scope.editCustomersData.email.splice(index, 1);
        $scope.closeTarget('#customerConfirmDeleteMailmodal');
    }
}

$scope.deleteCustomersphone = function (index) {
    if ($scope.editCustomersData.phone.length > 1) {
        $scope.editCustomersData.phone.splice(index, 1);
        $scope.closeTarget('#customerConfirmDeletePhonemodal');
    }else{
        $scope.editCustomersData.phone[index].phone = '';
        $scope.editCustomersData.phone[index].phone_detail = '';
        $scope.closeTarget('#customerConfirmDeletePhonemodal');
    }
}

$scope.addRowJobsiteCreate = function () {
    $scope.addCustomersData.jobsite.push({
        label: '',
        street: '',
        apt_unit: '',
        city: '',
        state: '',
        zipcode: '',
        contactperson: '',
        contactphone: '',
        detai: ''
    });
    $scope.resizeScroll('scrollCustomerAdd');
}
$scope.addRowJobsiteEdit = function () {
    $scope.editCustomersData.jobsite.push({
        label: '',
        street: '',
        apt_unit: '',
        city: '',
        state: '',
        zipcode: '',
        contactperson: '',
        contactphone: '',
        detai: ''
    });
    $scope.resizeScroll('scrollCustomerEdit');
}
$scope.removeItemJobsiteEdit = function (index) {
    $scope.editCustomersData.jobsite.splice(index, 1);
    $scope.resizeScroll('scrollCustomerEdit');
}
$scope.sizeChanged = function () {
    $scope.searchCustomers.rows = $scope.entryLimit;
    customers_pagesize.val($scope.searchCustomers.rows);
    localStorage.setItem('customers_pagesize', $scope.searchCustomers.rows);
    $scope.searchCustomers.current_page = 1;
    $scope.getCustomers();
}
$scope.pageChanged = function () {
    $scope.searchCustomers.current_page = $scope.currentPage;
    $scope.getCustomers();
};
$scope.setPage = function (pageNo) {
    $scope.currentPage = pageNo;
};
$scope.createCustomers_checkEmail = function () {
    if ($scope.addCustomersData.email[0].email == '') {
        var confirm = $.confirm('Email Confirmation', '<div class="text-content baseline check_email">' + 'The client email is blank, we will insert it as none@gmail.com. Are you sure to do it?' + '</div>', {
            messageType: 'warning',
            overlayTransparent: .75
        }, function () {
            $scope.addCustomersData.email[0].email = 'none@none.com';
            $scope.checkAdditionalPhoneCustomer('add');
        });
        $('.check_email').parent().parent().parent().find('input[value="Cancel"]').click(function () {
            openPopup('#customerPopupAdd');
        });
    } else {
        $scope.checkAdditionalPhoneCustomer('add');
    }
}
$scope.requiredEmail = function (email_id) {
    if ($scope.addCustomersData.email[email_id].email != undefined) {
        $('#email-' + email_id).removeAttr('required');
    } else {
        $('#email-' + email_id).attr('required', 'required');
    }
}
$scope.validateForm = function (formValidate, style) {
    var exitLoop = false;
    if (formValidate.$invalid) {
        $ionicScrollDelegate.$getByHandle('scrollCustomer' + style).scrollTop();
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    }
    ;
    if (style == 'Add') {
        if ($scope.addCustomersData.email[0].email == '') {
            $ionicPopup.show({
                template: 'The customer email is blank, we will insert it as none@gmail.com. Are you sure to do it?',
                title: 'Email Confirmation',
                scope: $scope,
                buttons: [{
                    text: 'Cancel',
                    onTap: function (e) {
                        $ionicScrollDelegate.$getByHandle('popupAdd').scrollTop();
                        $cordovaToast.showLongTop('Please fill all the required information.!!!');
                    }
                }, {
                    text: '<b>Continue</b>',
                    type: 'button-positive',
                    onTap: function (e) {
                        $scope.addCustomersData.email[0].email = 'none@none.com';
                        $scope.checkAdditionalPhoneCustomer('add');
                    }
                }]
            });
        } else {
            $scope.checkAdditionalPhoneCustomer('add');
        }
    } else {
        $scope.checkAdditionalPhoneCustomer('edit');
    }
}
$scope.createCustomers = function () {
    $ionicLoading.show({
        template: templateLoading
    });
    $scope.addCustomersDataCopy = angular.copy($scope.addCustomersData);
    $scope.addCustomersDataCopy.time_table = $('#customerPopupAdd input[name="time_table"]').val();
    $scope.addCustomersDataCopy.lastservicedate = $('#customerPopupAdd input[name="lastservicedate"]').val();
    $scope.addCustomersDataCopy.user_id = $scope.currentIdLogin;
    var jsArrLen = $scope.addCustomersDataCopy.reviews.length;
    delete $scope.addCustomersDataCopy.addStreet
    // if($scope.addCustomersDataCopy.jobsite.length>0){
    //     _.each($scope.addCustomersDataCopy.jobsite, function (item) {
    //         item.street = item.streetValue;
    //         delete item.streetValue;
    //     });
    // }
    Customers.save($scope.addCustomersDataCopy).success(function (data) {
        if (data.status) {
            $ionicLoading.hide();
            $scope.resetCustomers();
            $scope.closeTarget('#customerPopupAdd');
            $cordovaToast.showLongTop(data.msg);
        } else {
            $ionicLoading.hide();
            $cordovaToast.showLongTop(data.msg);
        }
    }).error(function (data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
    });
}
$scope.resetCustomers = function () {
    $scope.addCustomersData = {};
    $scope.Input_value = {};
    $scope.resizeScroll('scrollCustomerAdd');
    $scope.initialRefferedcustomerAdd = [];
    $("#formAddCustomer")[0].reset();
}
$scope.editCustomers = function (id) {
    $scope.openByGetTemplate('customerPopupEdit');
    $scope.initialRefferedcustomerEdit = [];
    $scope.initialRefferedEmployeeEdit = [];
    $scope.currentCustomerId = id;
    $ionicLoading.show({template: templateLoading});
    Customers.show(id).success(function (data) {
        $timeout(function () {
            $scope.setValueLeadsourceInput($scope.editCustomersData.dataCustomer.leadsource_id);
            $scope.setValuelastfieldworkerInput($scope.editCustomersData.dataCustomer.lastfieldworker);
            $scope.setValueFlagInput($scope.editCustomersData.dataCustomer.flag_id);
            $ionicLoading.hide();
        }, 2000);
        $scope.editCustomersData.phone = [];
        $scope.editCustomersData = data;

        var f = Date.parseDate(data.dataCustomer.lastservicedate);
        var t = Date.parseDate(data.dataCustomer.time_table);
        $scope.editCustomersData.dataCustomer.lastservicedate = globalParseDate(f);
        $scope.editCustomersData.dataCustomer.time_table = globalParseDate(t);
        $scope.editCustomersData.dataCustomer.zipcode = parseInt($scope.editCustomersData.dataCustomer.zipcode);
        $scope.editCustomersData.dataCustomer.lastfieldworker = parseInt($scope.editCustomersData.dataCustomer.lastfieldworker);
        if (!$scope.editCustomersData.phone.length) {
            $scope.editCustomersData.phone = [{
                phone: ''
            }];
        }
        var dataRefferedcustomerEdit = [];
        if ($scope.editCustomersData.refferedcustomer) {
            var params = {
                search: $scope.editCustomersData.refferedcustomer.nameShow
            };
            Customers.getSelect2(params).success(function (data) {
                $scope.rootDataCustomer = data;
                $scope.initialRefferedcustomerEdit = [$scope.editCustomersData.refferedcustomer.id];
            });
        }
        if ($scope.editCustomersData.reviews.length > 0) {
            for (var i = 0; i < $scope.editCustomersData.reviews.length; i++) {
                if ($scope.editCustomersData.reviews[i].user) {
                    $scope.initialRefferedEmployeeEdit[i] = $scope.editCustomersData.reviews[i].user.id
                }
            }
        }
        if ($scope.editCustomersData.refferedcustomer) {
            $scope.refferedcustomerEdit = $scope.editCustomersData.refferedcustomer.name;
        }

        $scope.editCustomersData.dataCustomer.addStreet = [{place_id:'place_id',description:$scope.editCustomersData.dataCustomer.street}];
        // _.each($scope.editCustomersData.jobsite, function (item) {
        //     item.streetValue = item.street;
        //     item.street = [{place_id:'',description:item.streetValue}]
        // });
    }).error(function (data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
    });
}
$scope.updateCustomers = function () {
    $ionicLoading.show({
        template: templateLoading
    });
    delete $scope.editCustomersData.dataCustomer.addStreet;
    $scope.editCustomersDataCopy = angular.copy($scope.editCustomersData);
    var id = $scope.editCustomersDataCopy.dataCustomer.id;
    //var idx = _.findIndex($scope.customers, {id: id});
    $scope.editCustomersDataCopy.user_id = $scope.currentIdLogin;
    if ($('#customerPopupEdit input[name="time_table"]').val() != "")
        $scope.editCustomersDataCopy.dataCustomer.time_table = $('#customerPopupEdit input[name="time_table"]').val();
    $scope.editCustomersDataCopy.dataCustomer.lastservicedate = $('#customerPopupEdit input[name="lastservicedate"]').val();
    $scope.editCustomersDataCopy.user_id = $scope.currentIdLogin;
    var jsArrLen = $scope.editCustomersDataCopy.reviews.length;
    // if($scope.editCustomersDataCopy.jobsite.length>0){
    //     _.each($scope.editCustomersDataCopy.jobsite, function (item) {
    //         item.street = item.streetValue;
    //         delete item.streetValue;
    //     });
    // }
    Customers.update(id, $scope.editCustomersDataCopy).success(function (data) {
        if (data.status) {
            if ((document.URL).substring((document.URL).lastIndexOf('/') + 1) == 'customers') {
                // if (idx != -1) {
                //     $scope.customers[idx].first_name = $scope.editCustomersData.dataCustomer.first_name;
                //     $scope.customers[idx].last_name = $scope.editCustomersData.dataCustomer.last_name;
                //     $scope.customers[idx].phone_number = $scope.editCustomersData.dataCustomer.phone_number;
                //     $scope.customers[idx].street = $scope.editCustomersData.dataCustomer.street;
                //     $scope.customers[idx].email = $scope.editCustomersData.email[0].email;
                //     $scope.customers[idx].flag_id = $scope.editCustomersData.dataCustomer.flag_id;
                // }
                $scope.getCustomers();
                if ($scope.inDetail == true) {
                    $scope.getCustomerData(id);
                }
            } else {
                $scope.getCustomerData(id);
            }
            $ionicLoading.hide();
            $scope.closeTarget('#customerPopupEdit');
            $scope.Input_value = {};
            $cordovaToast.showLongTop(data.msg);
        } else {
            $ionicLoading.hide();
            $cordovaToast.showLongTop(data.msg);
        }
    });
}
$scope.showsInActiveCustomers = function (showCustomer) {
    $scope.searchCustomers.showCustomer = showCustomer;
    switch(showCustomer){
        case 'all':
        $scope.customerShow = 'All';
        break;
        case 'active':
        $scope.customerShow = 'Active';
        break;
        case 'inactive':
        $scope.customerShow = 'Deactivated';
        break;
    }

    $scope.searchCustomers.current_page = 1;
    $scope.closeTarget('#customerPopupFilterReport');
    $scope.getCustomers();
}
$scope.confirmDeleteCustomer = function (id, name, status) {
    $scope.openByGetTemplate('customerPopupDelete');
    $scope.cusInfo = {};
    $scope.cusInfo.id = id;
    $scope.cusInfo.name = name;
    $scope.cusInfo.status = status;
}
$scope.deleteCustomers = function (id, status) {
    $ionicLoading.show({
        template: templateLoading
    });
    Login.checkLogin().success(function (e) {
        Customers.activeAndInactiveUser(id, status).success(function (data) {
            $ionicLoading.hide();
            $scope.closeTarget('#customerPopupDelete');
            if (data.status) {
                var idx = _.findLastIndex($scope.customers, {id: parseInt(id)});
                if($scope.searchCustomers.showCustomer == 'all'){
                    if (idx != -1) {
                        $scope.customers[idx].status = status == "1" ? "0" : "1";
                    }
                }
                else{
                    $scope.customers.splice(idx, 1);
                }
                if ($scope.customerDetail)
                    $scope.customerDetail.status = status == "1" ? "0" : "1";
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    });
}
$scope.getUserLogin = function () {
    return Login.getUserLogin().success(function (data) {
        // console.log(data);
        if (data == false) {
            localStorage.setItem("login_status", "0");
            redirectTo('index.html');
        } else {
            current_ext = data.extension_phone;
            $scope.imagePath = pathToPublic + data.image_pic;
            var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
            if ($.trim(displayname) == "") {
                $scope.displayname = "Hello, " + data.email;
            } else {
                $scope.displayname = "Hello, " + displayname;
            }
        // $scope.getCustomers();
        // by sinhdang
        // stopTime = $interval($scope.checkLogin, time_refresh);
    }
});
}
$scope.logout = function () {
    return Login.logout().success(function (data) {
        $window.location.href = url_login;
    });
}
$scope.filterCustomer = function () {
    $scope.filterAddress();
    $scope.filterlastservice();
    $scope.filterlastfieldworker();
}
$scope.resetFilter = function () {
    $('input[name=addressSortby]').attr('checked', false);
    $('input[name=lastservicedateSortby]').attr('checked', false);
    $('input[name=lastfieldworkerSortby]').attr('checked', false);
}
$scope.filterAddress = function () {
    var data = $scope.filterAddressCollection($scope.filterClientdata);
    data = $scope.filterlastserviceCollection(data);
    data = $scope.filterlastfieldworkerCollection(data);
    $scope.customers = data;
    $scope.order($scope.addressSortby)
// $scope.repalaceres();
}
$scope.filterAddressCollection = function (collection) {
    var result = [];
    if ($scope.addresschecked.length > 0) {
        $scope.checkaddress = true;
        _.each($scope.addresschecked, function (item) {
            var item2 = _.findWhere(collection, {
                id: item.id
            });
            if (item2) {
                result.push(item2);
            }
            return item;
        });
        return result;
    } else {
        result = collection;
        $scope.checkaddress = false;
        return result;
    }
}
$scope.filterlastservice = function () {
    var data = $scope.filterlastserviceCollection($scope.filterClientdata);
    data = $scope.filterAddressCollection(data);
    data = $scope.filterlastfieldworkerCollection(data);
    $scope.customers = data;
    $scope.order($scope.lastservicedateSortby);
// $scope.repalaceres();
}
$scope.filterlastserviceCollection = function (collection) {
    var result = [];
    if ($scope.servicedatechecked.length > 0) {
        $scope.checkservicedate = true;
        _.each($scope.servicedatechecked, function (item) {
            var item2 = _.findWhere(collection, {
                id: item.id
            });
            if (item2) {
                result.push(item2);
            }
            return item;
        });
        return result;
    } else {
        $scope.checkservicedate = false;
        return collection;
    }
}
$scope.filterlastfieldworker = function () {
    var data = $scope.filterlastfieldworkerCollection($scope.filterClientdata);
    data = $scope.filterlastserviceCollection(data);
    data = $scope.filterAddressCollection(data);
    $scope.customers = data;
    $scope.order($scope.lastfieldworkerSortby);
// $scope.repalaceres();
}
    /* day la mot thuat toan ngoai le, dieu nay xay ra vi 
    trong truong hop nay dep_id khong chi ra mot su phan biet ro rang*/
    $scope.filterlastfieldworkerCollection = function (collection) {
        var result = [];
        if ($scope.fieldworkderchecked.length > 0) {
            $scope.checkfieldworker = true;
            _.each($scope.fieldworkderchecked, function (item) {
                var item2 = _.where(collection, {
                    dep_id: item.dep_id,
                    display_name: item.display_name
                });
                if (item2) {
                    if (item2.length > 0) {
                        result = result.concat(item2);
                    }
                }
                return item;
            });
            result = arrayUnion(result, [], function (item1, item2) {
                return item1.id == item2.id;
            });
            return result;
        } else {
            $scope.checkfieldworker = false;
            return collection;
        }
    }
    var orderBy = $filter('orderBy');
    $scope.order = function (predicate) {
// if ($scope.sortby) {
    $scope.customers = orderBy($scope.customers, predicate);
// }
};
$scope.getlastservicedate = function () {
    $scope.createStructTreeLastService();
}
$scope.getLastFieldWorker = function () {
    /**/
    $scope.createStructFieldworker();
}
$scope.getstate = function () {
    $scope.createStructTreeAddress();
}
$scope.changeAddress = function (node, ihvselected, tree) {
    $scope.lastChangedNode = node;
    if (ihvselected) {
        switch (node.level) {
            case "0":
            $scope.addresschecked = $scope.streets;
            break;
            case "1":
            var list = _.where($scope.streets, {
                state: node.state
            });
            $scope.addresschecked = $scope.mergeAddresschecked(list, $scope.addresschecked);
            break;
            case "2":
            var list = _.where($scope.streets, {
                state: node.state,
                city: node.city
            });
            $scope.addresschecked = $scope.mergeAddresschecked(list, $scope.addresschecked);
            break;
            case "3":
            var list = _.where($scope.streets, {
                state: node.state,
                city: node.city,
                street: node.street
            });
            $scope.addresschecked = $scope.mergeAddresschecked(list, $scope.addresschecked);
            break;
        }
    } else {
        switch (node.level) {
            case "0":
            $scope.addresschecked = [];
            break;
            case "1":
            var list = _.where($scope.streets, {
                state: node.state
            });
            $scope.removeAddresschecked(list);
            break;
            case "2":
            var list = _.where($scope.streets, {
                state: node.state,
                city: node.city
            });
            $scope.removeAddresschecked(list);
            break;
            case "3":
            var list = _.where($scope.streets, {
                state: node.state,
                city: node.city,
                street: node.street
            });
            $scope.removeAddresschecked(list);
            break;
        }
    }
}
$scope.changeServiceDate = function (node, ihvselected, tree) {
    $scope.lastChangedNode = node;
    if (ihvselected) {
        switch (node.level) {
            case "0":
            $scope.servicedatechecked = $scope.dates;
            break;
            case "1":
            var list = _.where($scope.dates, {
                year: node.year
            });
            $scope.servicedatechecked = $scope.mergeServicedatechecked(list, $scope.servicedatechecked);
            break;
            case "2":
            var list = _.where($scope.dates, {
                year: node.year,
                month: node.month
            });
            $scope.servicedatechecked = $scope.mergeServicedatechecked(list, $scope.servicedatechecked);
            break;
            case "3":
            var list = _.where($scope.dates, {
                year: node.year,
                month: node.month,
                date: node.date
            });
            $scope.servicedatechecked = $scope.mergeServicedatechecked(list, $scope.servicedatechecked);
            break;
        }
    } else {
        switch (node.level) {
            case "0":
            $scope.servicedatechecked = [];
            break;
            case "1":
            var list = _.where($scope.dates, {
                year: node.year
            });
            $scope.removeServicedatechecked(list);
            break;
            case "2":
            var list = _.where($scope.dates, {
                year: node.year,
                month: node.month
            });
            $scope.removeServicedatechecked(list);
            break;
            case "3":
            var list = _.where($scope.dates, {
                year: node.year,
                month: node.month,
                date: node.date
            });
            $scope.removeServicedatechecked(list);
            break;
        }
    }
}
$scope.changeFieldWorker = function (node, ihvselected, tree) {
    $scope.lastChangedNode = node;
    if (ihvselected) {
        switch (node.level) {
            case "0":
            $scope.fieldworkderchecked = $scope.lastfieldworkers;
            break;
            case "1":
            var list = _.where($scope.lastfieldworkers, {
                dep_id: node.dep_id
            });
            $scope.fieldworkderchecked = $scope.mergeFieldworkderchecked(list, $scope.fieldworkderchecked);
            break;
            case "2":
            var list = _.where($scope.lastfieldworkers, {
                dep_id: node.dep_id,
                display_name: node.display_name
            });
            $scope.fieldworkderchecked = $scope.mergeFieldworkderchecked(list, $scope.fieldworkderchecked);
            break;
        }
    } else {
        switch (node.level) {
            case "0":
            $scope.fieldworkderchecked = [];
            break;
            case "1":
            var list = _.where($scope.lastfieldworkers, {
                dep_id: node.dep_id
            });
            $scope.removeFieldworkderchecked(list);
            break;
            case "2":
            var list = _.where($scope.lastfieldworkers, {
                dep_id: node.dep_id,
                display_name: node.display_name
            });
            $scope.removeFieldworkderchecked(list);
            break;
        }
    }
}
$scope.createStructTreeAddress = function () {
    if ($scope.isbuildtree) {
        $scope.addresschecked = [];
        var states = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "state", "city", 'street'), {
                label: currentObject.state,
                level: "1"
            });
        }), function (item, key, state) {
            return item.state;
        });
        var cities = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "state", "city", 'street'), {
                label: currentObject.city,
                level: "2"
            });
        }), function (item, key, city) {
            return item.city;
        });
        var streets = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "state", "city", 'street'), {
                label: currentObject.street,
                level: "3"
            });
        }));
        $scope.streets = _.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "state", "city", 'street', 'id'), {
                label: currentObject.street,
                level: "3"
            });
        });
        var city_fills = _.each(cities, function (item) {
            streetofcities = _.where(streets, {
                city: item.city,
                state: item.state
            });
            item.children = streetofcities;
            return item;
        });
        var state_fills = _.each(states, function (item) {
            cityofstate = _.where(city_fills, {
                state: item.state
            });
            item.children = cityofstate;
            return item;
        });
        $scope.stuff0 = [{
            label: 'Select All',
            level: "0",
            children: state_fills
        }];
    }
}
$scope.createStructTreeLastService = function () {
    if ($scope.isbuildtree) {
        $scope.servicedatechecked = [];
        var years = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "year", "month", 'date'), {
                label: currentObject.year,
                level: "1"
            });
        }), function (item, key, year) {
            return item.year;
        });
        years = _.sortBy(years, 'year');
        years = years.reverse();
        var months = $scope.uniqueMoth(_.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "year", "month", 'date'), {
                label: currentObject.month,
                level: "2"
            });
        }));
        months = _.sortBy(months, 'month');
        $scope.uniqueDate(_.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "id", "year", "month", 'date'), {
                label: currentObject.date,
                level: "3"
            });
        }));
        $scope.uniqueDate2(_.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "year", "month", 'date'), {
                label: currentObject.date,
                level: "3"
            });
        }));
        var month_fills = _.each(months, function (item) {
            var datetofmonth = _.where($scope.dates2, {
                year: item.year,
                month: item.month
            });
            item.children = _.sortBy(datetofmonth, 'date');
            return item;
        });
        var year_fills = _.each(years, function (item) {
            var cityofstate = _.where(month_fills, {
                year: item.year
            });
            item.children = cityofstate;
            return item;
        });
        $scope.stuff1 = [{
            label: 'Select All',
            level: "0",
            children: year_fills
        }];
    }
}
$scope.createStructFieldworker = function () {
    if ($scope.isbuildtree) {
        $scope.fieldworkderchecked = [];
        var deps = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "dep_id", "display_name", 'dep_name'), {
                label: currentObject.dep_name,
                level: "1"
            });
        }), function (item, key, dep_id) {
            return item.dep_id;
        });
        var workers = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "dep_id", "display_name", 'dep_name'), {
                label: currentObject.display_name,
                level: "2"
            });
        }), function (item, key, display_name) {
            return item.display_name;
        });
        $scope.lastfieldworkers = _.map($scope.filterClientdata, function (currentObject) {
            return _.extend(_.pick(currentObject, "dep_id", "display_name", 'dep_name'), {
                label: currentObject.display_name,
                level: "2"
            });
        });
        var year_fills = _.each(deps, function (item) {
            var cityofstate = _.where(workers, {
                dep_id: item.dep_id
            });
            item.children = cityofstate;
            return item;
        });
        $scope.stuff2 = [{
            label: 'Select All',
            level: "0",
            children: year_fills
        }];
    }
}
$scope.mergeFieldworkderchecked = function (list, listcurr) {
    return arrayUnion(list, listcurr, function (item1, item2) {
        return item1.dep_id == item2.dep_id && item1.display_name == item2.display_name;
    });
}
$scope.removeFieldworkderchecked = function (list) {
    _.each(list, function (item) {
        var indexof = _.findIndex($scope.fieldworkderchecked, {
            dep_id: item.dep_id,
            display_name: item.display_name
        });
        if (indexof >= 0) {
            $scope.fieldworkderchecked.splice(indexof, 1);
        }
    });
}
$scope.mergeServicedatechecked = function (list, listcurr) {
    return arrayUnion(list, listcurr, function (item1, item2) {
        return item1.id == item2.id;
    });
}
$scope.removeServicedatechecked = function (list) {
    _.each(list, function (item) {
        var indexof = _.findIndex($scope.servicedatechecked, {
            id: item.id,
            year: item.year,
            month: item.month,
            date: item.date
        });
        if (indexof >= 0) {
            $scope.servicedatechecked.splice(indexof, 1);
        }
    });
}
$scope.mergeAddresschecked = function (list, currentlist) {
    return arrayUnion(list, $scope.addresschecked, function (item1, item2) {
        return item1.id == item2.id;
    });
}
$scope.removeAddresschecked = function (list) {
    _.each(list, function (item) {
        var indexof = _.findIndex($scope.addresschecked, {
            id: item.id
        });
        if (indexof >= 0) {
            $scope.addresschecked.splice(indexof, 1);
        }
    });
}
$scope.uniqueMoth = function (list) {
    return arrayUnion(list, [], function (item1, item2) {
        return item1.month == item2.month && item1.year == item2.year;
    });
}
$scope.uniqueDate = function (list) {
    $scope.dates = arrayUnion(list, [], function (item1, item2) {
        return item1.month == item2.month && item1.year == item2.year && item1.date == item2.date && item2.id == item1.id;
    });
}
$scope.showHideTimeTable = function () {
    $scope.leadsource_id = $('#leadsource_id').val();
    if ($scope.leadsource_id == 2 || $scope.leadsource_id == 4) {
        $('.timetable-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.pageChanged = function () {
    $scope.searchCustomers.current_page = $scope.currentPage;
    $scope.getCustomers();
};
$scope.setPage = function (pageNo) {
    $scope.currentPage = pageNo;
    console.log('doi page');
};
$scope.refreshEmployeeReview = function (search) {
    if (search.length > 0) {
        var params = {
            search: search
        };
        Users.searchAssign(params).success(function (res) {
            var diff = differentArray(res, $scope.employeeReview);
            $scope.employeeReviewSelect = diff;
        })
    } else {
        $scope.employeeReviewSelect = [];
    }
};
$scope.refreshEmployeeReviewEdit = function (search) {
    if (search.length > 0) {
        var params = {
            search: search
        };
        Users.searchAssign(params).success(function (res) {
            var diff = differentArray(res, $scope.employeeReviewEdit);
            $scope.employeeReviewSelectEdit = diff;
        })
    } else {
        $scope.employeeReviewSelectEdit = [];
    }
};
// $scope.checkLogin = function () {
//     return Login.checkLogin().success(function (data) {
//         if (data.status == false) {
//             $window.location.href = url_login;
//         } else {
//             //$scope.getUserLogin();
//         }
//     });
// }
$scope.inactive = function (val) {
    return val == 1 ? false : true;
}
$scope.uniqueDate2 = function (list) {
    $scope.dates2 = arrayUnion(list, [], function (item1, item2) {
        return item1.month == item2.month && item1.year == item2.year && item1.date == item2.date;
    });
}
// by sinhdang change select hide / input tag
$scope.exportdata.Last_Field_Worker = [];
$scope.filterAllCustomers = function ($query, $switch) {
    switch ($switch) {
            case 1: // for lastfieldworker on filter report
            return $scope.lastfieldwors.filter(function ($str) {
                return $str.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
            });
            break;
// case 2: // for app suplier item
//     return $scope.rootSupplieritems.filter(function($str) {
//         return $str.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
//     });
//     break;
default:
//
}
};

// edit by haudao

//console.log((document.URL).substring((document.URL).lastIndexOf('/') + 1));
$scope.searchZipCodeFilter = function ($query) {
    return $scope.dataFilterZipcodeDetail.filter(function ($str) {
        return $str.postal_code.toLowerCase().indexOf($query.toLowerCase()) != -1;
    });
};

$scope.renderTemplateData = function () {
    dataHtml.getTemplate('templates/dashboard/customers/customers/customerMenuHeadermodal.tpl').success(function (results) {
        $scope.dataHtml.menuHeader = results;
        dataHtml.getTemplate('templates/dashboard/customers/customers/customerContentmodal.tpl').success(function (results) {
            $scope.dataHtml.listContent = results;
            $timeout(function () {
                setHeight("#main-content");
            }, 1)
            $scope.getCustomers();
        });
    });
}
$scope.openByGetTemplate = function (style) {
    $ionicLoading.show({template: templateLoading});
    $timeout(function () {
        switch (style) {
            case 'customerPopupFilterReport':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerFilterSettingmodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupFilterReport = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupFilterReport');
                    $ionicScrollDelegate.$getByHandle('scrollFilterReport').resize();
                    $ionicScrollDelegate.$getByHandle('scrollFilterReport').scrollTop(true);
                }, 1)
                $scope.getcustomerqueries();
                $ionicLoading.hide();
            });
            break;
            case 'customerPopupAdd':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupAddmodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupAdd = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupAdd');
                    $ionicScrollDelegate.$getByHandle('scrollCustomerAdd').resize();
                    $ionicScrollDelegate.$getByHandle('scrollCustomerAdd').scrollTop(true);
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupEdit':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupEditmodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupEdit = results;
                $timeout(function () {
                    $scope.Input_value = {};
                    $scope.showTarget('#customerPopupEdit');
                    $ionicScrollDelegate.$getByHandle('scrollCustomerEdit').resize();
                    $ionicScrollDelegate.$getByHandle('scrollCustomerEdit').scrollTop(true);
                }, 1)
            });
            break;
            case 'customerPopupDelete':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupDeletemodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupDelete = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupDelete');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupDelete':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupDeletemodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupDelete = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupDelete');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupReviewFilter':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupReviewFiltermodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupReviewFilter = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupReviewFilter');
                    $ionicScrollDelegate.$getByHandle('scrollCustomerReviewFilter').resize();
                    $ionicScrollDelegate.$getByHandle('scrollCustomerReviewFilter').scrollTop(true);
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupReviewAdd':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupReviewAddmodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupReviewAdd = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupReviewAdd');
                    $ionicScrollDelegate.$getByHandle('scrollCustomerReviewAdd').resize();
                    $ionicScrollDelegate.$getByHandle('scrollCustomerReviewAdd').scrollTop(true);
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupReviewEdit':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupReviewEditmodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupReviewEdit = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupReviewEdit');
                    $ionicScrollDelegate.$getByHandle('scrollCustomerReviewEdit').resize();
                    $ionicScrollDelegate.$getByHandle('scrollCustomerReviewEdit').scrollTop(true);
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupReviewDelete':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupReviewDeletemodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupReviewDelete = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupReviewDelete');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupJobsite':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupJobsitemodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupJobsite = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupJobsite');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupJobsiteAdd':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupJobsiteAddmodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupJobsiteAdd = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupJobsiteAdd');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupJobsiteEdit':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupJobsiteEditmodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupJobsiteEdit = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupJobsiteEdit');
                }, 1)
            });
            break;
            case 'customerPopupJobsiteDelete':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupJobsiteDeletemodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupJobsiteDelete = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupJobsiteDelete');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupJobsiteMakePrimary':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupJobsiteMakePrimarymodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupJobsiteMakePrimary = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupJobsiteMakePrimary');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupDetail':
            dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupDetailmodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupDetail = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupDetail');
                    $ionicScrollDelegate.$getByHandle('scrollCustomerDetail').resize();
                    $ionicScrollDelegate.$getByHandle('scrollCustomerDetail').scrollTop(true);
                }, 1)
            });
            break;

            case 'customerDetailPopupAppointmentHistoryViewLog':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailPopupAppointmentHistoryViewLogmodal.tpl').success(function (results) {
                $scope.dataHtml.customerDetailPopupAppointmentHistoryViewLog = results;
                $timeout(function () {
                    $scope.showTarget('#customerDetailPopupAppointmentHistoryViewLog');
                }, 1)
            });
            break;
            case 'customerPopupPhoneAdditionalMore':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailPopupPhoneAdditionalMoremodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupPhoneAdditionalMore = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupPhoneAdditionalMore');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupEmailAdditionalMore':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailPopupEmailAdditionalMoremodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupEmailAdditionalMore = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupEmailAdditionalMore');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'popupCheckAdditionalPhones':
            dataHtml.getTemplate('templates/dashboard/customers/customers/popupCheckAdditionalPhones.tpl').success(function (results) {
                $scope.dataHtml.popupCheckAdditionalPhones = results;
                $timeout(function () {
                    $scope.showTarget('#popupCheckAdditionalPhones');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerConfirmDeleteMailmodal':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerConfirmDeleteMailmodal.tpl').success(function (results) {
                $scope.dataHtml.customerConfirmDeleteMailmodal = results;
                $timeout(function () {
                    $scope.showTarget('#customerConfirmDeleteMailmodal');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerConfirmDeletePhonemodal':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerConfirmDeletePhonemodal.tpl').success(function (results) {
                $scope.dataHtml.customerConfirmDeletePhonemodal = results;
                $timeout(function () {
                    $scope.showTarget('#customerConfirmDeletePhonemodal');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'addJobsiteModal':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailAddJobsiteModal.tpl').success(function (results) {
                $scope.dataHtml.addJobsiteModal = results;
                $timeout(function () {
                    $scope.showTarget('#addJobsiteModal');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'jobsiteLogModal':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerJobsiteLogModal.tpl').success(function (results) {
                $scope.dataHtml.jobsiteLogModal = results;
                $timeout(function () {
                    $scope.showTarget('#jobsiteLogModal');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'popupCustomerFilterJobsite':
            dataHtml.getTemplate('templates/dashboard/customers/customers/popupCustomerFilterJobsite.tpl').success(function (results) {
                $scope.dataHtml.popupCustomerFilterJobsite = results;
                $timeout(function () {
                    $scope.showTarget('#popupCustomerFilterJobsite');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerPopupCreditCard':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerPopupCreditCardmodal.tpl').success(function (results) {
                $scope.dataHtml.customerPopupCreditCard = results;
                $timeout(function () {
                    $scope.showTarget('#customerPopupCreditCard');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerDetailAddCreditCard':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailAddCreditCardModal.tpl').success(function (results) {
                $scope.dataHtml.customerDetailAddCreditCard = results;
                $timeout(function () {
                    $scope.showTarget('#customerDetailAddCreditCard');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerDetailEditCreditCard':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailEditCreditCardModal.tpl').success(function (results) {
                $scope.dataHtml.customerDetailEditCreditCard = results;
                $timeout(function () {
                    $scope.showTarget('#customerDetailEditCreditCard');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'customerDetailPopupCreditCardDelete':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailPopupCreditCardDeletemodal.tpl').success(function (results) {
                $scope.dataHtml.customerDetailPopupCreditCardDelete = results;
                $timeout(function () {
                    $scope.showTarget('#customerDetailPopupCreditCardDelete');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'popupInstoreCredit':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerPopupInstoreCredit.tpl').success(function (results) {
                $scope.dataHtml.popupInstoreCredit = results;
                $timeout(function () {
                    $scope.showTarget('#popupInstoreCredit');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'popupAddInstoreCredit':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerPopupAddInstoreCredit.tpl').success(function (results) {
                $scope.dataHtml.popupAddInstoreCredit = results;
                $timeout(function () {
                    $scope.showTarget('#popupAddInstoreCredit');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'confirmOverateInstoreCredit':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailConfirmOverateInstoreCreditmodal.tpl').success(function (results) {
                $scope.dataHtml.confirmOverateInstoreCredit = results;
                $timeout(function () {
                    $scope.showTarget('#confirmOverateInstoreCredit');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'popupEditInstoreCredit':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerPopupEditInstoreCredit.tpl').success(function (results) {
                $scope.dataHtml.popupEditInstoreCredit = results;
                $timeout(function () {
                    $scope.showTarget('#popupEditInstoreCredit');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
            case 'confirmDeleteInstoreCredit':
            dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailConfirmDeleteInstoreCreditmodal.tpl').success(function (results) {
                $scope.dataHtml.confirmDeleteInstoreCredit = results;
                $timeout(function () {
                    $scope.showTarget('#confirmDeleteInstoreCredit');
                    $ionicLoading.hide();
                }, 1)
            });
            break;
        }
    }, 500);
}
$scope.openImages = function () {
    var options = {
        maximumImagesCount: 1,
        width: 0,
        height: 0,
        quality: 100
    };
    $cordovaImagePicker.getPictures(options).then(function (results) {
        console.log(results[0]);
        $scope.src = results[0];
    })
}


// edit by haudao
$scope.getappointmenthistory = function (customerId) {
    $scope.customerDetail.id = customerId;
    $ionicLoading.show({template: templateLoading});
    dataHtml.getTemplate('templates/dashboard/customers/customer-detail/customerDetailPopupAppointmentHistorymodal.tpl').success(function (results) {
        $scope.dataHtml.customerDetailPopupAppointmentHistory = results;
        $timeout(function () {
            $scope.showTarget('#customerDetailPopupAppointmentHistory');
            $ionicScrollDelegate.$getByHandle('scrollAppointmentHistory').resize();
            $ionicScrollDelegate.$getByHandle('scrollAppointmentHistory').scrollTop(true);
            Customers.getappointmenthistory(customerId).success(function (data) {
                $scope.dataJobsiteToAutocomplete = [];
                $ionicLoading.hide();
                if (data['error']) {
                    $scope.appointmenthistory = [];
                } else {
                    $scope.appointmenthistory = $scope.sortAppHistory(data.data);
                }
                $scope.customeraddress = data.customeraddress;
                $scope.jobsitedataView = [{id: '', name: 'All'}];
                $scope.dataJobsiteToAutocomplete = data.jobsitedata;
                $scope.appointment_history_error = data['error'];
                $scope.initialJobsiteFilter = [""];
            });

        }, 1)
    });


}

$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.customerDetail.id).success(function (data) {
        $ionicLoading.hide();
        if (data['error']) {
            $scope.appointmenthistory = [];
        } else {
            $scope.appointmenthistory = data;
        }
        $scope.appointment_history_error = data['error'];
        $ionicScrollDelegate.$getByHandle('scrollAppointmentHistory').resize();
        $ionicScrollDelegate.$getByHandle('scrollAppointmentHistory').scrollTop();
    });
}
$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.setValueForInput = function (arrData, id) {
    var result = '';
    var index = _.findLastIndex(arrData, {
        id: id
    });
    if (index >= 0)
        result = arrData[index];
    return result;
}
$scope.setValueLeadsourceInput = function (id) {
    $scope.Input_value.leadsource = "";
    $scope.Input_value.leadsource = $scope.setValueForInput($scope.leadsources, id).name;
}
$scope.setValuelastfieldworkerInput = function (id) {
    $scope.Input_value.lastfieldworker = "";
    $scope.Input_value.lastfieldworker = $scope.setValueForInput($scope.lastfieldwors, id).name;
}
$scope.setValueReviewInput = function (id) {
    $scope.Input_value.review = "";
    $scope.Input_value.review = $scope.setValueForInput($scope.reviews, id).name;
}
$scope.setValueFlagInput = function (id) {
    $scope.Input_value.flag = "";
    $scope.Input_value.flag = $scope.setValueForInput($scope.flags, id).name;
}
    // $interval(function () {
    //     if (window.StatusBar) {
    //         StatusBar.hide();
    //     }
    // }, 5000);
    $scope.hideKeyboard = function () {
        $cordovaKeyboard.close();
    }; //ng-click vao doi tuong muon hide keyboard
    $scope.scrollHandle = function (positionID, style, offset) {
// popup = 'popupAddCustomer';
// if (style != 'Add') popup = 'customerPopupEdit';
// $location.hash(positionID); //set the location hash
// var handle = $ionicScrollDelegate.$getByHandle('scroll' + style);
// handle.anchorScroll();
// $timeout(function() {
//     var top = handle.getScrollPosition().top - 30;
//     // console.log('160',top);
//     handle.scrollTo(0, top, false);
// }, 500);
}

$scope.activeTab = function (style) {
    popup = 'customerPopupEdit';
    if (style != 'Edit')
        popup = 'popupAddCustomer';
    var handle = $ionicScrollDelegate.$getByHandle('scroll' + style);
    var top = handle.getScrollPosition().top;
    // console.log(top);
    if (top < 1020) {
        $("#" + popup + " .tab-link-4 .itm").removeClass('active');
        $("#" + popup + " .tab-link-4 div").eq(0).addClass('active');
    } else {
        $("#" + popup + " .tab-link-4 .itm").removeClass('active');
        $("#" + popup + " .tab-link-4 div").eq(1).addClass('active');
    }
}
$scope.phone = {};
$scope.openPopupPhone = function (item) {
    $ionicLoading.show({template: templateLoading});
    dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupPhonemodal.tpl').success(function (results) {
        $scope.dataHtml.customerPopupPhone = results;
        $scope.phone.primary = item.phone_number;
        $scope.phone.additional = item.customerphones;
        $scope.phone.totalPhones = $scope.phone.additional.length + 1;
        $scope.phone.name = item.first_name + ' ' + item.last_name;
        $scope.showTarget('#customerPopupPhone');
        $ionicLoading.hide();
    });
}
$scope.clickedMethodUser = function (callback, index, style) {
    if (style == 'add') {
    // print out the selected item
    // console.log(callback.item);
    $scope.addCustomersData.reviews[index].user = [];
    $scope.addCustomersData.reviews[index].user = callback.item;
    console.log($scope.addCustomersData.reviews);
} else {
    // print out the selected item
    // console.log(callback.item);
    $scope.editCustomersData.reviews[index].user = [];
    $scope.editCustomersData.reviews[index].user = callback.item;
    // console.log($scope.editCustomersData.reviews);
}
}
$scope.removeMethodUser = function (callback, index, style) {
    if (style == 'add') {
        $scope.addCustomersData.reviews[index].user = [];
        console.log($scope.addCustomersData.reviews);
    } else {
        $scope.editCustomersData.reviews[index].user = [];
        console.log($scope.editCustomersData.reviews);
    }
}
$scope.getEmployeeReview = function (query, isInitializing, index, style) {
    var returnValue = {
        items: []
    };
    var id = $scope.autocompleteList.refferedEmployeeAdd[index];
    if (style != 'add') {
        id = $scope.autocompleteList.refferedEmployeeEdit[index];
    }
    $scope.autocompleteUser.forEach(function (item) {
        if (item.id != id) {
            if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                returnValue.items.push(item);
            } else if (item.id.indexOf(query) > -1) {
                returnValue.items.push(item);
            }
        }
    });
    return returnValue;
};
$scope.initialRefferedEmployeeEdit = [];
$scope.setValueForRefferedEmployee = function (modelValue) {
    for (var i = 0; i < $scope.autocompleteUser.length; i++) {
        if ($scope.autocompleteUser[i].id == modelValue) {
            return $scope.autocompleteUser[i];
        }
    }
    return {};
};
$scope.filterReferred = function (query, type) {
    var returnValue = {
        items: []
    };
    var id = $scope.autocompleteList.refferedcustomerAdd;
    if (type != 'add') {
        id = $scope.autocompleteList.refferedcustomerEdit;
    }
    if (query.length > 0) {
        var params = {
            search: query
        };
        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.rootDataCustomer.forEach(function (item) {
                if (id.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);
                    }
                }
            });
        })
    }
    return returnValue;
};
$scope.onSelectReferred = function (callback, type) {
    if (type == 'add') {
        $scope.addCustomersData.refferedcustomer = callback.item;
    } else {
        $scope.editCustomersData.refferedcustomer = callback.item;
    }
    $scope.Input_value.displayReferred = callback.item.first_name + ' ' + callback.item.last_name;
}
$scope.onRemoveReferred = function (callback, type) {
    if (type == 'add') {
        $scope.addCustomersData.refferedcustomer = {};
    } else {
        $scope.editCustomersData.refferedcustomer = {}
    }
    $scope.Input_value.displayReferred = '';
}
$scope.initialRefferedcustomerEdit = [];
$scope.initialRefferedcustomerAdd = [];
$scope.setValueForRefferedCustomer = function (modelValue) {
    for (var i = 0; i < $scope.rootDataCustomer.length; i++) {
        if ($scope.rootDataCustomer[i].id == modelValue) {
            return $scope.rootDataCustomer[i];
        }
    }
    return {};
};
//find value by key
$scope.colorFlag = function (valuetosearch) {
    for (var i = 0; i < flagColorObj.length; i++) {
        if (flagColorObj[i]['id'] == parseInt(valuetosearch)) {
            return flagColorObj[i]['nclass'];
        }
    }
    return null;
}
// end
// edit by haudao
$scope.redirectTo = function (url) {
    $ionicLoading.show({template: templateLoading});
    $timeout(function () {
        redirectTo(url);
    }, 1000)
}
$scope.filterCustomerForSearch = function (query) {
    var returnValue = {
        items: []
    };
    var params = {
        rows: 50,
        current_page: 1,
        search: query,
        showCustomer: $scope.searchCustomers.showCustomer
    };
    $ionicLoading.show({template: templateLoading});
    Customers.getPaging(params).success(function (data) {
        $scope.rootDataCustomer = data.data;
        $scope.rootDataCustomer.forEach(function (item) {
            item.name = item.first_name + ' ' + item.last_name + ' ' + item.street + ' ' + item.phone_number;
        })
        $scope.rootDataCustomer.forEach(function (item) {
            if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                returnValue.items.push(item);
            } else if (replaceAllPhone(item.phone_number).indexOf(replaceAllPhone(query)) > -1) {
                returnValue.items.push(item);
            }
        });
        $timeout(function () {
            $ionicLoading.hide();
        }, 1000)

    })
    return returnValue;
}
$scope.selectCustomerFormSearch = function (callback) {
    $scope.getCustomerData(callback.item.id);
    $scope.initialCustomerForSearch = [];
}
$scope.selectCustomerFormSearchReview = function (callback) {
    $scope.searchCustomereviews.search = callback.item.first_name + ' ' + callback.item.last_name;
    $scope.searchCustomereviews.current_page = 1;
    $scope.getCustomereviews();
}
$scope.modelCustomerForSearch = function (modelValue) {
    return
}
$scope.viewAppnote = function (dataOfficeNote, dataFieldWorkerNote, type) {
    $scope.noteViewMode = type;
    $ionicLoading.show({template: templateLoading});
    $scope.openByGetTemplate('customerDetailPopupAppointmentHistoryViewLog');
    $timeout(function (val) {
        $scope.dataViewAppNote.office = dataOfficeNote;
        $scope.dataViewAppNote.fieldworker = dataFieldWorkerNote;
        $ionicLoading.hide();
    }, 10);
}
$scope.showAppointmentHistoryDetail = [];
$scope.checkAppointmentHistoryDetail = function (idx) {
    $scope.showAppointmentHistoryDetail[idx] = $scope.showAppointmentHistoryDetail[idx] == 1 ? 0 : 1;
    $ionicScrollDelegate.$getByHandle('scrollAppointmentHistory').resize();

}
$scope.resizeScroll = function (id) {
    $ionicScrollDelegate.$getByHandle(id).resize();
}
$scope.openAutocomplete = function (className) {
    if(className=='ion-autocomplete-search-customer'){
        dataHtml.getTemplate('templates/dashboard/customers/customers/customerSearchSettingmodal.tpl').success(function (results) {
            $scope.dataHtml.searchCustomer = results;
        });
    }

    if(className=='ion-autocomplete-search-customer-review'){
        dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupReviewSearchmodal.tpl').success(function (results) {
            $scope.dataHtml.searchCustomer = results;
        });
    }
    
    $timeout(function () {
        var ionAutocompleteElement = document.getElementsByClassName(className);
        angular.element(ionAutocompleteElement).controller('ionAutocomplete').fetchSearchQuery("", true);
        angular.element(ionAutocompleteElement).controller('ionAutocomplete').showModal();
        $timeout(function() {
            angular.element('.backdrop').removeClass('visible').removeClass('active');
        }, 1000);
    }, 500)

}

// customerDetail

$scope.getCustomerData = function (id) {
    if($scope.viewCustomerDetail){
        $scope.inDetail = true;
        $scope.openByGetTemplate('customerPopupDetail');
        $ionicLoading.show({template: templateLoading});
        Customers.showDetail(id).success(function (data) {
            $ionicLoading.hide();
            $scope.customerDetail = data;
            // format date for lastservice
            var f = Date.parseDate($scope.customerDetail.lastservicedate);
            $scope.customerDetail.lastservicedate = globalParseDate(f);
            var f = Date.parseDate($scope.customerDetail.customer_since);
            $scope.customerDetail.customer_since = globalParseDate(f);
            // trust email
            _.extend($scope.customerDetail, {
                mailto: $sce.trustAsHtml('<a href="mailto:' + $scope.customerDetail.email + '">' + $scope.customerDetail.email + '</a>'),
                link_phone_number: $sce.trustAsHtml('<a href="tel:' + $scope.customerDetail.phone_number + '">' + $scope.customerDetail.phone_number + '</a>'),
                link_additionalPhone: [],
                link_additionalEmail: []
            });
            _.each($scope.customerDetail.additionalPhone, function (val) {
                $scope.customerDetail.link_additionalPhone.push({
                    link: $sce.trustAsHtml("<a href='tel:" + val + "'>" + val + "</a>"),
                    phone: val
                });
            });
            _.each($scope.customerDetail.additionalEmail, function (val) {
                $scope.customerDetail.link_additionalEmail.push({
                    link: $sce.trustAsHtml("<a href='mailto:" + val + "'>" + val + "</a>")
                });
            });
            request_notify_get_chat = true;
            if($scope.org_page=='apphistory'){
                $scope.getappointmenthistory(id);
            }
        });
    }
    else{
        $cordovaToast.showLongCenter('No permission !!! ');
    }
    
}

$scope.confirmMakePrimary = function (id) {
    $scope.openByGetTemplate('customerPopupJobsiteMakePrimary');
    $scope.dataMakePrimary = {};
    $scope.dataMakePrimary.jobsiteId = id;
    $scope.dataMakePrimary.customerId = $scope.current_jobsite_customer_id;
}
$scope.makePrimary = function () {
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.makePrimary($scope.dataMakePrimary).success(function (data) {
        $ionicLoading.hide();
        $cordovaToast.showLongCenter(data.msg);
        $scope.closeTarget('#customerPopupJobsiteMakePrimary');
    }).error(function (data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
    });
};

$scope.openlistjobsite = function(customer_id,from) {
    $scope.current_customer = _.where($scope.customers, {
        id: customer_id
    })[0];
    $scope.openByGetTemplate('customerPopupJobsite');
    $scope.loadJobsiteByCustomerId(customer_id);

    $scope.click_jobsite_form = from;
};

$scope.loadJobsiteByCustomerId = function(customer_id) {
    $scope.current_jobsite_customer_id = customer_id;
    $scope.searchCustomerJobsite.customer_id = customer_id;
    $ionicLoading.show({template: templateLoading});
    Customers.loadJobsiteByCustomerId($scope.searchCustomerJobsite).success(function(data) {
        $ionicLoading.hide();
        if(data.status == false){
            $cordovaToast.showLongCenter(data.msg);
        }else{
            $scope.tableJobsiter = data.data;
        }
        
    })
};
$scope.changeDatetime = function (type, s) {
    if (s == null)
        return "";
    switch (type) {
        case "DT2D":
        var dateS = s.split(' ');
        return dateS[0];
        break;
        case "DT2T":
        return Date.parseDate(s);
        // var dateS = s.split(' ');
        // return dateS[1];
        break;
        default:
    }
}
$scope.openFileManager = function (id) {
    $scope.$broadcast('openFileManager', {customer_id: id});
}

// end customerDetail


// customerReview
function searchCusReviewHandle() {
    toggleDelegateHandle('#customer_page', '.link-customer-review-search', '.customer-review-search');
    toggleDelegateHandle('#customer_page', '.customer-review-search .search-type .btn-close', '.customer-review-search');
    toggleDelegateHandle('#customer_page', '.customer-review-search .search-content .btn-close', '.customer-review-search');
    closeOutsideHandle('.link-customer-review-search, .customer-review-search', '.customer-review-search');
}
searchCusReviewHandle();
$scope.searchCustomereviews = {rows: $scope.itemsPerPage, current_page: $scope.currentPage, search: ""};
$scope.time = {};
$scope.time.start = moment().add(-90, 'days').format('MM/DD/YYYY');
$scope.time.end = moment().format('MM/DD/YYYY');
$scope.checkLoadMoreCustomerReview = false;
$scope.firstLoad = true;
$scope.setTime = false;
$scope.addCustomereviewsData = {};
$scope.editCustomereviewsData = {};
$scope.addCustomereviewsData.selectCustomer = [];
$scope.addCustomereviewsData.employee = [];
$scope.dataFilterLoaded = false;
$scope.dataCustomerReview = {};
$scope.dataCustomerReview.totalItems = 0;
$scope.dataCustomerReview.countCurrentItems = 0;

$scope.getReviews = function () {
    Reviews.getSelect().success(function (data) {
        $scope.reviews = data;
        $scope.firstLoad = false;
    });
    $scope.getAppointmentType();
}


$scope.getAppointmentType = function () {
    Customers.getAppointmentType().success(function (data) {
        $scope.appointmentgroups = data;
    });
}
$scope.getCustomereviews = function () {
    $scope.checkLoadMoreCustomerReview = false;
    $ionicLoading.show({template: templateLoading});
    dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupReviewmodal.tpl').success(function (results) {
        $scope.dataHtml.customerPopupReview = results;
        dataHtml.getTemplate('templates/dashboard/customers/customers/customerPopupReviewSearchmodal.tpl').success(function (results) {
            $scope.dataHtml.customerPopupReviewSearch = results;
        })
        $timeout(function () {
            $scope.getCustomereviewCore();

        }, 1)
    });
};

$scope.getCustomereviewCore = function () {
    $scope.showTarget('#customerPopupReview');
    $ionicLoading.show({template: templateLoading});
    $scope.searchCustomereviews.start_time = $('#start_time').html();
    $scope.searchCustomereviews.end_time = $('#end_time').html();
    $('#displayStartDate .day').html(moment($scope.searchCustomereviews.start_time, 'MM/DD/YYYY').format('DD'));
    $('#displayStartDate .month').html(moment($scope.searchCustomereviews.start_time, 'MM/DD/YYYY').format('MMMM'));
    $('#displayEndDate .day').html(moment($scope.searchCustomereviews.end_time, 'MM/DD/YYYY').format('DD'));
    $('#displayEndDate .month').html(moment($scope.searchCustomereviews.end_time, 'MM/DD/YYYY').format('MMMM'));
    $scope.searchCustomereviews.current_page = 1;
    Customereviews.getPaging($scope.searchCustomereviews).success(function (data) {
        if(data.status == false ){
            $cordovaToast.showLongCenter(data.msg);
        }
        else{
            $ionicLoading.hide();
            for (var i = 0; i < data.data.length; i++) {
                if (data.data[i].comments.length > 160) {
                    data.data[i].customereviewComment = data.data[i].comments.substring(0, 160) + '...';
                    data.data[i].popupcomment = true;
                } else {
                    data.data[i].customereviewComment = data.data[i].comments;
                    data.data[i].popupcomment = false;
                }
            }
            $scope.dataCustomerReview.totalItems = data.total_rows;
            $scope.dataCustomerReview.countCurrentItems = data.data.length;
            $scope.filterClientdata = data.data;
            data.data = _.sortBy(data.data, 'date').reverse();
            $scope.customereviews = _.groupBy(data.data, 'date');
            $timeout(function () {
                if (data.data.length != 0)
                    $scope.checkLoadMoreCustomerReview = true;
            }, 5000);
            request_notify_get_chat = true;
            $scope.setTime = true;
            if ($scope.firstLoad) {
                $scope.getReviews();
            }
            $ionicScrollDelegate.$getByHandle('scrollCustomerReview').resize();
            $ionicScrollDelegate.$getByHandle('scrollCustomerReview').scrollTop(true);
            var params = {
                search: ''
            };
            Customers.getSelect2(params).success(function (data) {
                $scope.rootDataCustomer = data;
            });
        }
        
    }).error(function (data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
    });
}

$scope.clearSearchCusReview = function () {
    $scope.searchCustomereviews.search = '';
    $scope.searchCustomereviews.current_page = 1;
    $scope.getCustomereviews();
}
$scope.keypressCusReview = function (delegate) {
    var keysByCode = [9, 16, 17, 18, 20, 27, 32, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 144];
    if ($scope.searchCustomereviews.search.keyCode >= 112 && $scope.searchCustomereviews.search.keyCode <= 123)
        return;
    if (keysByCode.indexOf($scope.searchCustomereviews.search.keyCode) > -1)
        return;
    $scope.coundown = 10;
    if ($scope.myTime != null)
        clearInterval($scope.myTime);
    $scope.downTimerCusReview();
};
$scope.downTimerCusReview = function (delegate) {
    $scope.myTime = setInterval(function () {
        $scope.coundown--;
        if ($scope.coundown <= 0) {
            $ionicLoading.show({
                template: templateLoading
            });
            $scope.searchCustomereviews.current_page = 1;
            $scope.getCustomereviews();
            $ionicScrollDelegate.$getByHandle(delegate).scrollTop();
            clearInterval($scope.myTime);
        }
    }, 100);
}
$scope.LoadMoreCustomerReview = function () {
    if (!$scope.checkLoadMoreCustomerReview)
        return;
    $scope.searchCustomereviews.current_page++;
    Customereviews.getPaging($scope.searchCustomereviews).success(function (data) {
        $scope.dataCustomerReview.countCurrentItems += data.data.length;
        if (data.data.length < $scope.itemsPerPage)
            $scope.checkLoadMoreCustomerReview = false;
        for (var i = 0; i < data.data.length; i++) {
            if (data.data[i].comments.length > 160) {
                data.data[i].customereviewComment = data.data[i].comments.substring(0, 160) + '...';
                data.data[i].popupcomment = true;
            } else {
                data.data[i].customereviewComment = data.data[i].comments;
                data.data[i].popupcomment = false;
            }
            $scope.filterClientdata.push(data.data[i]);
            $scope.totalCustomerReviews++;
        }

        data.data = _.sortBy(data.data, 'date').reverse();
        var tempData = _.groupBy(data.data, 'date');
        $scope.customereviews = Object.assign($scope.customereviews, tempData);

    })
    $timeout(function () {
        $scope.$broadcast('scroll.infiniteScrollComplete');
    }, 2000);
};
$scope.$watch('time.start', function (value) {
    if ($scope.setTime) {
        $('#start_time').html(moment(value).format('MM/DD/YYYY'));
        $scope.getCustomereviews();
    }
})
$scope.$watch('time.end', function (value) {
    if ($scope.setTime) {
        $('#end_time').html(moment(value).format('MM/DD/YYYY'));
        $scope.getCustomereviews();
    }
})

$scope.orderCustomerReview = function (predicate, check) {
    $scope.predicate = predicate;
    if (check == 'Oldest') {
        $scope.reverse = true;
    } else {
        $scope.reverse = false;
    }
    $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
    $scope.predicate = predicate;
};
$scope.filterCustomerReviewCustomer = function (query, type) {
    var returnValue = {
        items: []
    };
    var id = $scope.autocompleteList.customerReviewCustomerAdd;
    if (type != 'add') {
        id = $scope.autocompleteList.customerReviewCustomerEdit;
    }
    if (query.length > 0) {
        var params = {
            search: query
        };
        Customers.getSelect2(params).success(function (data) {
            $scope.rootDataCustomer = data;
            // console.log($scope.rootDataCustomer);
            $scope.rootDataCustomer.forEach(function (item) {
                item.fullName = item.first_name + ' ' + item.last_name + ',' + item.street + ',' + item.phone;
            })
            $scope.rootDataCustomer.forEach(function (item) {
                if (id.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);
                    }
                }
            });
        })
    } else if (query.length == 0 && $scope.rootDataCustomer.length > 0) {
        $scope.rootDataCustomer.forEach(function (item) {
            item.fullName = item.first_name + ' ' + item.last_name + ',' + item.street + ',' + item.phone;
        })
        $scope.rootDataCustomer.forEach(function (item) {
            if (id.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);
                }
            }
        });
    }
    return returnValue;
};
$scope.onSelectCustomerReviewCustomer = function (callback, type) {
    if (type == 'add') {
        $scope.addCustomereviewsData.selectCustomer = callback.item;
    } else {
        $scope.editCustomereviewsData.selectCustomer = callback.item;
    }
    $scope.Input_value.displayCustomerReviewCustomer = callback.item.first_name + ' ' + callback.item.last_name;
}
$scope.onRemoveCustomerReviewCustomer = function (callback, type) {
    if (type == 'add') {
        $scope.addCustomereviewsData.selectCustomer = {};
    } else {
        $scope.editCustomereviewsData.selectCustomer = {}
    }
    $scope.Input_value.displayCustomerReviewCustomer = '';
}
$scope.initialdisplayCustomerReviewEdit = "";
$scope.initialdisplayCustomerReviewAdd = "";
$scope.setValueForCustomerReviewCustomer = function (modelValue) {
    for (var i = 0; i < $scope.rootDataCustomer.length; i++) {
        if ($scope.rootDataCustomer[i].id == modelValue) {
            return $scope.rootDataCustomer[i];
        }
    }
    return {};
};

$scope.filterCustomerReviewEmployee = function (query, type) {
    var returnValue = {
        items: []
    };
    var id = $scope.autocompleteList.customerReviewEmployeeAdd;
    if (type != 'add') {
        id = $scope.autocompleteList.customerReviewEmployeeEdit;
    }
    $scope.autocompleteUser.forEach(function (item) {
        if (item.id != id) {
            if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                returnValue.items.push(item);
            } else if (item.id.indexOf(query) > -1) {
                returnValue.items.push(item);
            }
        }
    });
    return returnValue;
};
$scope.onSelectCustomerReviewEmployee = function (callback, type) {
    if (type == 'add') {
        $scope.addCustomereviewsData.employee = callback.item;
    } else {
        $scope.editCustomereviewsData.employee = callback.item;
    }
}
$scope.onRemoveCustomerReviewEmployee = function (callback, type) {
    if (type == 'add') {
        $scope.addCustomereviewsData.employee = {};
    } else {
        $scope.editCustomereviewsData.employee = {};
    }
}

$scope.initialDisplayEmployeeReviewAdd = [];
$scope.initialDisplayEmployeeReviewEdit = [];
$scope.setValueForCustomerReviewEmployee = function (modelValue) {
    for (var i = 0; i < $scope.autocompleteUser.length; i++) {
        if ($scope.autocompleteUser[i].id == modelValue) {
            return $scope.autocompleteUser[i];
        }
    }
    return {};
};
$scope.createCustomereviews = function () {
    if (!$scope.addCustomereviewsData.selectCustomer.id || !$scope.addCustomereviewsData.employee.id || !$scope.addCustomereviewsData.review_id || !$scope.addCustomereviewsData.comments || !$scope.addCustomereviewsData.rating) {
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    }
    $scope.addCustomereviewsData.dateShow = $("#customerReviewDateAdd").html();
    $scope.addCustomereviewsData.date = moment($scope.addCustomereviewsData.dateShow, 'MM/DD/YYYY').format('YYYY-MM-DD');
    $scope.addCustomereviewsData.customer_id = $scope.addCustomereviewsData.selectCustomer.id;
    $scope.addCustomereviewsData.employee_id = $scope.addCustomereviewsData.employee.id;
    $ionicLoading.show({template: templateLoading});
    Customereviews.save($scope.addCustomereviewsData).success(function (data) {
        $ionicLoading.hide();
        $scope.closeTarget('#customerPopupReviewAdd');
        if (data.status) {
            $('#start_time').html(moment($("#customerReviewDateAdd").html(), "MM/DD/YYYY").add(-90, "days").format("MM/DD/YYYY"));
            $('#end_time').html(moment($("#customerReviewDateAdd").html(), "MM/DD/YYYY").format("MM/DD/YYYY"));
            $scope.getCustomereviews();
            $scope.addCustomereviewsData = {};
            $scope.addCustomereviewsData.selectCustomer = {};
            $scope.addCustomereviewsData.employee = {};
            $scope.Input_value.displayCustomerReviewCustomer = "";
            $scope.Input_value.review = "";
            $scope.initialdisplayCustomerReviewAdd = [];
            $scope.initialDisplayEmployeeReviewAdd = [];
            $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.editCustomereviews = function (id) {
    $scope.openByGetTemplate('customerPopupReviewEdit');
    $ionicLoading.show({template: templateLoading});
    Customereviews.show(id).success(function (data) {
        $scope.editCustomereviewsData = data;
        $scope.setValueReviewInput($scope.editCustomereviewsData.review_id);
        $scope.initialDisplayEmployeeReviewEdit = $scope.editCustomereviewsData.employee.id;
        $ionicLoading.hide();
        var params = {
            search: $scope.editCustomereviewsData.selectCustomer.first_name
        };
        Customers.getSelect2(params).success(function (data) {
            $scope.rootDataCustomer = data;
            $scope.initialdisplayCustomerReviewEdit = $scope.editCustomereviewsData.selectCustomer.id;
        });
    }).error(function (data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
    });
}
$scope.updateCustomereviews = function () {
    if (!$scope.editCustomereviewsData.selectCustomer.id || !$scope.editCustomereviewsData.employee.id || !$scope.editCustomereviewsData.review_id || !$scope.editCustomereviewsData.comments || !$scope.editCustomereviewsData.rating) {
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    }
    $scope.editCustomereviewsData.dateShow = $("#customerReviewDateEdit").html();
    $scope.editCustomereviewsData.date = moment($scope.editCustomereviewsData.dateShow, 'MM/DD/YYYY').format('YYYY-MM-DD');
    $scope.editCustomereviewsData.customer_id = $scope.editCustomereviewsData.selectCustomer.id;
    $scope.editCustomereviewsData.employee_id = $scope.editCustomereviewsData.employee.id;
    $ionicLoading.show({template: templateLoading});
    Customereviews.update($scope.editCustomereviewsData.id, $scope.editCustomereviewsData).success(function (data) {
        $ionicLoading.hide();
        $scope.closeTarget('#customerPopupReviewEdit');
        if (data.status) {
            $('#start_time').html(moment($("#customerReviewDateEdit").html(), "MM/DD/YYYY").add(-30, "days").format("MM/DD/YYYY"));
            $('#end_time').html(moment($("#customerReviewDateEdit").html(), "MM/DD/YYYY").format("MM/DD/YYYY"));
            $scope.getCustomereviews();
            $scope.editCustomereviewsData = {};
            $scope.editCustomereviewsData.selectCustomer = {};
            $scope.editCustomereviewsData.employee = {};
            $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.confrimCustomereviews = function (id, key) {
    $scope.deleteCustomereviewsData = {id: id, key: key};
    $scope.openByGetTemplate('customerPopupReviewDelete');
}
$scope.deleteCustomereviews = function () {
    $ionicLoading.show({
        template: templateLoading
    });
    Customereviews.destroy($scope.deleteCustomereviewsData.id).success(function (data) {
        $ionicLoading.hide();
        $scope.closeTarget('#customerPopupReviewDelete');
        var idx = _.findIndex($scope.customereviews[$scope.deleteCustomereviewsData.key], {id: $scope.deleteCustomereviewsData.id});
        $scope.customereviews[$scope.deleteCustomereviewsData.key].splice(idx, 1);
        if ($scope.customereviews[$scope.deleteCustomereviewsData.key].length == 0)
            delete $scope.customereviews[$scope.deleteCustomereviewsData.key];
        $scope.deleteCustomereviewsData = {};
        if (data.status) {
            $cordovaToast.showLongTop(data.msg);
        } else {
            $cordovaToast.showLongTop(data.msg);
        }
// $scope.getCustomereviews();
}).error(function (data, status, headers, config) {
    $ionicLoading.hide();
    console.log('error status: ' + status);
    $cordovaToast.showLongTop('Connection Error!!!');
});
}
$scope.getDataFilter = function () {
    $scope.openByGetTemplate('customerPopupReviewFilter');
    if (!$scope.dataFilterLoaded) {
        $ionicLoading.show({template: templateLoading});
        Reviews.getSelectFilter().success(function (data) {
            $ionicLoading.hide();
                $scope.reviewTitle = data.review;//$scope.initNode('Reviews', data.review);
                $scope.employeeTitle = data.employee;//$scope.initNode('Employee', );
                $scope.dataFilterLoaded = true;
            });
    }
}
$scope.initNode = function (lblRoot, objChild) {
    var _node = [];
    _node = [{
        label: lblRoot,
        selected: true,
        children: []
    }];
    for (var i = 0; i < objChild.length; i++) {
        var _item = {
            label: objChild[i].name,
            selected: true
        };
        _.where(_node[0].children, {
            label: _item.label
        }).length == 0 ? _node[0].children.push(_item) : '';
    }
    return _node;
}
$scope.getfilterClient = function () {
    $scope.searchCustomereviews.reviews = $scope.reviewFilter.source ? $scope.reviewFilter.source : [];
    $scope.searchCustomereviews.employees = $scope.reviewFilter.employees ? $scope.reviewFilter.employees : [];
    $scope.searchCustomereviews.current_page = 1;
    $scope.getCustomereviewCore();
    $scope.closeTarget('#customerPopupReviewFilter');
}
$scope.changeCallback = function (node, forFilter) {
    var __where = _.where(node[0].children, {
        selected: true
    });
    var __filter = new Array();
    for (var i = 0; i < __where.length; i++) {
        __filter = _.union(__filter, _.filter($scope.filterClientdata, function (item) {
            if (forFilter == 1) {
                return item.reviewName === __where[i]['label'];
            } else {
                return item.empName === __where[i]['label'];
            }
        }));
    }
    return _.intersection($scope.filterClientdata, __filter);
}
$scope.resetFilter = function () {
    $('input[name=sort]').attr('checked', false);
    $scope.orderCustomerReview('', '');
    ivhTreeviewMgr.selectAll($scope.reviewTitle);
    ivhTreeviewMgr.selectAll($scope.employeeTitle);
    $scope.searchCustomereviews = {rows: $scope.itemsPerPage, current_page: $scope.currentPage, search: ""};
    $scope.getCustomereviews();
    $scope.closeTarget('#customerPopupReviewFilter');
}

$scope.beforeSaveQuery = function () {
    $scope.submitTypeFilter('Save');
    openPopup('#inputnamequery');
};

$scope.submitTypeFilter = function (action) {
    $scope.submitType = action;
};
$scope.exportdata = {};
$scope.exportdatafilter = {};
$scope.exportdata.refferedcustomer = [];
$scope.exportdata.appointmentType = [];
$scope.submitFomFiter = function () {
    $scope.exportdata.actionType = $scope.submitType;
    if ($scope.exportdata.actionType == 'Delete') {
        $scope.exportdata = {};
        $scope.exportdata.actionType = 'Delete';
        $scope.exportdata.queryId = $scope.queryId;
    } else {
        if ($scope.exportdata.actionType == 'Display') {
            $scope.isFilterExport = true;
            $scope.searchCustomers.search = '';
            $scope.exportdata.rows = $scope.searchCustomers.rows;
            $scope.exportdata.current_page = 1;
        }
    }
    $scope.rebuildFilter();
    if(!$scope.continueFilter){
        return;
    }
    $scope.customerFilterData($scope.exportdata);

}
$scope.customerFilterData = function (params) {
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.filter(params).success(function (data) {
        $scope.closeTarget('#customerPopupFilterReport')
        $ionicLoading.hide();
        switch ($scope.submitType) {
            case 'Display':
            if (data.data.length < $scope.itemsPerPage)
                $scope.checkLoadMore = false;
            $scope.isFilterCusomer=true;
            var dataCustomers = $scope.parseDate(data.data)
            _.each(dataCustomers, function (val) {
                var f = Date.parseDate(val.lastservicedate);
                val.lastservicedate = globalParseDate(f);
                val.customer_name = val.first_name + ' ' + val.last_name;
                $scope.autocompleteCustomer.push({
                    id: val.id,
                    name: val.customer_name
                });
            })
            if (params.current_page == 1) {
                $scope.customers = dataCustomers;
            } else {
                $scope.customers = arrayUnion($scope.customers, dataCustomers, function (item1, item2) {
                    return item1.id == item2.id;
                });
            }
            break;
            case 'Export':
            $scope.submitType = 'Display';
            var publicPos = url_site.indexOf("public");
            if(publicPos>-1){
                var link = data.link.replace('./../', url_site.replace('public', ''));
            }
            else{
                var link = data.link.replace('./../','');
                link = url_site+'/'+link;
            }
            $scope.cordovaBrowser(link, 'internal');
            break;
            case 'Save':
            $scope.getcustomerqueries();
            $scope.queryId = data.insertedid;
            closePopupById('inputnamequery');
            openPopup('#filterandreport');
            $cordovaToast.showLongTop(data.msg);
            break;
            case 'Delete':
            $scope.getcustomerqueries();
            $scope.queryId = 'new';
            $cordovaToast.showLongTop(data.msg);
            break;
        }
    }).error(function (data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
    });
}

$scope.rebuildFilter = function () {
    $scope.continueFilter = true;
    if($scope.exportdatafilter.companyName!=undefined && $scope.exportdatafilter.companyName!=''){
        $scope.exportdata.companyName = {company_name:$scope.exportdatafilter.companyName};
    }

    if($scope.exportdatafilter.city != undefined){
        $scope.exportdata.city = getArrayAutocompelte($scope.dataFilterCity, $scope.exportdatafilter.city, "city");
    }else{
        delete $scope.exportdata.city;
    }

    if($scope.exportdatafilter.zip != undefined){
        $scope.exportdata.zip = getArrayAutocompelte($scope.dataFilterZipcodeDetail, $scope.exportdatafilter.zip, "postal_code");
    }
    else{
        delete $scope.exportdata.zip;
    }

    if($scope.exportdatafilter.customerSince_start != undefined && $scope.exportdatafilter.customerSince_end!=undefined){
        $scope.exportdata.customerSince = moment($scope.exportdatafilter.customerSince_start).format('MM/DD/YYYY')+' - '+moment($scope.exportdatafilter.customerSince_end).format('MM/DD/YYYY');
    }
    else{
        if($scope.exportdatafilter.customerSince_start == undefined && $scope.exportdatafilter.customerSince_end == undefined){
            delete $scope.exportdata.customerSince;
        }
        else{
            $cordovaToast.showLongTop('Please input both start date and end date.');
            $scope.continueFilter = false;
            return;
        }
    }

    if($scope.exportdatafilter.leadSource){
        $scope.exportdata.leadSource = $scope.exportdatafilter.leadSource.id;
    }
    else{
        delete $scope.exportdata.leadSource;
    }
    
    if($scope.exportdatafilter.refferedcustomer == undefined){
        $scope.exportdata.refferedcustomer = {};
    }
    else{
        $scope.exportdata.refferedcustomer = $scope.exportdatafilter.refferedcustomer;
    }

    if($scope.exportdatafilter.lastService_start != undefined && $scope.exportdatafilter.lastService_end!=undefined){
        $scope.exportdata.lastService = moment($scope.exportdatafilter.lastService_start).format('MM/DD/YYYY')+' - '+moment($scope.exportdatafilter.lastService_end).format('MM/DD/YYYY');
    }
    else{
        if($scope.exportdatafilter.lastService_start == undefined && $scope.exportdatafilter.lastService_end==undefined){
            delete $scope.exportdata.lastService;
        }
        else{
            $cordovaToast.showLongTop('Please input both start date and end date.');
            $scope.continueFilter = false;
            return;
        } 
    }

    $scope.exportdata.state = $scope.exportdatafilter.state;
    $scope.exportdata.lastFieldWorker = $scope.autocompleteListData.fieldworker;
    $scope.exportdata.customerReview = $scope.exportdatafilter.customerReview;
    $scope.exportdata.appointmentType = $scope.autocompleteListData.appointmentType;
    $scope.exportdata.customerFlag = $scope.exportdatafilter.customerFlag;
    $scope.exportdata.jobsiteExist = $scope.exportdatafilter.jobsiteExist;
}

function getArrayAutocompelte(source, hash, key) {
    if (!hash) return null;
    var array = [];
    for (var i = 0; i < hash.length; i++) {
        var item = hash[i];
        for (var j = 0; j < source.length; j++) {
            var item2 = source[j];
            if (item2[key] == item) {
                array.push(item2);
            }
        }
        ;
    }
    ;

    return array;
}

function getObjectAutocompelte(source, hash, key) {


    for (var j = 0; j < source.length; j++) {
        var item2 = source[j];
        if (item2[key] == hash) {
            return item2;
        }
    }
    ;

    return {};
}



$scope.getcustomerqueries = function () {
    Customers.getcustomerqueries().success(function (data) {
        $scope.dataCusQuery = data;
    })
};
//-------------------------------City---------------------------
$scope.filterCitySearch = function (query) {
    var returnValue = {
        items: []
    };
    $scope.dataFilterCity.forEach(function (item) {
        if (item.city.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            if ($scope.exportdatafilter.city && $scope.exportdatafilter.city.indexOf(item.id) < 0) {
                returnValue.items.push(item);
            } else if (!$scope.exportdatafilter.city) {
                returnValue.items.push(item);
            }

        }
    });
    return returnValue;
}

$scope.filterCitySearchClicked = function (callback) {

}


$scope.filterCitySearchRemoved = function (callback) {

}


//--------------------------------------------------------------------- 
//-------------------------------Zip---------------------------
$scope.filterZipSearch = function (query) {
    var returnValue = {
        items: []
    };

    $scope.dataFilterZipcodeDetail.forEach(function (item) {
        if (item.postal_code.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            if ($scope.exportdatafilter.zip && $scope.exportdatafilter.zip.indexOf(item.postal_code) < 0) {
                returnValue.items.push(item);
            } else if (!$scope.exportdatafilter.zip) {
                returnValue.items.push(item);
            }

        }
    });
    return returnValue;
}

$scope.filterZipSearchClicked = function (callback) {

}


$scope.filterZipSearchRemoved = function (callback) {

}

//--------------------------------------------------------------------- 
//-------------------------------Refferedcustomer---------------------------
$scope.filterRefferedcustomerSearch = function (query) {
    var returnValue = {
        items: []
    };
    $scope.allUser.forEach(function (item) {
        if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            if ($scope.exportdatafilter.refferedcustomer && $scope.exportdatafilter.refferedcustomer.indexOf(item.id) < 0) {
                returnValue.items.push(item);
            } else if (!$scope.exportdatafilter.refferedcustomer) {
                returnValue.items.push(item);
            }

        }
    });
    return returnValue;
}

$scope.filterRefferedcustomerSearchClicked = function (callback) {

}


$scope.filterRefferedcustomerSearchRemoved = function (callback) {

}

//--------------------------------------------------------------------- 
//-------------------------------LastFieldWorker---------------------------
$scope.filterLastFieldWorkerSearch = function (query) {
    var returnValue = {
        items: []
    };
    $scope.lastfieldwors.forEach(function (item) {
        if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            if ($scope.exportdatafilter.lastFieldWorker && $scope.exportdatafilter.lastFieldWorker.indexOf(item.id) < 0) {
                returnValue.items.push(item);
            } else if (!$scope.exportdatafilter.lastFieldWorker) {
                returnValue.items.push(item);
            }

        }
    });
    return returnValue;
}

$scope.filterLastFieldWorkerSearchClicked = function (callback) {
    $scope.autocompleteListData.fieldworker = callback.selectedItems;
}


$scope.filterLastFieldWorkerSearchRemoved = function (callback) {
    $scope.autocompleteListData.fieldworker = callback.selectedItems;
}

//--------------------------------------------------------------------- 
    /*$scope.refreshcompanyNamesonfilter = function(search){
     if (search.length > 0) {
     var params = {
     search: search
     };
     Customers.getCompanyName(params).success(function(res) {
     var diff = differentArray(res.data, $scope.editCustomersData.companyName);
     $scope.companyNameSelectFilter = diff;
     })
     } else {
     $scope.companyNameSelectFilter = [];
     }
 }*/
//-------------------------------CompanyName---------------------------

$scope.filterCompanyNameSearch = function (query) {
    var returnValue = {
        items: []
    };

    var params = {
        search: query ? querry : ''
    };
    $ionicLoading.show({template: templateLoading});
    Customers.getCompanyName(params).success(function (res) {

        res.data.forEach(function (item) {
            if (item.company_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                if ($scope.exportdatafilter.companyName && $scope.exportdatafilter.companyName.indexOf(item.id) < 0) {
                    returnValue.items.push(item);
                } else if (!$scope.exportdatafilter.companyName) {
                    returnValue.items.push(item);
                }

            }
        });
        $timeout(function () {
            $ionicLoading.hide();
        }, 1000)

    })


    return returnValue;
}

$scope.filterCompanyNameSearchClicked = function (callback) {

}


$scope.filterCompanyNameSearchRemoved = function (callback) {

}

$scope.modelToItemCompanyName = function (modelValue) {
        //var modelItem = getModelItem(modelValue);
        return modelValue;
    }


//--------------------------------------------------------------------- 
//-------------------------------AppointmentType---------------------------
$scope.filterAppointmentTypeSearch = function (query) {
    var returnValue = {
        items: []
    };
    $scope.appointmentgroups.forEach(function (item) {
        if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            if ($scope.exportdatafilter.appointmentType && $scope.exportdatafilter.appointmentType.indexOf(item.id) < 0) {
                returnValue.items.push(item);
            } else if (!$scope.exportdatafilter.appointmentType) {
                returnValue.items.push(item);
            }

        }
    });
    return returnValue;
}

$scope.filterAppointmentTypeSearchClicked = function (callback) {
    $scope.autocompleteListData.appointmentType = callback.selectedItems;
}


$scope.filterAppointmentTypeSearchRemoved = function (callback) {
    $scope.autocompleteListData.appointmentType = callback.selectedItems;
}


//---------------------------------------------------------------------


//-------------------------------Source---------------------------
$scope.filterSourceSearch = function (query) {
    var returnValue = {
        items: []
    };
    $scope.reviewTitle.forEach(function (item) {
        if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            if ($scope.reviewFilter.source && $scope.reviewFilter.source.indexOf(item.id) < 0) {
                returnValue.items.push(item);
            } else if (!$scope.reviewFilter.source) {
                returnValue.items.push(item);
            }

        }
    });
    return returnValue;
}

$scope.filterSourceSearchClicked = function (callback) {

}


$scope.filterSourceSearchRemoved = function (callback) {

}

//--------------------------------------------------------------------- 
//-------------------------------Employees---------------------------
$scope.filterEmployeesSearch = function (query) {
    var returnValue = {
        items: []
    };
    $scope.employeeTitle.forEach(function (item) {
        if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            if ($scope.reviewFilter.employees && $scope.reviewFilter.employees.indexOf(item.id) < 0) {
                returnValue.items.push(item);
            } else if (!$scope.reviewFilter.employees) {
                returnValue.items.push(item);
            }

        }
    });
    return returnValue;
}

$scope.filterEmployeesSearchClicked = function (callback) {

}


$scope.filterEmployeesSearchRemoved = function (callback) {

}

$scope.converArrayToObj = function (data) {
    var array = [];
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        array.push({id: item});
    }
    ;
    return array;
}

$scope.hrefToViewSchedule = function() {
    switch ($scope.roleName) {
        //saleman
        case $scope.isSalesman:
        $scope.locationGetSchedule = "myschedule.html";
        break;
        //fieldinstaller
        case $scope.isFieldinstaller:
        $scope.locationGetSchedule = "myschedule.html";
        break;
        //admin
        case $scope.isAdmin:
        $scope.locationGetSchedule = "scheduleapp.html";
        break;
        case $scope.isStrategicDevelopment:
        $scope.locationGetSchedule = "scheduleapp.html";
        break;
        //manager
        case $scope.isManager:
        $scope.locationGetSchedule = "scheduleapp.html";
        break;
        //isReporter
        case $scope.isReporter:
        $scope.locationGetSchedule = "scheduleapp.html";
        break;
        //isScheduler
        case $scope.isScheduler:
        $scope.locationGetSchedule = "scheduleapp.html";
        break;
        case $scope.isWarehouse:
        $scope.locationGetSchedule = "scheduleapp.html";
        break;
        case $scope.isSupportAssistant:
        $scope.locationGetSchedule = "scheduleapp.html";
        break;
        case $scope.isOutsideSales:
        $scope.locationGetSchedule = "scheduleapp.html";
        break;
        case $scope.isInFieldSupervisor:
        $scope.locationGetSchedule = "scheduleapp.html";
        break;
    }
}

$scope.hrefToViewSchedule();

$scope.openPopupReviewAdd = function(){
    $scope.editCustomereviewsData = {};
    $scope.addCustomereviewsData.selectCustomer = [];
    $scope.addCustomereviewsData.employee = [];
    $scope.Input_value.review = '';
    $scope.initialdisplayCustomerReviewAdd = [];
    $scope.autocompleteList.customerReviewCustomerAdd = [];
    $scope.Input_value.displayCustomerReviewCustomerAdd = '';
    $scope.openByGetTemplate('customerPopupReviewAdd');
}

$scope.checkAdditionalPhoneCustomer = function(action){
    if(action == 'edit' ){
        if($scope.editCustomersData.phone && $scope.editCustomersData.phone.length){
            var checkDuplicate = $scope.checkDuplicatePhone($scope.editCustomersData.phone);
            if(checkDuplicate){
                $cordovaToast.showLongTop('Additional Phone Number Duplicate !');
                return;
            }
        }
    }
    if(action == 'add' ){
        if($scope.addCustomersData.phone && $scope.addCustomersData.phone.length){
            var checkDuplicate = $scope.checkDuplicatePhone($scope.addCustomersData.phone);
            if(checkDuplicate){
                $cordovaToast.showLongTop('Additional Phone Number Duplicate !');
                return;
            }
        }
    }
    $ionicLoading.show({template: templateLoading});
    $scope.actionCheckAdditionalPhone = action;
    switch(action){
        case 'add':
        var customerId = 0;
        var customerAdditionalPhones = $scope.addCustomersData.phone;
        break;
        case 'edit':
        var customerId = $scope.editCustomersData.dataCustomer.id;
        var customerAdditionalPhones = $scope.editCustomersData.phone;
        break;
    }
    if(customerAdditionalPhones.length > 0 && customerAdditionalPhones[0].phone != ''){
        Customers.checkAdditionalPhone(customerId,customerAdditionalPhones).success(function(result){
            $ionicLoading.hide();
            if(result.status == false){
                $cordovaToast.showLongTop(result.msg);
            }
            else{
                if(result.data.length > 0){
                    $scope.listCustomersPhonesDup = result.data;
                    $scope.openByGetTemplate('popupCheckAdditionalPhones');
                }else{
                    $scope.actionCreateUpdate(action);
                }
            }
        });
    }else{
        $scope.actionCreateUpdate(action);
    }
}

$scope.actionCreateUpdate = function(action){
    switch(action){
        case 'add':
        $scope.createCustomers();
        break;
        case 'edit':
        $scope.updateCustomers();
        break;
    }
    $scope.closeTarget('#popupCheckAdditionalPhones');
}

$scope.confirmationAction = function(){
    $scope.actionCreateUpdate($scope.actionCheckAdditionalPhone);
}

$scope.selectAddress = function(value,type) {
    if(type == 'add'){
        if($scope.addCustomersData.addStreet.length>0){
            $scope.addCustomersData.addStreet.splice(0,1);
        }
    }
    if(type == 'edit'){
        if($scope.editCustomersData.dataCustomer.addStreet.length>0){
            $scope.editCustomersData.dataCustomer.addStreet.splice(0,1);
        }
    }
    if(type == 'jobsite'){
        if($scope.dataEditJobsite.addStreet.length>0){
            $scope.dataEditJobsite.addStreet.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 == 'add'){
            data['locality'] ? $scope.addCustomersData.city = data['locality'] : $scope.addCustomersData.city = '';
            data['administrative_area_level_1'] ? $scope.addCustomersData.state = data['administrative_area_level_1'] : $scope.addCustomersData.state = '';
            data['postal_code'] ? $scope.addCustomersData.zipcode = data['postal_code'] : $scope.addCustomersData.zipcode = '' ;
            $scope.addCustomersData.street = location.formatted_address;
            $('#formAddCustomer #street').val(location.formatted_address);
        }
        if(type == 'edit'){
            data['locality'] ? $scope.editCustomersData.dataCustomer.city = data['locality'] : $scope.editCustomersData.dataCustomer.city ='';
            data['administrative_area_level_1'] ? $scope.editCustomersData.dataCustomer.state = data['administrative_area_level_1'] : $scope.editCustomersData.dataCustomer.state = '';
            data['postal_code'] ? $scope.editCustomersData.dataCustomer.zipcode = data['postal_code'] : $scope.editCustomersData.dataCustomer.zipcode = '';
            $scope.editCustomersData.dataCustomer.street = location.formatted_address;
            $('#formEditCustomer #street').val(location.formatted_address);
        }
        if(type == 'jobsite'){
            data['locality'] ? $scope.dataEditJobsite.city = data['locality'] : $scope.dataEditJobsite.city ='';
            data['administrative_area_level_1'] ? $scope.dataEditJobsite.state = data['administrative_area_level_1'] : $scope.dataEditJobsite.state = '';
            data['postal_code'] ? $scope.dataEditJobsite.zipcode = data['postal_code'] : $scope.dataEditJobsite.zipcode = '';
            $scope.dataEditJobsite.street = location.formatted_address;
        }
    })
};

$scope.selectAddressJobsite = function(value,type) {
    if(type=='add'){
        console.log($scope.dataAddJobsite);
        if($scope.dataAddJobsite.street.length>0){
            $scope.dataAddJobsite.street.splice(0,1);
        }
    }
    if(type=='edit'){
        if($scope.editCustomersData.jobsite[index].street.length>0){
            $scope.editCustomersData.jobsite[index].street.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=='add'){
            data['locality'] ? $scope.dataAddJobsite.city = data['locality'] : $scope.dataAddJobsite.city = '' ;
            data['administrative_area_level_1'] ? $scope.dataAddJobsite.state = data['administrative_area_level_1'] : $scope.dataAddJobsite.state = '';
            data['postal_code'] ? $scope.dataAddJobsite.zipcode = data['postal_code'] : $scope.dataAddJobsite.zipcode = '';
            $scope.dataAddJobsite.streetValue = location.formatted_address;
        }
        if(type=='edit'){
            data['locality'] ? $scope.editCustomersData.jobsite[index].city = data['locality'] : $scope.editCustomersData.jobsite[index].city = '';
            data['administrative_area_level_1'] ? $scope.editCustomersData.jobsite[index].state = data['administrative_area_level_1'] : $scope.editCustomersData.jobsite[index].state = '';
            data['postal_code'] ? $scope.editCustomersData.jobsite[index].zipcode = data['postal_code'] : $scope.editCustomersData.jobsite[index].zipcode = '';
            $scope.editCustomersData.jobsite[index].streetValue = location.formatted_address;
        }
    })
};

$scope.removetag = function(value,type) {
    if(type == 'add'){
        $scope.addCustomersData.city = '';
        $scope.addCustomersData.state = '';
        $scope.addCustomersData.zipcode = '';
        $scope.addCustomersData.street = '';
        $scope.addCustomersData.addStreet = [];
    }
    if(type == 'edit'){
        $scope.editCustomersData.dataCustomer.city = '';
        $scope.editCustomersData.dataCustomer.state = '';
        $scope.editCustomersData.dataCustomer.zipcode = '';
        $scope.editCustomersData.dataCustomer.street = '';
        $scope.editCustomersData.dataCustomer.addStreet = [];
    }
    if(type == 'jobsite'){
        $scope.dataEditJobsite.city = '';
        $scope.dataEditJobsite.state = '';
        $scope.dataEditJobsite.zipcode = '';
        $scope.dataEditJobsite.street = '';
        $scope.dataEditJobsite.addStreet = [];
    }
};

$scope.removetagJobsite = function(value,index,type) {
    if(type == 'add'){
        $scope.addCustomersData.jobsite[index].city = '';
        $scope.addCustomersData.jobsite[index].state = '';
        $scope.addCustomersData.jobsite[index].zipcode = '';
        $scope.addCustomersData.jobsite[index].streetValue = ''; 
        $scope.addCustomersData.jobsite[index].street = [];
    }
    if(type == 'edit'){
        $scope.editCustomersData.jobsite[index].city = '';
        $scope.editCustomersData.jobsite[index].state = '';
        $scope.editCustomersData.jobsite[index].zipcode = '';
        $scope.editCustomersData.jobsite[index].streetValue = '';
        $scope.editCustomersData.jobsite[index].street = [];
    }
};

$scope.checkDuplicatePhone = function(arrPhone) {
    var arr =  _.pluck(arrPhone, 'phone');
    return arr.length != _.uniq(arr).length;
};

$scope.sortAppHistory = function(data) {
    var arrTBD = _.filter(data, function(app){ 
        return app.dateofappt == "TBD"; 
    });
    var arrNoneTBD = _.filter(data, function(app){ 
        return app.dateofappt != "TBD"; 
    });
    var sum = arrTBD.concat(arrNoneTBD);
    return sum;
}

$scope.openPopupAddJobsite = function() {
    $scope.dataAddJobsite = {};
    $scope.dataAddJobsite.street = [];
    $scope.openByGetTemplate('addJobsiteModal');
}

$scope.validateForm_Jobsite = function (formValidate, style) {
    var exitLoop = false;
    if (formValidate.$invalid) {
        $ionicScrollDelegate.$getByHandle('scrollJobsite' + style).scrollTop();
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    }
    if (style == 'Add') {
        $scope.createJobsites();
    } else {
        $scope.updateJobsites();
    }
}

$scope.createJobsites = function() {
    $ionicLoading.show({template: templateLoading});
    $scope.dataAddJobsiteCopy = angular.copy($scope.dataAddJobsite);
    $scope.dataAddJobsiteCopy.customer_id = $scope.current_jobsite_customer_id ;
    $scope.dataAddJobsiteCopy.street = $scope.dataAddJobsiteCopy.streetValue;
    delete $scope.dataAddJobsiteCopy.streetValue;
    Customers.addJobsite($scope.dataAddJobsiteCopy).success(function(data) {
        $ionicLoading.hide();
        if(data.status == false){
            $cordovaToast.showLongTop(data.msg);
        }else{
            $cordovaToast.showLongTop(data.msg);
            closeTarget('#addJobsiteModal');
            $scope.loadJobsiteByCustomerId($scope.current_jobsite_customer_id);
        }
    })
};

$scope.getJobsiteById = function(id) {
    $scope.openByGetTemplate('customerPopupJobsiteEdit');
    $ionicLoading.show({template: templateLoading});
    Customers.getJobsiteById(id).success(function (data) {
        if($scope.click_jobsite_form == 'lists'){
            $scope.current_customer = _.where($scope.customers, {
                id: $scope.current_jobsite_customer_id
            })[0];
        }else{
            $scope.current_customer = $scope.customerDetail;
        }
        $scope.dataEditJobsite = data;
        $scope.dataEditJobsite.addStreet = [{place_id:'',description:$scope.dataEditJobsite.street}];
        $ionicLoading.hide();
    });
};

$scope.editJobsites = function (id) {
    $scope.openByGetTemplate('customerPopupJobsiteEdit');
    $ionicLoading.show({template: templateLoading});
    Jobsites.show(id).success(function (data) {
        $scope.dataEditJobsite = data;
        $scope.dataEditJobsite.addStreet = [{place_id:'',description:$scope.dataEditJobsite.street}];
        $ionicLoading.hide();
    });
}

$scope.updateJobsites = function () {
    $scope.dataEditJobsiteCopy = angular.copy($scope.dataEditJobsite);
    delete $scope.dataEditJobsiteCopy.addStreet;
    var id = $scope.dataEditJobsiteCopy.id;
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.updateJobsite($scope.dataEditJobsiteCopy).success(function (data) {
        $ionicLoading.hide();
        if (data.status) {
            var idx = _.findLastIndex($scope.tableJobsiter, {id: $scope.dataEditJobsite.id});
            $scope.tableJobsiter[idx] = $scope.dataEditJobsite;
            $scope.dataEditJobsite = {};
            $scope.closeTarget('#customerPopupJobsiteEdit');
            $cordovaToast.showLongTop(data.msg);
            $scope.loadJobsiteByCustomerId($scope.current_jobsite_customer_id);
        } else {
            $cordovaToast.showLongTop(data.msg);
        }
    });
}

$scope.confirmDeleteJobsite = function (id, label, status) {
    $scope.openByGetTemplate('customerPopupJobsiteDelete');
    $scope.jobsiteInfo = {};
    $scope.jobsiteInfo.id = id;
    $scope.jobsiteInfo.label = label;
    $scope.jobsiteInfo.status = status;
}

$scope.deleteJobsite = function(id,status) {
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.activeAndInactiveJobsite(id, status).success(function(data) {
        $ionicLoading.hide();
        $scope.closeTarget('#customerPopupJobsiteDelete');
        $cordovaToast.showLongTop(data.msg);
        $scope.loadJobsiteByCustomerId($scope.current_jobsite_customer_id);
    });
}

$scope.viewJobsiteHistory = function(history) {
    $scope.jobsiteHistory = history;
    $scope.openByGetTemplate('jobsiteLogModal');
    
}

$scope.showsInActiveCustomersJobiste = function (show) {
    $scope.searchCustomerJobsite.show = show;
    switch(show){
        case 'all':
        $scope.customerJobsiteShow = 'All';
        break;
        case 'active':
        $scope.customerJobsiteShow = 'Active';
        break;
        case 'inactive':
        $scope.customerJobsiteShow = 'Deactivated';
        break;
    }
    $scope.closeTarget('#popupCustomerFilterJobsite');
    $scope.loadJobsiteByCustomerId($scope.current_jobsite_customer_id);
}

$scope.loadCreditCard = function(opentable) {
    $ionicLoading.show({
        template: templateLoading
    });
    $scope.searchCustomers.customer_id = $scope.customerDetail.id;
    Customers.loadCreditCard($scope.searchCustomers).success(function(data) {
        $scope.creditcards = data.creditcards;
        $scope.dataInstoreCredit = data.instorecredits;
        $scope.total_instorecredit = '$'+data.total_instorecredit;
        $scope.currentPage = data.page;
        $scope.itemsPerPage = $scope.searchCustomers.rows;
        customers_pagesize.val($scope.itemsPerPage);
        $scope.totalItems = data.total_rows;


        if(opentable){
            $scope.openByGetTemplate('customerPopupCreditCard');
        }
        $ionicLoading.hide();
    });
};

$scope.openPopupAddCreditCard = function() {
    $scope.addCreditCardData = {};
    $scope.openByGetTemplate('customerDetailAddCreditCard');
}

$scope.requirednumber = function (value) {
    if (!value)
        return 0;
    if (value.length == 0) {
        value = 0;
    }
    value = parseInt(value.toString().replace(/[^0-9]/g, ''));
    if (isNaN(value) == true) {
        value = 0;
    }
    return value;
};
$scope.checkCardNumberAddCreditCard = function (value) {
    $scope.addCreditCardData.card_number = $scope.requirednumber(value);
    angular.element('#card_number_form_add').validateCreditCard(function (result) {
        if (result.valid == true && result.length_valid == true && result.luhn_valid == true) {
            $('.logs').html(result.card_type.name + '<img class="icon_opportunities" src="resources/images/icons/checked-form-2-green.png" style="width:20px" />');
            $scope.accept_this_card_add = true;
        } else {
            $scope.accept_this_card_add = false;
            $('.logs').html('Please input card number.');
        }
    });
}

$scope.checkCardNumberEditCreditCard = function (value) {
    $scope.editCreditCardData.card_number = $scope.requirednumber(value);
    angular.element('#card_number_form_edit').validateCreditCard(function (result) {
        if (result.valid == true && result.length_valid == true && result.luhn_valid == true) {
            $('.logs').html(result.card_type.name + '<img class="icon_opportunities" src="resources/images/icons/checked-form-2-green.png" style="width:20px" />');
            $scope.accept_this_card_edit = true;
        } else {
            $scope.accept_this_card_edit = false;
            $('.logs').html('Please input card number.');
        }
    });
}

$scope.setValueInput = function (id,type) {
    if(type =='expired_month_add'){
        var month_seletected = _.where($scope.monthNames, {
            value: id
        });
        if(month_seletected.length){
            $scope.Input_value.expired_month = month_seletected[0].name;
        }else{
            $scope.Input_value.expired_month = '';
        }
    }

    if(type =='expired_month_edit'){
        var month_seletected = _.where($scope.monthNames, {
            value: id
        });
        if(month_seletected.length){
            $scope.Input_value.expired_month_edit = month_seletected[0].name;
        }else{
            $scope.Input_value.expired_month_edit = '';
        }
    }

}

$scope.validateForm_CreditCard = function (formValidate, style) {
    var exitLoop = false;
    if (formValidate.$invalid) {
        $ionicScrollDelegate.$getByHandle(formValidate).scrollTop();
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    }
    if (style == 'Add') {
        $scope.addCreditCard();
    } else {
        $scope.updateCreditCard()
    }
}

$scope.addCreditCard = function() {
    $scope.addCreditCardData.customer_id = $scope.customerDetail.id;
    if($scope.accept_this_card_add == false){
        $cordovaToast.showLongTop('Card Number Invalid.!!!');  
        return;
    }
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.addCreditCard($scope.addCreditCardData).success(function(data) {
        $ionicLoading.hide();
        if(data.status){
            $scope.accept_this_card_add = false;
            $cordovaToast.showLongTop(data.msg);
            $scope.closeTarget('#customerDetailAddCreditCard');
            $scope.addCreditCardData = {};
            $scope.loadCreditCard(false);
        }else{
            $cordovaToast.showLongTop(data.msg);
        }
    });
}

$scope.getDataCreditCard = function(id) {
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.getDataCreditCard(id).success(function(data) {
        $ionicLoading.hide();
        $scope.editCreditCardData = data;
        $scope.setValueInput(parseInt($scope.editCreditCardData.expired_month),'expired_month_edit');
        $scope.openByGetTemplate('customerDetailEditCreditCard');
    });
}

$scope.updateCreditCard = function() {
    if($scope.accept_this_card_edit == false){
        $cordovaToast.showLongTop('Card Number Invalid.!!!');  
        return;
    }
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.updateCreditCard($scope.editCreditCardData).success(function(data) {
     $ionicLoading.hide();
     if(data.status){
        $scope.accept_this_card_edit = false;
        $cordovaToast.showLongTop(data.msg);
        $scope.closeTarget('#customerDetailEditCreditCard');
        $scope.loadCreditCard(false);
    }else{
        $cordovaToast.showLongTop(data.msg);
    }
});
}

$scope.confirmDeleteCreditCard = function (id) {
    $scope.openByGetTemplate('customerDetailPopupCreditCardDelete');
    $scope.deleteCreditCardData = {};
    $scope.deleteCreditCardData.id = id;
}

$scope.deleteCreditCard = function() {
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.deleteCreditCard($scope.deleteCreditCardData.id).success(function(data) {
        $ionicLoading.hide();
        if(data.status == false){
            $cordovaToast.showLongTop(data.msg);
        }else{
            $scope.deleteCreditCardData = {};
            $scope.closeTarget('#customerDetailPopupCreditCardDelete');
            $cordovaToast.showLongTop(data.msg);
            $scope.loadCreditCard();
        }
    });
}

$scope.loadInstoreCredit = function(opentable) {
    $ionicLoading.show({
        template: templateLoading
    });
    $scope.searchCustomers.customer_id = $scope.customerDetail.id;
    $scope.searchCustomers.on_app = true;
    Customers.loadCreditCard($scope.searchCustomers).success(function(data) {
        $scope.dataInstoreCredit = data.instorecredits;
        $scope.total_instorecredit = '$'+data.total_instorecredit;
        $scope.currentPage = data.page;
        $scope.itemsPerPage = $scope.searchCustomers.rows;
        customers_pagesize.val($scope.itemsPerPage);
        $scope.totalItems = data.total_rows;
        if(opentable){
            $scope.openByGetTemplate('popupInstoreCredit');
        }
        $ionicLoading.hide();
    });
};

$scope.openPopupAddInstoreCredit = function() {
    $scope.addInstoreCreditData ={};
    $scope.openByGetTemplate('popupAddInstoreCredit');
}

$scope.validateForm_InstoreCredit = function (formValidate, style) {
    var exitLoop = false;
    if (formValidate.$invalid) {
        $ionicScrollDelegate.$getByHandle(formValidate).scrollTop();
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    }
    $scope.checkAmountOverate(style);
}

$scope.checkAmountOverate = function(action){
    $scope.actionCreateUpdateInstore = action;
    if(action == 'add'){
        $scope.closeTarget('#popupAddInstoreCredit');
        if(parseFloat($scope.addInstoreCreditData.amount) > 500){
            $scope.amount_instore_credit_over = $scope.addInstoreCreditData.amount;
            $scope.openByGetTemplate('confirmOverateInstoreCredit');
        }else{
            $scope.createInstoreCredit();
        }
    }else{
        $scope.closeTarget('#popupEditInstoreCredit');
        if(parseFloat($scope.editInstoreCreditData.amount) > 500){
            $scope.amount_instore_credit_over = $scope.editInstoreCreditData.amount;
            $scope.openByGetTemplate('confirmOverateInstoreCredit');
        }else{
            $scope.updateInstoreCredit();
        }
    }   
};

$scope.createInstoreCredit = function(){
    $scope.addInstoreCreditData.customer_id = $scope.customerDetail.id;
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.createInstoreCredit($scope.addInstoreCreditData).success(function(data) {
        $ionicLoading.hide();
        if(data.status){
            $scope.addInstoreCreditData = {};
            $cordovaToast.showLongTop(data.msg);
            $scope.loadInstoreCredit(false);
        }else{
            $cordovaToast.showLongTop(data.msg);
        }
    });
};

$scope.editInstoreCredit = function(id){
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.showInstoreCredit(id).success(function(data) {
        $ionicLoading.hide();
        $scope.editInstoreCreditData = data;
        $scope.openByGetTemplate('popupEditInstoreCredit');
    });
};

$scope.updateInstoreCredit = function(){
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.updateInstoreCredit($scope.editInstoreCreditData.id,$scope.editInstoreCreditData).success(function(data) {
        $ionicLoading.hide();
        if(data.status){
            $cordovaToast.showLongTop(data.msg);
            $scope.loadInstoreCredit(false);
        }else{
            $cordovaToast.showLongTop(data.msg);
        }
    });
};
$scope.createUpdateInstoreCredit = function(){
    if($scope.actionCreateUpdateInstore == 'add'){
        $scope.createInstoreCredit();
    }else{
        $scope.updateInstoreCredit();
    }
};

$scope.confirmInstoreCredit = function(id){
    $scope.dataDeleteInstoreCredit = {};
    $scope.dataDeleteInstoreCredit.id = id;
    $scope.openByGetTemplate('confirmDeleteInstoreCredit');
};

$scope.deleteInstoreCredit = function(){
    $ionicLoading.show({
        template: templateLoading
    });
    Customers.deleteInstoreCredit($scope.dataDeleteInstoreCredit.id).success(function(data) {
        $ionicLoading.hide();
        
        if(data.status == false){
            $cordovaToast.showLongTop(data.msg);
        }else{
            $cordovaToast.showLongTop(data.msg);
            closeTarget('#confirmDeleteInstoreCredit');
            $scope.loadInstoreCredit(false);
        }
    });
};


$scope.$on('getJsonData', function (event, data) {
    var jsondata = data.data;
    var index = _.findIndex(jsondata,{roletree_id:'23'});
    var index1 = _.findIndex(jsondata[index].child,{roletree_id:'24'});

    var indexCusDetail = _.findIndex(jsondata[index].child,{roletree_id:'25'});
    var indexCusReview = _.findIndex(jsondata[index].child,{roletree_id:'26'});

    if(jsondata[index].check && jsondata[index].child[index1].check){
        $scope.viewSearch = jsondata[index].child[index1].child[0].check;
        $scope.hideViewAll = jsondata[index].child[index1].child[1].check;
        $scope.hideAddCus = jsondata[index].child[index1].child[2].check;
        $scope.hideEditCustomer = jsondata[index].child[index1].child[3].check;
        $scope.hideDeleteCustomer = jsondata[index].child[index1].child[4].check;
        $scope.showFilterAndReport = jsondata[index].child[index1].child[5].check;
        $scope.hideExportButton = jsondata[index].child[index1].child[6].check;  


        $scope.viewCustomerDetail = jsondata[index].child[indexCusDetail].check;
        $scope.hideInfo = jsondata[index].child[indexCusDetail].child[0].check;
        $scope.hideEditCustomerDetail = jsondata[index].child[indexCusDetail].child[1].check;
        $scope.hideAppointments = jsondata[index].child[indexCusDetail].child[2].check;
        $scope.hideFileManagement = jsondata[index].child[indexCusDetail].child[3].check;
        $scope.viewDownload = jsondata[index].child[indexCusDetail].child[3].child[0].check;
        $scope.renameDelete = jsondata[index].child[indexCusDetail].child[3].child[1].check;
        $scope.hideEstEnv = jsondata[index].child[indexCusDetail].child[4].check;

        $scope.accessReview = jsondata[index].child[indexCusReview].check;
        $scope.viewSearchReview = jsondata[index].child[indexCusReview].child[0].check;
        $scope.buttonAddreview = jsondata[index].child[indexCusReview].child[1].check;
        $scope.buttonEditreview = jsondata[index].child[indexCusReview].child[2].check;
        $scope.buttonDeletereview = jsondata[index].child[indexCusReview].child[3].check;

        $scope.viewJobsiteList = jsondata[index].child[index1].child[7].child[0].check;
        $scope.addJobsiteButton = jsondata[index].child[index1].child[7].child[1].check;
        $scope.editJobsiteButton = jsondata[index].child[index1].child[7].child[2].check;
        $scope.activeDeactiveJobsiteButton = jsondata[index].child[index1].child[7].child[3].check;
        $scope.makePrimaryJobsiteButton = jsondata[index].child[index1].child[7].child[4].check;
        
        if (!$stateParams.customerID && page == "customers.html") {
            $scope.renderTemplateData();
        }
        if (getParameterByName('customer_id'))
            $scope.getCustomerData(getParameterByName('customer_id'));
        if (getParameterByName('action') == 'review')
            $scope.getCustomereviews();
    }else{
        localStorage.setItem("login_status", "0");
        redirectTo('index.html');
    }
})

})

function addCustomersInOppotunities() {
    var scope = angular.element($("#btnAddCustomerOnOppotunities")).scope();
    console.log(scope);
    scope.$apply(function () {
        scope.$$childTail.$$childHead.getCustomers();
    });

}
