var socket = io(server_chat);
var menuScope;
var chat_head = null;
angular.module('LocationServiceModulues', []).factory('LocationService', function($q) {
    var autocompleteService = new google.maps.places.AutocompleteService();
    var detailsService = new google.maps.places.PlacesService(document.createElement("input"));
    return {
        searchAddress: function(input) {
            var deferred = $q.defer();
            autocompleteService.getPlacePredictions({
                input: input
            }, function(result, status) {
                if (status == google.maps.places.PlacesServiceStatus.OK) {
                    //  console.log(result);
                    deferred.resolve(result);
                } else {
                    deferred.reject(status)
                }
            });
            return deferred.promise;
        },
        getDetails: function(placeId) {
            var deferred = $q.defer();
            detailsService.getDetails({
                placeId: placeId
            }, function(result) {
                deferred.resolve(result);
            });
            return deferred.promise;
        }
    };
});
angular.module('menuController', ['constantAngular', 'ionic', 'ngCordova', 'ion-datetime-picker', //
    'checklist-model', 'LoginService', 'ion-autocomplete', 'notifiesCtrl', 'chatController', 'ion-place-tools', 'authenticationSvc', 'newfeedtypesService', 'usersService', // all module
    'usercredentialsService', 'userdetailsService', 'supplieritemsService', 'listviewsService', 'departmentsService', //
    'positiontitlesService', 'roomsService', 'skillsService', 'rolesService', 'appointmentgroupsService', 'pipusService', 'LocationServiceModulues'
]).controller('menuCtrl', function($scope, $sce, $window, $filter, Auth, $ionicLoading, //
    $ionicPlatform, $ionicPopup, $http, $timeout, $interval, Login, $ionicPopup, $cordovaToast, Login, $ionicHistory, dataHtml, //
    Userdetails, Usercredentials, $ionicScrollDelegate, Listviews, Newfeedtypes, Users, Departments, Positiontitles, Supplieritems, Skills, Rooms, Roles, Appointmentgroups, Pipus, $cordovaInAppBrowser, $ionicPosition, //
    $cordovaImagePicker, $cordovaCamera, $cordovaActionSheet, $cordovaFileTransfer, $cordovaFile, $ionicActionSheet, $cordovaDevice, //
    $cordovaAppVersion, LocationService) {
    document.addEventListener("deviceready", function() {
        var platform = $cordovaDevice.getPlatform();
        if (platform != "iOS") {
            isiOs = false;
        }
        $cordovaAppVersion.getVersionNumber().then(function(version) {
            $scope.versionNumber = version;
        })
    }, false);
    $scope.cordovaBrowser = function(link, type) {
        $ionicLoading.show({
            template: templateLoading
        });
        $timeout(function() {
            if (link.indexOf('s3.amazonaws.com') == -1 && type != 'internal') {
                if (link.indexOf('http') != 0) {
                    link = url_site + '/' + link;
                }
            }
            var vitualElm = document.createElement("a");
            vitualElm.setAttribute("id", "linktopdf");
            //vitualElm.setAttribute("href", link);
            vitualElm.addEventListener("click", function() {
                window.open(link, '_system', 'location=no, clearcache=no, toolbar=yes, enableViewportScale=yes, hidden=yes');
                return false;
            })
            vitualElm.click();
            $ionicLoading.hide();
        }, 1000);
    }
    menuScope = $scope;
    $scope.roleName = role;
    // if (role != null && role != undefined && role != "") {
    //     var denies = {
    //         salesman: ['scheduleapp.html', 'opportunities.html', 'pipus.html'],
    //         fieldinstaller: ['scheduleapp.html', 'opportunities.html', 'pipus.html'],
    //         admin: ['myschedule.html'],
    //         manager: ['myschedule.html'],
    //         reporter: ['myschedule.html', 'pipus.html'],
    //         scheduler: ['myschedule.html', 'pipus.html'],
    //         warehouse: ['myschedule.html', 'pipus.html'],
    //         stratdev: [],
    //         supportassistant: [],
    //         outsidesales: ['pipus.html'],
    //         infieldsupervisor: ['opportunities.html']
    //     };
    //     var exitInAccessDenied = denies[role].indexOf(page);
    //     if (exitInAccessDenied > -1) {
    //         redirectTo('newsfeed.html');
    //     }
    // }
    $scope.UIthemes = [{
        name: "uis-theme-default",
        displayname: "Default"
    }, {
        name: "uis-theme-blue",
        displayname: "Blue"
    }];
    $scope.UIstyles = [{
        name: "uis-style-default",
        displayname: "Default"
    }, {
        name: "uis-style-flat-circle",
        displayname: "Flat circle"
    }];
    $scope.UItheme = {
        key: "storageUItheme",
        theme: 0
    };
    $scope.UIstyle = {
        key: "storageUIstyle",
        style: 0
    };
    $scope.setUItheme = function(theme) {
        $scope.UItheme.theme = theme;
        localStorage.setItem($scope.UItheme.key, theme);
    }
    $scope.setUIstyle = function(style) {
        $scope.UIstyle.style = style;
        localStorage.setItem($scope.UIstyle.key, style);
    }
    $scope.getUItheme = function() {
        if (localStorage.getItem($scope.UItheme.key) === null) {
            $scope.setUItheme(0);
        } else {
            $scope.setUItheme(parseInt(localStorage.getItem($scope.UItheme.key)));
        }
    }
    $scope.getUIstyle = function() {
        if (localStorage.getItem($scope.UIstyle.key) === null) {
            $scope.setUIstyle(0);
        } else {
            $scope.setUIstyle(parseInt(localStorage.getItem($scope.UIstyle.key)));
        }
    }
    $scope.renderNotify = function() {
        dataHtml.getTemplate('templates/dashboard/notifies/notifies.tpl').success(function(results) {
            $scope.menuHtml.notifieschat = results;
        });
    }
    $scope.getUItheme();
    $scope.getUIstyle();
    $scope.isAdmin = isAdmin;
    $scope.isManager = isManager;
    $scope.isReporter = isReporter;
    $scope.isScheduler = isScheduler;
    $scope.isFieldinstaller = isFieldinstaller;
    $scope.isSalesman = isSalesman;
    $scope.isWarehouse = isWarehouse;
    $scope.isStrategicDevelopment = isStrategicDevelopment;
    $scope.isSupportAssistant = isSupportAssistant;
    $scope.isOutsideSales = isOutsideSales;
    $scope.isInFieldSupervisor = isInFieldSupervisor;
    $scope.currentIdLogin = currentIdLogin;
    $scope.departmentId = departmentId;
    $scope.settings = {};
    $scope.settings.storeInCloud = storeInCloud == 'true' ? true : false;
    $scope.settings.requestCheckPunch = request_check_punch_inout == 'true' ? true : false;
    $scope.today = {};
    $scope.today.day = moment().format('DD');
    $scope.today.month = moment().format('MMMM');
    $scope.menuHtml = {};
    $scope.posTitle = [];
    $scope.searchPipus = {
        rows: 100,
        userId: currentIdLogin,
        current_page: 1,
        search: ""
    };
    $scope.autocompleteList = {};
    $scope.check_usercredentials = false;
    $scope.displayValue = {};
    $scope.Input_value = {};
    $scope.pageNanme = $ionicHistory.currentStateName().substr($ionicHistory.currentStateName().lastIndexOf('.') + 1);
    $scope.CurrentDate = {
        day: moment().format("DD"),
        month: moment().format("MMMM"),
        year: moment().format("YYYY"),
        date: moment().format("dddd MM/DD/YYYY")
    };
    // console.log($scope.pageNanme);
    // $scope.timeData=[
    //     {id:1,from:'07:00 AM',to:'08:00 AM'}, {id:2,from:'08:00 AM',to:'09:00 AM'}, {id:3,from:'09:00 AM',to:'10:00 AM'},
    //     {id:4,from:'10:00 AM',to:'11:00 AM'}, {id:5,from:'11:00 AM',to:'12:00 AM'}, {id:6,from:'00:00 PM',to:'01:00 PM'},
    //     {id:7,from:'01:00 PM',to:'02:00 PM'}, {id:8,from:'02:00 PM',to:'03:00 PM'}, {id:9,from:'03:00 PM',to:'04:00 PM'},
    //     {id:10,from:'04:00 PM',to:'05:00 PM'}, {id:11,from:'05:00 PM',to:'06:00 PM'}, {id:12,from:'06:00 PM',to:'07:00 PM'},
    //     {id:13,from:'07:00 PM',to:'08:00 PM'}, {id:14,from:'08:00 PM',to:'09:00 PM'}, {id:15,from:'09:00 PM',to:'10:00 PM'},
    //     {id:16,from:'10:00 PM',to:'11:00 PM'}, {id:17,from:'11:00 PM',to:'00:00 AM'}
    // ];
    $scope.currentTarget = null;
    $scope.bubbleArr = [];
    $scope.driverOrNotSelect = [{id:'1',name:'Yes'},{id:'0',name:'No'}];
    $scope.logincredential_status = 'active';
    $scope.searchUsercredentials = {};
    $scope.searchUsercredentials.show = $scope.logincredential_status;
    $scope.onsubmitPunchin = false;
    $scope.renderTemplateData = function() {
        dataHtml.getTemplate('templates/dashboard/general/menuHeader.tpl').success(function(results) {
            $scope.menuHtml.menuHeader = results;
            dataHtml.getTemplate('templates/dashboard/general/menuNav.tpl').success(function(results) {
                $scope.menuHtml.menuNav = results;
                dataHtml.getTemplate('templates/dashboard/general/punch/menuPunchmodal.tpl').success(function(results) {
                    $scope.menuHtml.menuPunch = results;
                })
            });
        })
    }
    $scope.openByGetTemplate_menu = function(style) {
        $ionicLoading.show({
            template: templateLoading
        });
        $timeout(function() {
            switch (style) {
                case 'popupEmployeeEdit':
                dataHtml.getTemplate('templates/dashboard/users/users/userPopupEditmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeEdit = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeEdit');
                        $ionicScrollDelegate.$getByHandle('scrollEdit').resize();
                        $ionicScrollDelegate.$getByHandle('scrollEdit').scrollTop(true);
                    }, 1)
                });
                break;
                case 'popupEmployeeDetail':
                dataHtml.getTemplate('templates/dashboard/users/users/userPopupDetailsmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeDetail = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeDetail');
                        $ionicScrollDelegate.$getByHandle('scrollEmployeeDetail').resize();
                        $ionicScrollDelegate.$getByHandle('scrollEmployeeDetail').scrollTop(true);
                    }, 1)
                })
                break;
                case 'popupEmployeeIssueLog':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailIssueLogsmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeIssueLog = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeIssueLog');
                        $ionicScrollDelegate.$getByHandle('scrollIssueLog').resize();
                        $ionicScrollDelegate.$getByHandle('scrollIssueLog').scrollTop(true);
                        $ionicLoading.hide();
                        $scope.getAllUsers();
                    }, 1)
                })
                break;
                case 'popupEmployeeIssueLogAdd':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailIssueLogsAddmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeIssueLogAdd = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeIssueLogAdd');
                        $ionicScrollDelegate.$getByHandle('scrollIssueLogAdd').resize();
                        $ionicScrollDelegate.$getByHandle('scrollIssueLogAdd').scrollTop(true);
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeIssueLogEdit':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailIssueLogsEditmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeIssueLogEdit = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeIssueLogEdit');
                        $ionicScrollDelegate.$getByHandle('scrollIssueLogEdit').resize();
                        $ionicScrollDelegate.$getByHandle('scrollIssueLogEdit').scrollTop(true);
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeIssueLogDelete':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailIssueLogsDeletemodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeIssueLogDelete = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeIssueLogDelete');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeSendFeed':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailNewsfeedmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeSendFeed = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeSendFeed');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeLoginCredentials':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailLoginCredentialsmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeLoginCredentials = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeLoginCredentials');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeLoginCredentialsAdd':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailLoginCredentialsAddmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeLoginCredentialsAdd = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeLoginCredentialsAdd');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeLoginCredentialsEdit':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailLoginCredentialsEditmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeLoginCredentialsEdit = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeLoginCredentialsEdit');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeLoginCredentialsDelete':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailLoginCredentialsDeletemodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeLoginCredentialsDelete = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeLoginCredentialsDelete');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeSetting':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailAcountSettingmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeSetting = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeSetting');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeSettingChangePassword':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailAcountSettingChangePasswordmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeSettingChangePassword = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeSettingChangePassword');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeePunchInOutHistory':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailPipusmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeePunchInOutHistory = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeePunchInOutHistory');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeePunchInOutHistoryAdd':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailPipusAddmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeePunchInOutHistoryAdd = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeePunchInOutHistoryAdd');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeePunchInOutHistoryEdit':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailPipusEditmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeePunchInOutHistoryEdit = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeePunchInOutHistoryEdit');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeePunchInOutHistoryDelete':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailPipusDeletemodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeePunchInOutHistoryDelete = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeePunchInOutHistoryDelete');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeDefaultSchedule':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailDefaultSchedulemodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeDefaultSchedule = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeDefaultSchedule');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeDetailVisibility':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailVisibilitymodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeDetailVisibility = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeDetailVisibility');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeDetailDefaultListView':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailDefaultListViewmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEmployeeDetailDefaultListView = results;
                    $timeout(function() {
                        $scope.showTarget('#popupEmployeeDetailDefaultListView');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'confirmDeleteEmployee':
                dataHtml.getTemplate('templates/dashboard/users/users/userPopupDeletemodal.tpl').success(function(results) {
                    $scope.menuHtml.popupDeleteEmployee = results;
                    $scope.showTarget('#confirmDeleteEmployee');
                    $ionicLoading.hide();
                });
                break;
                case 'popupSendConsumableList':
                dataHtml.getTemplate('templates/dashboard/general/punch/popupSendConsumableList.tpl').success(function(results) {
                    $scope.menuHtml.popupSendConsumableList = results;
                    $scope.showTarget('#popupSendConsumableList');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPunchOutIssue':
                dataHtml.getTemplate('templates/dashboard/general/punch/punchOutIssuemodal.tpl').success(function(results) {
                    $scope.menuHtml.popupPunchOutIssue = results;
                    $scope.showTarget('#popupPunchOutIssue');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPunchInIssue':
                dataHtml.getTemplate('templates/dashboard/general/punch/punchInIssuemodal.tpl').success(function(results) {
                    $scope.menuHtml.popupPunchInIssue = results;
                    $scope.showTarget('#popupPunchInIssue');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPunchLastPount':
                dataHtml.getTemplate('templates/dashboard/general/punch/punchLastPountmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupPunchLastPount = results;
                    $scope.showTarget('#popupPunchLastPount');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPunchAbsence':
                dataHtml.getTemplate('templates/dashboard/general/punch/punchAbsencemodal.tpl').success(function(results) {
                    $scope.menuHtml.popupPunchAbsence = results;
                    $scope.showTarget('#popupPunchAbsence');
                    $ionicLoading.hide();
                });
                break;
                case 'popupUserFilemanagerContent':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailFileManagermentmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupUserFilemanagerContent = results;
                    $scope.showTarget('#popupUserFilemanagerContent');
                });
                break;
                case 'popupAddFileFolderName':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailFileManagermentAddmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupAddFileFolderName = results;
                    $scope.showTarget('#popupAddFileFolderName');
                    $scope.dataUrlFileManager.name = "";
                    $ionicLoading.hide();
                });
                break;
                case 'popupEditFileFolderName':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailFileManagermentRenamemodal.tpl').success(function(results) {
                    $scope.menuHtml.popupEditFileFolderName = results;
                    $scope.showTarget('#popupEditFileFolderName');
                    $ionicLoading.hide();
                });
                break;
                case 'confirmDeleteFolder':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailFileManagermentDeletemodal.tpl').success(function(results) {
                    $scope.menuHtml.confirmDeleteFolder = results;
                    $scope.showTarget('#confirmDeleteFolder');
                    $ionicLoading.hide();
                });
                break;
                case 'optionFileDetail':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailFileManagermentOptionsmodal.tpl').success(function(results) {
                    $scope.menuHtml.optionFileDetail = results;
                    $scope.showTarget('#optionFileDetail');
                    $ionicLoading.hide();
                });
                break;
                case 'popupConfirmVehicles':
                dataHtml.getTemplate('templates/dashboard/users/users/popupConfirmVehiclesmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupConfirmVehicles = results;
                    $scope.showTarget('#popupConfirmVehicles');
                    $ionicLoading.hide();
                });
                break;
                case 'popupFilterLogincredential':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailFilterLogincredentialmodal.tpl').success(function(results) {
                    $scope.menuHtml.popupFilterLogincredential = results;
                    $scope.showTarget('#popupFilterLogincredential');
                    $ionicLoading.hide();
                });
                break;
                case 'confirmActiveOrDeactiveCredential':
                dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailConfirmActiveOrDeactiveCredential.tpl').success(function(results) {
                    $scope.menuHtml.popupconfirmActiveOrDeactiveCredential = results;
                    $scope.showTarget('#confirmActiveOrDeactiveCredential');
                    $ionicLoading.hide();
                });
                break;
            }
        }, 500);
}
$scope.dataChangePassword = {};
$scope.getDataUser = function() {
    Login.getUserLogin().success(function(data) {
        if (data.status == false) {
            localStorage.setItem("login_status", "0");
            redirectTo('index.html');
        } else {
            var jsondataonmenu = data.jsondata;
            var indexUser = _.findIndex(jsondataonmenu, {
                roletree_id: '1'
            });
            $scope.showTabUser = jsondataonmenu[indexUser].check;
            var indexCustomer = _.findIndex(jsondataonmenu, {
                roletree_id: '23'
            });
            $scope.showTabCustomer = jsondataonmenu[indexCustomer].check;
            var indexOppotunity = _.findIndex(jsondataonmenu, {
                roletree_id: '43'
            });
            $scope.showTabOppotunity = jsondataonmenu[indexOppotunity].check;
            var indexSchedule = _.findIndex(jsondataonmenu, {
                roletree_id: '46'
            });
            $scope.showTabSchedule = jsondataonmenu[indexSchedule].check;
            var indexMySchedule = _.findIndex(jsondataonmenu, {
                roletree_id: '68'
            });
            $scope.showTabMySchedule = jsondataonmenu[indexMySchedule].check;
            var indexChat = _.findIndex(jsondataonmenu, {
                roletree_id: '77'
            });
            $scope.showTabChat = jsondataonmenu[indexChat].check;
            var indexTask = _.findIndex(jsondataonmenu, {
                roletree_id: '78'
            });
            $scope.showTabTask = jsondataonmenu[indexTask].check;
            var indexNewfeed = _.findIndex(jsondataonmenu, {
                roletree_id: '81'
            });
            $scope.showTabNewfeed = jsondataonmenu[indexNewfeed].check;
            var indexPricebook = _.findIndex(jsondataonmenu, {
                roletree_id: '87'
            });
            $scope.showTabPricebook = jsondataonmenu[indexPricebook].check;
            var indexPayment = _.findIndex(jsondataonmenu, {
                roletree_id: '92'
            });
            $scope.showTabPayment = jsondataonmenu[indexPayment].check;
            var indexPuninout = _.findIndex(jsondataonmenu, {
                roletree_id: '93'
            });
            $scope.showTabPuninout = jsondataonmenu[indexPuninout].check;
            var indexSetting = _.findIndex(jsondataonmenu, {
                roletree_id: '94'
            });
            $scope.showTabSetting = jsondataonmenu[indexSetting].check;
            $scope.showTabCutomerReview = jsondataonmenu[indexCustomer].child[2].check;
            $scope.showTabTaskFilter = jsondataonmenu[indexTask].child[1].check;
            $scope.dataInfo = data;
            $scope.dataChangePassword.emailShow = data.email;
            localStorage.setItem('departmentId', $scope.dataInfo.department_id);
            localStorage.setItem('currentIdLogin', $scope.dataInfo.id);
            $scope.$broadcast('getJsonData', {
                data: data.jsondata
            })
                //view user detail by click left menu
                var index_user = _.findIndex(data.jsondata, {
                    roletree_id: '1'
                });
                var index_user_detail = _.findIndex(data.jsondata[index_user].child, {
                    roletree_id: '3'
                });
                $scope.checkViewClientRole(data.jsondata[index_user].child[index_user_detail]);
                $scope.renderNotify();
            }
        })
}
$scope.getDataUser();
$scope.changePassword = function(formValidate) {
    if (formValidate.$invalid) {
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    };
    if ($scope.newPassword != $scope.conFirmPassword) {
        $cordovaToast.showLongTop('Password does not match !!!');
        return;
    }
    if ($scope.newPassword.length < 6) {
        $cordovaToast.showLongTop('The password must be at least 7 characters long !!!');
        return;
    }
    $scope.md_pass = forge.md.sha256.create();
    $scope.md_newpass = forge.md.sha256.create();
    $scope.currentpassword = ($scope.oldPassword == '') ? '' : $scope.md_pass.update($scope.oldPassword);
    $scope.newpassword = ($scope.newPassword == '') ? '' : $scope.md_newpass.update($scope.newPassword);
    $scope.renewpassword = $scope.conFirmPassword;
    $scope.dataChangePassword.currentpassword = $scope.md_pass.digest().toHex();
    $scope.dataChangePassword.newpassword = $scope.md_newpass.digest().toHex();
    $scope.dataChangePassword.orgpassword = $scope.newPassword;
    $ionicLoading.show({
        template: templateLoading
    });
    return Login.changePassword($scope.dataChangePassword).success(function(data) {
        $ionicLoading.hide();
        if (data.status) {
            $scope.Logout();
                // $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 Errror!!!');
        });
    }
    $scope.redirectTo = function(url) {
        $ionicLoading.show({
            template: templateLoading
        });
        $timeout(function() {
            $scope.initialEmployeeForSearch = [];
            redirectTo(url);
        }, 1000)
    }
    var myPopup;
    $scope.configStoreInCloud = function() {
        storeInCloud = $scope.settings.storeInCloud;
        localStorage.setItem('storeInCloud', storeInCloud);
    }
    $scope.configRequestCheckPunch = function() {
        request_check_punch_inout = $scope.settings.requestCheckPunch;
        localStorage.setItem('request_check_punch_inout', request_check_punch_inout);
    }
    $scope.layoutDashboardActive = 'AllApp';
    $scope.setLayoutDashboard = function(tab) {
        $scope.layoutDashboardActive = tab;
        if (tab == 'AllPunch') $scope.getPipus();
    }
    // Logout Option Handle
    logoutOptionHandle();
    function logoutOptionHandle() {
        toggleHandle('.link-logout-option', '.logout-option');
        closeOutsideHandle('.link-logout-option', '.logout-option');
    }
    $scope.Logout = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        data = {
            token: localStorage.getItem("token")
        }
        Auth.Logout(data).success(function() {
            localStorage.setItem("login_status", "0");
            localStorage.setItem("email", "");
            localStorage.setItem("token", "");
            $ionicLoading.hide();
            redirectTo('index.html');
        });
    }
    $scope.exitApp = function() {
        navigator.app.exitApp();
        // ionic.Platform.exitApp();
        window.close();
    }
    $scope.validateForm = function(formValidate, style, file) {
        var exitLoop = false;
        if (formValidate.$invalid) {
            $ionicScrollDelegate.$getByHandle('scroll' + style).scrollTop();
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        };
        switch (style) {
            case 'Add':
            $scope.beforeCreateUsers(file);
            break;
            case 'Edit':
            $scope.beforeUpdateUsers(file);
            break;
            case 'outIssue':
            $scope.punchOutIssuesAddTask();
            break;
            case 'inIssue':
            $scope.punchInIssuesAddTask();
            break;
            case 'lastPount':
            $scope.lastPoutAddTask();
            break;
            default:
            $scope.unplannedAbsenceAddTask();
            break;
        }
    }
    $scope.openIonicPopup = function(templateUrl, title) {
        myPopup = $ionicPopup.show({
            templateUrl: templateUrl,
            title: title,
            scope: $scope
        });
    }
    $scope.closeIonicPopup = function() {
        myPopup.close();
    }
    $scope.openPickerForProfile = function() {
        var options = {
            maximumImagesCount: 1,
            width: 0,
            height: 0,
            quality: 100
        };
        $ionicLoading.show({
            template: templateLoading
        });
        $cordovaImagePicker.getPictures(options).then(function(results) {
            $scope.file = results[0];
            window.plugins.Base64.encodeFile($scope.file, function(base64) {
                $scope.imageURI = base64;
                // console.log('file base64 encoding: ' + base64);
            });
            $timeout(function() {
                $ionicLoading.hide();
            }, 3000)
        })
    }
    $scope.blurFocusCombobox = function() {
        $(window).on("click.Bst", function(e) {
            if (!$('select').is(e.target)) {
                $('select').blur();;
            } else {}
        });
    }
    $scope.blurFocusCombobox();
    /* METHOD 1 */
    //$scope.backButtonAction = function () {
    //    var backActionKey = 'RGDapp_backAction';
    //    if (localStorage.getItem(backActionKey) === null) {
    //        navigator.app.exitApp();
    //    } else {
    //        var backAction = JSON.parse(localStorage.getItem(backActionKey));
    //        if (!backAction.length) {
    //            navigator.app.exitApp();
    //            localStorage.removeItem(key);
    //        } else {
    //            var lastAction = backAction[backAction.length - 1];
    //            switch (lastAction.action) {
    //                case "closePopup":
    //                    $scope.closeTarget(lastAction.arg)
    //                    break;
    //            }
    //            backAction.splice(backAction.length - 1, 1);
    //            localStorage.setItem(backActionKey, JSON.stringify(backAction));
    //        }
    //    }
    //}
    /* METHOD 2 */
    $scope.backButtonAction = function() {
        var backable = true;
        var $backButton;
        var $popupShowing;
        if ($('.app-dashboard-menu').hasClass('show')) {
            $backButton = $('.app-dashboard-menu').find('.dashboard-menu-close-button')
        } else {
            $popupShowing = $('.ion-datetime-picker-popup.active');
            if ($popupShowing.length) {
                $backButton = $popupShowing.find('.popup-buttons .button-stable');
            } else {
                $popupShowing = $('.app-content-popup-area').find('.app-content-popup.show, .app-confirm-popup.show, .app-setting.show');
                if ($popupShowing.length) {
                    if ($popupShowing.hasClass('app-confirm-popup')) {
                        $backButton = $popupShowing.last().find('> .overlay-area');
                    } else if ($popupShowing.hasClass('app-setting')) {
                        $backButton = $popupShowing.last().find('> .overlay-full-fixed');
                    } else {
                        $backButton = $popupShowing.last().find('> .app-header .popup-back-button, > .app-header .popup-close-button, > .app-control .popup-back-button');
                        if ($popupShowing.hasClass('file') && $popupShowing.last().find('.folder-back-button').length) {
                            $backButton = $popupShowing.last().find('.folder-back-button');
                        }
                        if ($('body').hasClass('chat-page') && $popupShowing.last().find('.chat-emoticon.show').length) {
                            $backButton = $(window);
                        }
                    }
                } else {
                    $popupShowing = $('.app-main > .app-control.forbidden.show');
                    if ($popupShowing.length) {
                        $backButton = $popupShowing.find('.popup-back-button')
                    } else {
                        $popupShowing = $('.app-main > .app-header .page-back-button');
                        if ($popupShowing.length) {
                            $backButton = $popupShowing.first();
                        } else {
                            backable = false;
                        }
                    }
                }
            }
        }
        if (backable) {
            angular.element($backButton).triggerHandler('click');
        } else {
            navigator.app.exitApp();
        }
    }
    //$(window).dblclick(function () {
    //    $scope.backButtonAction();
    //})
    $ionicPlatform.registerBackButtonAction(function() {
        $scope.backButtonAction();
    }, 100);
    $scope.focusInputTag = function($event) {
        if (!isKeyboardHide) return;
        var t = isKeyboardHide ? 1200 : 600;
        $timeout(function() {
            var $lastPopup = angular.element('.dashboard .app-content-popup.show').last();
            var currentDelegateScroll = $lastPopup.find('ion-scroll');
            if ($lastPopup.find('ion-slides').length > 0) {
                currentDelegateScroll = $lastPopup.find('.swiper-slide-active').find('ion-scroll').attr('delegate-handle');
            } else {
                currentDelegateScroll = $lastPopup.find('ion-scroll').attr('delegate-handle');
            }
            var target = $($event.target);
            if (target) {
                var offsetTop = parseInt($ionicPosition.offset(angular.element($($event.target).closest('.itm'))).top);
                var scrollTop = parseInt($ionicScrollDelegate.$getByHandle(currentDelegateScroll).getScrollPosition().top);
                var contentTop = $ionicPosition.offset($lastPopup.find('.content > .content-inner')).top;
                var y = (offsetTop + scrollTop) - contentTop;
            }
            $($event.target).closest('.itm').addClass('has-tag-input');
            $ionicScrollDelegate.$getByHandle(currentDelegateScroll).scrollTo(0, y, true);
        }, t);
    }
    $scope.blurInputTag = function() {
        var $lastPopup = angular.element('.dashboard .app-content-popup.show').last();
        var currentDelegateScroll = $lastPopup.find('ion-scroll');
        if ($lastPopup.find('ion-slides').length > 0) {
            currentDelegateScroll = $lastPopup.find('.swiper-slide-active').find('ion-scroll').attr('delegate-handle');
        } else {
            currentDelegateScroll = $lastPopup.find('ion-scroll').attr('delegate-handle');
        }
        $lastPopup.find('.itm').removeClass('has-tag-input');
        $ionicScrollDelegate.$getByHandle(currentDelegateScroll).resize();
    }
    $scope.toggleItem = "";
    $scope.toggleTemplate = "appointment-history-item";
    $scope.toggleItemHandle = function($event, p, pe, e) {
        $scope.toggleItem = pe;
        $('.appointment-history-item-no-acttach' + " " + '.appointment-detail-no-acttach').hide();
        var $lastPopup = $('.dashboard .app-content-popup.show').last();
        $lastPopup.find(p + " " + e).hide();
        $($event.target).closest(pe).find(e).toggle();
    }
    $scope.focusHandle = function($event) {
        //===== move to focusHandler above
        return;
        // if (isiOs && $($event.target).find('select').length) return;
        // var t = isKeyboardHide ? 1200 : 600;
        // $($event.target).closest('form').addClass('hide-blinking-cursor');
        // var $lastPopup = $('.dashboard .app-content-popup.show').last();
        // var currentDelegateScroll = $lastPopup.find('ion-scroll').attr('delegate-handle');
        // $timeout(function () {
        //     var offsetTop = parseInt($ionicPosition.offset(angular.element($($event.target).closest('.itm'))).top);
        //     var scrollTop = parseInt($ionicScrollDelegate.$getByHandle(currentDelegateScroll).getScrollPosition().top);
        //     var contentTop = $ionicPosition.offset(angular.element($lastPopup.find('.app-content'))).top;
        //     var y = (offsetTop + scrollTop) - contentTop;
        //     $ionicScrollDelegate.$getByHandle(currentDelegateScroll).scrollTo(0, y, true);
        // }, t).then(function () {
        //     setTimeout(function () {
        //         $scope.$apply(function () {
        //             $($event.target).closest('form').removeClass('hide-blinking-cursor');
        //             $ionicScrollDelegate.$getByHandle(currentDelegateScroll).resize();
        //             $($event.target).find('input, textarea').first().focusout();
        //             $($event.target).find('input, textarea').first().focus();
        //         });
        //     }, t);
        // })
    }
    $scope.scrollToElement = function(event, e) {
        var $lastPopup = $('.dashboard .app-content-popup.show').last();
        var currentDelegateScroll = $lastPopup.find('ion-scroll');
        if ($lastPopup.find('ion-slides').length > 0) {
            currentDelegateScroll = $lastPopup.find('.swiper-slide-active').find('ion-scroll').attr('delegate-handle');
        } else {
            currentDelegateScroll = $lastPopup.find('ion-scroll').attr('delegate-handle');
        }
        var offsetTop = parseInt($ionicPosition.offset(angular.element($lastPopup.find(e))).top);
        var scrollTop = parseInt($ionicScrollDelegate.$getByHandle(currentDelegateScroll).getScrollPosition().top);
        var contentTop = $ionicPosition.offset(angular.element($lastPopup.find('.app-content'))).top;
        var y = (offsetTop + scrollTop) - contentTop;
        $timeout(function() {
            $ionicScrollDelegate.$getByHandle(currentDelegateScroll).resize();
        }, 1).then(function() {
            $ionicScrollDelegate.$getByHandle(currentDelegateScroll).scrollTo(0, y, true);
        })
    }
    $scope.enableEditedInput = function($event) {
        var t = isKeyboardHide ? 1200 : 600;
        $($event.target).siblings('.value-text').hide().siblings('.value-input').removeClass('hidden');
        $timeout(function() {
            $($event.target).siblings('.value-input').focus().select();
        }, 1) // t
    }
    $scope.disableEditedInput = function($event) {
        $($event.target).addClass('hidden').siblings('.value-text').show();
    }
    $scope.toggleText = function(s, l, lx, moreText, lessText) {
        if (s == null) return;
        var result;
        if (s.length > (l + lx)) {
            var textShow = s.slice(0, l);
            var textHide = s.slice(l, s.length);
            result = textShow + '<span class="hidden-text">' + textHide + '</span>';
            result += '<span class="show-hide-text text-link-1 pdL4"><span class="show-text">' + moreText + '</span>' + '<span class="hide-text">' + lessText + '</span></span>';
        } else {
            result = s;
        }
        return result;
    }
    $scope.displayTime = function(t, hasFilter) {
        if (!t) return '';
        if (hasFilter) t = $filter('date')(t, 'hh:mma');
        t = t.toLowerCase();
        t = t.replace(' ', '').replace('am', '<span class="fz10 pdL2">am</span>').replace('pm', '<span class="fz10 pdL2">pm</span>');
        return t;
    }
    $scope.displayHourTime = function(t) {
        if (!t) return;
        t = t.toLowerCase();
        t = t.replace(' hours', '<span class="fz10 pdLR2">hrs</span>').replace(' minutes', '<span class="fz10 pdL2">mins</span>');
        return t;
    }
    $scope.switchTimeToIndex = function(hour) {
        if (!hour) return;
        var arrHour = hour.split(':');
        var hh = arrHour[0];
        var id;
        // var mm=arrHour[1];
        switch (hh) {
            case '06':
            id = 1;
            break;
            case '07':
            id = 2;
            break;
            case '08':
            id = 3;
            break;
            case '09':
            id = 4;
            break;
            case '10':
            id = 5;
            break;
            case '11':
            id = 6;
            break;
            case '12':
            id = 7;
            break;
            case '13':
            id = 8;
            break;
            case '14':
            id = 9;
            break;
            case '15':
            id = 10;
            break;
            case '16':
            id = 11;
            break;
            case '17':
            id = 12;
            break;
            case '18':
            id = 13;
            break;
            case '19':
            id = 14;
            break;
            case '20':
            id = 15;
            break;
            case '21':
            id = 16;
            break;
            case '22':
            id = 17;
            break;
            case '23':
            id = 18;
            break;
        }
        return _.findLastIndex($scope.timeData, {
            id: parseInt(id)
        });
    }
    $scope.calculateTimePercent = function(from_hour, to_hour, first) {
        var arrFrom_hour = from_hour.split(':');
        var hh_from_hour = arrFrom_hour[0];
        var mm_from_hour = arrFrom_hour[1];
        var arrTo_hour = to_hour.split(':');
        var hh_to_hour = arrTo_hour[0];
        var mm_to_hour = arrTo_hour[1];
        var left = 0,
        right = 0,
        width = 0,
        from, to;
        var stop = true;
        var left = mm_from_hour / 60 * 100;
        if (first) {
            from = moment(from_hour, 'HH:mm').format('hh:mm');
        }
        if ((hh_to_hour - hh_from_hour == 0) || ((hh_to_hour - hh_from_hour == 1) && (mm_to_hour == '00'))) {
            to = moment(to_hour, 'HH:mm').format('hh:mm');
        }
        if (hh_to_hour - hh_from_hour == 0) {
            width = (mm_to_hour - mm_from_hour) / 60 * 100;
            right = 100 - left - width;
        } else {
            width = 100 - left;
            if (hh_to_hour - hh_from_hour > 1 || mm_to_hour != '00') {
                stop = false;
            }
        }
        return {
            stop: stop,
            detail: {
                left: left,
                right: right,
                width: width,
                from: from,
                to: to
            }
        };
    }
    // userDetail
    $scope.time = {};
    $scope.time.start = moment().day("Sunday").format('MM/DD/YYYY');
    $scope.time.end = moment().format('MM/DD/YYYY');
    $scope.selectedUserId = {};
    $scope.insideMenu = false;
    $scope.searchPipus = {
        rows: 5,
        current_page: $scope.currentPagePipus,
        search: ""
    };
    $scope.setTime = false;
    $scope.addPipusData = {};
    $scope.refreshDetailUser = false;
    $scope.getUserData = function(id, insideMenu, status) {
        $scope.insideMenu = insideMenu;
        $scope.refreshDetailUser = true;
        $scope.openByGetTemplate_menu('popupEmployeeDetail');
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.show(id).success(function(data) {
            $ionicLoading.hide();
            $scope.usersDetail = data;
            $scope.callGetResultView(data);
            if (!$scope.insideMenu) $scope.usersDetail.dataUser.status = status;
            $scope.rootUserDataUrl = $scope.userDataUrl + $scope.usersDetail.dataUser.id + '/';
            $scope.fDateInput(data.dataUserDetail, $scope.usersDetail.dataUserDetail);
            $scope.getUsercredentials();
            if ($scope.roleName != $scope.isFieldinstaller) {
                $scope.loadUserlogs(id);
                $scope.getlist_fieldwork(id);
            }
            $scope.getSelectListviews();
            $scope.showTabByRole(id, $scope.usersDetail.dataUser.department_id);
            $scope.getConfigS3(id);
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.editUsers = function(id) {
        // $scope.insideMenu = insideMenu;
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.openByGetTemplate_menu('popupEmployeeEdit');
        $scope.currentUserId = id;
        $ionicScrollDelegate.scrollTop(false);
        $scope.initialSuppliersItemEdit = [];
        $scope.initialAppointmentGroupEdit = [];
        $scope.initialVehicleEditEdit = [];
        $scope.file = "";
        $scope.imageURI = "";
        $scope.editUsersData = {};
        Users.show(id).success(function(data) {
            // console.log(data);
            $scope.editUsersData = data;
            if ($scope.editUsersData.dataUserDetail != null) {
                // var parseTarget_hour = parseInt($scope.editUsersData.dataUserDetail.target_hour);
                // $scope.editUsersData.dataUserDetail.target_hour = parseTarget_hour;
                var parseZipcode = parseInt($scope.editUsersData.dataUserDetail.zipcode);
                $scope.editUsersData.dataUserDetail.zipcode = parseZipcode;
                if ($scope.editUsersData.dataUserDetail.zipcode == NaN) $scope.editUsersData.dataUserDetail.zipcode = undefined;
                var supervisor_user1 = parseInt($scope.editUsersData.dataUser.supervisor_user1);
                $scope.editUsersData.dataUser.supervisor_user1 = supervisor_user1;
                var supervisor_user2 = parseInt($scope.editUsersData.dataUser.supervisor_user2);
                $scope.editUsersData.dataUser.supervisor_user2 = supervisor_user2;
                $scope.fDateInput(data.dataUserDetail, $scope.editUsersData.dataUserDetail);
            }
            var parseCellphone = String($scope.editUsersData.dataUser.cell_phone);
            $scope.editUsersData.dataUser.cell_phone = parseCellphone;
            var parseOffice = String($scope.editUsersData.dataUser.office_phone);
            $scope.editUsersData.dataUser.office_phone = parseOffice;
            var parseExtension = String($scope.editUsersData.dataUser.extension_phone);
            $scope.editUsersData.dataUser.extension_phone = parseExtension;
            if ($scope.editUsersData.dataUser.extension_phone == "null") $scope.editUsersData.dataUser.extension_phone = "";
            $scope.editUsersData.userSkillArrId = {
                skillId: $scope.editUsersData.dataUserSkill
            };
            // $('#current_startdate').val($scope.editUsersData.dataUserPositiontitles.current_startdate);
            // $('#current_hiredate').val($scope.editUsersData.dataUserPositiontitles.current_hiredate);
            $scope.getDepartments(2);
            // $scope.dataUserAppointmentGroupsEdit=$scope.editUsersData.dataUserAppointmentGroups;
            var dataSupplier = [];
            var dataApointmentGroup = [];
            angular.forEach($scope.editUsersData.dataSupplieritems, function(item) {
                dataSupplier.push(item.id);
            });
            angular.forEach($scope.editUsersData.dataUserAppointmentGroups, function(item) {
                dataApointmentGroup.push(item.id);
            });
            $scope.initialAppointmentGroupEdit = dataApointmentGroup;
            if (!$scope.holdValueAddress) {
                $scope.holdValueAddress = {};
            }
            if ($scope.editUsersData.dataUserDetail.street.length > 0) {
                $scope.holdValueAddress.editUserAddress = [{
                    place_id: 'place_id',
                    description: $scope.editUsersData.dataUserDetail.street
                }];
            } else {
                $scope.holdValueAddress.editUserAddress = [];
            }
            if ($scope.editUsersData.dataUserDetail.start_location.length > 0) {
                $scope.holdValueAddress.editUserStarLocation = [{
                    place_id: 'place_id',
                    description: $scope.editUsersData.dataUserDetail.start_location
                }];
            } else {
                $scope.holdValueAddress.editUserStarLocation = [];
            }
            if($scope.editUsersData.assignedVehicle != null){
                $scope.initialVehicleEdit = [$scope.editUsersData.assignedVehicle.id];
            }else{
                $scope.initialVehicleEdit = [];
            }
            
            // if ($scope.editUsersData.dataUserDetail.assigned_location.length > 0) {
            //     $scope.holdValueAddress.editUserAssignLocation = [{
            //         place_id: 'place_id',
            //         description: $scope.editUsersData.dataUserDetail.assigned_location
            //     }];
            // } else {
            //     $scope.holdValueAddress.editUserAssignLocation = [];
            // }
            // console.log($scope.initialAppointmentGroupEdit);
            // edit by haudao clone data into input
            $timeout(function() {
                $scope.initialSuppliersItemEdit = dataSupplier;
                $scope.Input_value.department = "";
                var deparment_index = _.findLastIndex($scope.departments, {
                    id: $scope.editUsersData.dataUser.department_id
                });
                if (deparment_index >= 0) $scope.Input_value.department = $scope.departments[deparment_index].name;
                $scope.setValueDepartmentGroupInput($scope.editUsersData.dataUser.department_group);
                $scope.Input_value.positiontitle = "";
                var positiontitle_index = _.findLastIndex($scope.positiontitles_by_department, {
                    id: $scope.editUsersData.dataUserPositiontitles.positiontitle_id
                });
                if (positiontitle_index >= 0) $scope.Input_value.positiontitle = $scope.positiontitles_by_department[positiontitle_index].name;
                $scope.setValueRoleInput($scope.editUsersData.dataUserRole.role_id);
                $scope.setValueSuperVisor1Input($scope.editUsersData.dataUser.supervisor_user1);
                $scope.setValueSuperVisor2Input($scope.editUsersData.dataUser.supervisor_user2);
                $scope.setValuePushChatRoomInput($scope.editUsersData.dataUser.pushchatroom);
                $scope.setValueUserType($scope.editUsersData.dataUser.usertype_id);
                $scope.setValueAssignLocation($scope.editUsersData.dataUserDetail.assigned_location_id);
                $scope.setValueCurrentWageDetail($scope.editUsersData.dataUserDetail.currentwage_detail_id);
                $scope.setValueStartingWageDetail($scope.editUsersData.dataUserDetail.startwage_detail_id);
                $scope.setValueDriverornot($scope.editUsersData.dataUserDetail.driverornot);
                angular.element("#editUsersDataColor").spectrum("set", $scope.editUsersData.dataUserDetail.color);
                $ionicLoading.hide();
            }, 7000);
        });
}
$scope.locationChangedEdit = function(location) {
    $scope.editUsersData.dataUserDetail.city = location['locality'];
    $scope.editUsersData.dataUserDetail.state = location['administrative_area_level_1'];
    $scope.editUsersData.dataUserDetail.zipcode = location['postal_code'];
}
$scope.beforeUpdateUsers = function(file) {
    if(parseInt($scope.editUsersData.dataUserDetail.driverornot) == 1 && !parseInt($scope.editUsersData.assignedVehicle.id) > 0){
        $cordovaToast.showLongTop('Please assign vehicle');
        return;
    }
    $ionicLoading.show({
        template: templateLoading
    });
    $scope.editUsersData.storeInCloud = storeInCloud;
    if (storeInCloud && file !== undefined && file !== "" && file !== null) {
        $scope.fileUploadData = {};
        $scope.fileUploadData.type = 'image/jpeg';
        $scope.fileUploadData.name = 'user_image.jpg';
        $scope.fileUploadData.bucket = bucketName;
        $scope.fileUploadData.acl = aclConfig;
        $scope.fileUploadData.for = 'users';
        $scope.fileUploadData.email = $scope.editUsersData.dataUser.email;
        Login.getConfigFileUpload($scope.fileUploadData).success(function(data) {
            var Uoptions = {};
            Uoptions.fileKey = "file";
            Uoptions.fileName = data.folder + '/' + data.microtime + 'user_image.jpg';
            Uoptions.mimeType = "image/jpeg";
            Uoptions.chunkedMode = false;
            Uoptions.headers = {
                connection: "close"
            };
            Uoptions.params = {
                "Key": data.folder + '/' + data.microtime + 'user_image.jpg',
                "AWSAccessKeyId": data.awsAccessKeyId,
                "acl": data.acl,
                "Policy": data.policy,
                "Signature": data.signature,
                "success_action_status": data.successActionStatus,
                "Content-Type": "image/jpeg"
            };
            $cordovaFileTransfer.upload('http://' + bucketName + '.s3.amazonaws.com/', file, Uoptions).then(function(return_data) {
                try {
                    $scope.fileLocation = return_data.headers.Location;
                } catch (e) {
                    $scope.jsonObject = xml2json.parser(return_data.response);
                    $scope.fileLocation = $scope.jsonObject.postresponse.location;
                }
                $scope.editUsersData.dataUser.image_pic = $scope.fileLocation;
                $scope.fileUploadData = {};
                $scope.updateUsers(file);
            })
        });
    } else {
        $scope.updateUsers(file);
    }
        // $cordovaKeyboard.close();
    }
    $scope.updateUsers = function(file) {
        var id = $scope.editUsersData.dataUser.id;
        $scope.editUsersDataCopy = angular.copy($scope.editUsersData);
        $scope.editUsersDataCopy.dataUserDetail.dob = $('#popupEmployeeEdit input[name="dob"]').val();
        $scope.editUsersDataCopy.dataUserDetail.company_hiredate = $('#popupEmployeeEdit input[name="company_hiredate"]').val();
        $scope.editUsersDataCopy.dataUserDetail.company_startdate = $('#popupEmployeeEdit input[name="company_startdate"]').val();
        $scope.editUsersDataCopy.dataUserDetail.last_review = $('#popupEmployeeEdit input[name="last_review"]').val();
        $scope.editUsersDataCopy.dataUserDetail.next_review = $('#popupEmployeeEdit input[name="next_review"]').val();
        $scope.editUsersDataCopy.dataUserDetail.last_raise = $('#popupEmployeeEdit input[name="last_raise"]').val();
        $scope.editUsersDataCopy.dataUserPositiontitles.current_startdate = $('#popupEmployeeEdit input[name="current_startdate"]').val();
        $scope.editUsersDataCopy.dataUserPositiontitles.current_hiredate = $('#popupEmployeeEdit input[name="current_hiredate"]').val();
        $scope.editUsersDataCopy.managerId = currentIdLogin;
        $scope.editUsersDataCopy.dataSupplieritems = JSON.stringify($scope.editUsersData.dataSupplieritems);
        $scope.editUsersDataCopy.dataUser = JSON.stringify($scope.editUsersData.dataUser);
        $scope.editUsersDataCopy.dataUserAppointmentGroups = JSON.stringify($scope.editUsersData.dataUserAppointmentGroups);
        $scope.editUsersDataCopy.dataUserDetail = JSON.stringify($scope.editUsersData.dataUserDetail);
        $scope.editUsersDataCopy.dataUserLog = JSON.stringify($scope.editUsersData.dataUserLog);
        $scope.editUsersDataCopy.dataUserPositiontitles = JSON.stringify($scope.editUsersData.dataUserPositiontitles);
        $scope.editUsersDataCopy.dataUserRole = JSON.stringify($scope.editUsersData.dataUserRole);
        $scope.editUsersDataCopy.dataUserSkill = JSON.stringify($scope.editUsersData.dataUserSkill);
        $scope.editUsersDataCopy.userSkillArrId = JSON.stringify($scope.editUsersData.userSkillArrId);
        $scope.editUsersDataCopy.assignedVehicle = JSON.stringify($scope.editUsersData.assignedVehicle);
        $scope.editUsersDataCopy.userlogin = $scope.currentIdLogin;
        $scope.editUsersDataCopy.phoneApp = false;
        // console.log($scope.editUsersData);
        if (file) {
            $scope.editUsersDataCopy.phoneApp = true;
            var options = {
                fileKey: "file",
                params: $scope.editUsersDataCopy,
                chunkedMode: false
            };
            $ionicLoading.show({
                template: templateLoading
            });
            $cordovaFileTransfer.upload(url_server + 'users/update/' + id, file, options).then(function(e) {
                $ionicLoading.hide();
                var results = JSON.parse(e.response);
                if (results.status) {
                    if ($scope.refreshDetailUser) {
                        $scope.getUserData(id, $scope.insideMenu);
                    }
                    $scope.$broadcast('refreshUsers', {
                        data: $scope.editUsersDataCopy,
                        dataValue: $scope.Input_value
                    })
                    if ($scope.editUsersData.remove_exist_vehicle == true) {
                        $scope.closeTarget('#popupConfirmVehicles');
                    }
                    $scope.closeTarget('#popupEmployeeEdit');
                    $cordovaToast.showLongTop(results.msg);
                } else {
                    if (data.type_error == 'vehicle_exist') {
                        $scope.msgConfirmVehicles = data.msg;
                        $scope.editUsersData.remove_exist_vehicle = true;
                        $scope.currentFileUpdateUser = file;
                        $scope.openByGetTemplate_menu('popupConfirmVehicles');
                    } else {
                        $cordovaToast.showLongTop(data.msg);
                    }
                }
            }, function(err) {
                $cordovaToast.showLongTop('Errror!!!');
                console.log(err);
                console.log("ERROR: " + JSON.stringify(err));
                $ionicLoading.hide();
            });
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Users.update(id, $scope.editUsersDataCopy).success(function(data, status, headers, config) {
            $ionicLoading.hide();
            if (data.status) {
                if ($scope.refreshDetailUser) {
                    $scope.getUserData(id, $scope.insideMenu);
                }
                $scope.$broadcast('refreshUsers', {
                    data: $scope.editUsersDataCopy,
                    dataValue: $scope.Input_value
                })
                if ($scope.editUsersData.remove_exist_vehicle == true) {
                    $scope.closeTarget('#popupConfirmVehicles');
                }
                $scope.closeTarget('#popupEmployeeEdit');
                $cordovaToast.showLongTop(data.msg);
            } else {
                if (data.type_error == 'vehicle_exist') {
                    $scope.msgConfirmVehicles = data.msg;
                    $scope.currentFileUpdateUser = file;
                    $scope.openByGetTemplate_menu('popupConfirmVehicles');
                } else {
                    $cordovaToast.showLongTop(data.msg);
                }
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log(data);
            $cordovaToast.showLongTop('Errror!!!');
            console.log('error status: ' + status);
        })
    };
    $scope.confirmVehicles = function(type) {
        $scope.editUsersData.remove_exist_vehicle = true;
        $scope.beforeUpdateUsers($scope.currentFileUpdateUser);
    }
    $scope.confirmDeleteUser = function(id, name, status) {
        $scope.openByGetTemplate_menu('confirmDeleteEmployee');
        $scope.userInfo = {};
        $scope.userInfo.id = id;
        $scope.userInfo.name = name;
        $scope.userInfo.status = status;
    }
    $scope.deleteUsers = function(id, status) {
        $ionicLoading.show({
            template: templateLoading
        });
        Login.checkLogin().success(function(e) {
            Users.activeAndInactiveUser(id, status).success(function(data) {
                $ionicLoading.hide();
                $scope.closeTarget('#confirmDeleteEmployee');
                if (data.status) {
                    $scope.$broadcast('sendInactiveUser', {
                        id: parseInt(id),
                        status: status
                    });
                    if ($scope.usersDetail) $scope.usersDetail.dataUser.status = status == "1" ? "0" : "1";
                    $cordovaToast.showLongTop(data.msg);
                } else {
                    $cordovaToast.showLongTop(data.msg);
                }
            });
        });
    }
    $scope.getDepartments = function(_crud) {
        // document.getElementById("formAddUser").reset();
        // $ionicLoading.show({ template: templateLoading });
        Login.checkLogin().success(function(data) {
            if (data.status) {
                Departments.getSelect().success(function(data) {
                    // console.log('get department', data);
                    $scope.departments = data;
                    $scope.departmentsGroup = data;
                    $scope.getPositiontitles();
                    $timeout(function() {
                        switch (_crud) {
                            case 3:
                            if (!$scope.dataFilterLoaded) {
                                Departments.getSelectFilter().success(function(data) {
                                    $scope.departTitle = $scope.initNode('Department', data);
                                    $scope.dataFilterLoaded = true;
                                });
                            }
                            break;
                            case 2:
                            $scope.getDepartmentsGroupEdit();
                            break;
                            case 1:
                                // console.log($scope.deparmentdata);
                                $scope.addUsersData.appointmentgroup_id = [];
                                $scope.addUsersData.notes = '';
                                if ($scope.deparmentdata == null) {
                                    $scope.deparmentdata = data;
                                    $scope.getDepartmentsGroup();
                                } else {
                                    $scope.addUsersData.positiontitle_id = '';
                                    $scope.addUsersData.department_id = '';
                                    $('.department_group').hide();
                                    // $scope.getListSkill();
                                }
                                break;
                            }
                        }, 500);
                });
            } else {
                console.log('get department fail!!!');
            }
        });
    }
    $scope.listSkill = [];
    $scope.getListSkill = function() {
        if ($scope.editUsersData.dataUser.positiontitle_id == undefined || $scope.editUsersData.dataUser.positiontitle_id == '') return;
        Skills.getListSkill($scope.editUsersData.dataUser.positiontitle_id).success(function(data) {
            $scope.editUsersData.dataUser = _.extend($scope.editUsersData.dataUser, {
                positiontitles: data.positiontitle
            });
            $scope.listSkill = data.data;
            if ($scope.roomsall == undefined) {
                $scope.getRooms();
            } else {
                $scope.getRoles();
            }
        });
    }
    $scope.getDepartmentsGroup = function(department_id) {
        // edit by haudao
        $scope.Input_value.department = "";
        var deparment_index = _.findLastIndex($scope.departments, {
            id: department_id
        });
        if (deparment_index >= 0) $scope.Input_value.department = $scope.departments[deparment_index].name;
        // console.log($scope.Input_value.department);
        // end edit
        Departments.getDepartmentsGroup({
            id: department_id
        }).success(function(data) {
            $scope.departmentsGroup = data;
            $scope.editUsersData.dataUser.department_id == undefined ? '' : $scope.positiontitles_by_department = _.where($scope.positiontitles, {
                department_id: $scope.editUsersData.dataUser.department_id
            });
            $scope.setValueDepartmentGroupInput($scope.editUsersData.dataUser.department_group);
            // $scope.editUsersData.dataUser.positiontitle_id = 1;
            $scope.getListSkill();
            if ($scope.roomsall == undefined) {
                $scope.getRooms();
            }
        });
    }
    $scope.getPositiontitles = function() {
        if ($scope.posTitle.length > 0) return;
        $ionicLoading.show({
            template: templateLoading
        })
        Positiontitles.getSelect().success(function(data) {
            $ionicLoading.hide();
            $scope.positiontitles = data;
            $scope.posTitle = $scope.initNode('Position Title', data);
            // $scope.getSupplieritems();
        });
    }
    $scope.getSupplieritems = function() {
        Supplieritems.getSelect().success(function(data) {
            $scope.rootSupplieritems = data;
            $scope.getVehicles();
        })
    }
    $scope.getSupplieritems();
    $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.getDepartmentsGroupEdit = function() {
        Departments.getDepartmentsGroup({
            id: $scope.editUsersData.dataUser.department_id
        }).success(function(data) {
            if (data.length > 0) {
                $('.department_group').show();
            } else {
                $('.department_group').hide();
            }
            $scope.departmentsGroupEdit = data;
            $scope.departmentsGroup = data;
            $scope.editUsersData.dataUser.department_id == undefined ? '' : $scope.positiontitles_by_department = _.where($scope.positiontitles, {
                department_id: $scope.editUsersData.dataUser.department_id
            });
            $scope.getListSkillEdtit();
        });
    }
    $scope.getSelectListviews = function() {
        if ($scope.disableListView_Search()) return;
        Listviews.getSelect().success(function(data) {
            $scope.ListView = data;
            try {
                $scope.displayValue.defaultlistview = _.where($scope.ListView, {
                    id: $scope.usersDetail.dataUser.defaultlistview
                })[0].name;
            } catch (e) {
                $scope.displayValue.defaultlistview = "";
            }
            // $scope.getUserData();
        });
    }
    $scope.populatecurrent_hiredate = function(action, positiontitle_id) {
        $scope.Input_value.positiontitle = "";
        var positiontitle_index = _.findLastIndex($scope.positiontitles_by_department, {
            id: positiontitle_id
        });
        if (positiontitle_index >= 0) $scope.Input_value.positiontitle = $scope.positiontitles_by_department[positiontitle_index].name;
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth() + 1; //January is 0!
        var yyyy = today.getFullYear();
        if (dd < 10) {
            dd = '0' + dd
        }
        if (mm < 10) {
            mm = '0' + mm
        }
        var today = mm + '/' + dd + '/' + yyyy;
        if (action == 'add') {
            $scope.addUsersData.current_hiredate = today;
            $scope.addUsersData.current_startdate = today;
            $scope.getListSkill();
        }
        if (action == 'edit') {
            $('#current_hiredateEdit').val(today);
            $('#current_startdateEdit').val(today);
            $scope.getListSkillEdtit();
        }
    }
    $scope.fDateInput = function(data, obj) {
        // format date for edit lastservice
        var ch = Date.parseDate(data.company_hiredate);
        var cs = Date.parseDate(data.company_startdate);
        var lr = Date.parseDate(data.last_review);
        var nr = Date.parseDate(data.next_review);
        var lra = Date.parseDate(data.last_raise);
        var chi = Date.parseDate(data.current_hiredate);
        var cst = Date.parseDate(data.current_startdate);
        var dob = Date.parseDate(data.dob);
        obj.company_hiredate = globalParseDate(ch);
        obj.company_startdate = globalParseDate(cs);
        obj.last_review = globalParseDate(lr);
        obj.next_review = globalParseDate(nr);
        obj.last_raise = globalParseDate(lra);
        obj.current_hiredate = globalParseDate(chi);
        obj.current_startdate = globalParseDate(cst);
        obj.dob = globalParseDate(dob);
    }
    $scope.getUsersNewfeedType = function(itm) {
        // if ($scope.hideNewfeedCheck($scope.usersDetail.dataUser.department_id)) return;
        $scope.selectedUserId.id = itm.id;
        $scope.selectedUserId.display_name = itm.display_name;
        $scope.selectedUserId.fullname = itm.first_name + ' ' + itm.last_name;
        if (!$scope.newfeedtypesOnUser) {
            Newfeedtypes.newfeedtypesOnUser().success(function(data) {
                $scope.newfeedtypesOnUser = data;
                Users.getUsersNewfeedtype($scope.selectedUserId.id).success(function(data) {
                    $scope.newfeedtypeArrId = {
                        newfeedId: data
                    };
                });
            });
        } else {
            Users.getUsersNewfeedtype($scope.selectedUserId.id).success(function(data) {
                $scope.newfeedtypeArrId = {
                    newfeedId: data
                };
            });
        }
        $scope.openByGetTemplate_menu('popupEmployeeSendFeed');
    }
    $scope.saveUsernewfeedTypes = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Login.checkLogin().success(function(data) {
            Users.saveUsernewfeedTypes($scope.selectedUserId.id, $scope.newfeedtypeArrId).success(function(data) {
                $ionicLoading.hide();
                $scope.closeTarget('#popupEmployeeSendFeed');
                if (data.status) {
                    $cordovaToast.showShortTop(data.msg);
                } else {
                    $cordovaToast.showShortTop(data.msg);
                }
            });
        })
    }
    $scope.getUserNewfeedById = function(id) {
        for (var i = 0; i < $scope.newfeedtypesOnUser.length; i++) {
            var item = $scope.newfeedtypesOnUser[i];
            if (id == item.id) {
                $scope.selectedNewfeed = item;
            }
        };
        return $scope.selectedNewfeed;
    }
    $scope.getUsercredentials = function($close_popup_filter = false) {
        $scope.searchUsercredentials.user_id = $scope.usersDetail.dataUser.id;
        Usercredentials.getNoPaging($scope.searchUsercredentials).success(function(data) {
            $scope.usercredentials = data.data;
            if($close_popup_filter){
                $scope.closeTarget('#popupFilterLogincredential');
            }
            // $scope.replaceRes();
            // stopTime = $interval($scope.checkLogin, time_refresh);
            request_notify_get_chat = true;
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection!!!');
        });
    };
    $scope.addUsercredentialsData = {};
    $scope.createUsercredentials = function() {
        if (!$scope.addUsercredentialsData.service || !$scope.addUsercredentialsData.username || !$scope.addUsercredentialsData.password) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $scope.addUsercredentialsData.user_id = $scope.usersDetail.dataUser.id;
        $ionicLoading.show({
            template: templateLoading
        });
        Usercredentials.save($scope.addUsercredentialsData).success(function(data) {
            $ionicLoading.hide();
            $scope.closeTarget('#popupEmployeeLoginCredentialsAdd');
            if (data.status) {
                $scope.getUsercredentials();
                $scope.addUsercredentialsData = {};
                $cordovaToast.showShortTop(data.msg);
            } else {
                $cordovaToast.showShortTop(data.msg);
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Add Errror!!!');
        });
    }
    $scope.editUsercredentialsData = {};
    $scope.editUsercredentials = function(id) {
        $scope.openByGetTemplate_menu('popupEmployeeLoginCredentialsEdit');
        $ionicLoading.show({
            template: templateLoading
        });
        Usercredentials.show(id).success(function(data) {
            $ionicLoading.hide();
            $scope.editUsercredentialsData = data.data;
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Errror!!!');
        });
    }
    $scope.updateUsercredentials = function() {
        if (!$scope.editUsercredentialsData.service || !$scope.editUsercredentialsData.username || !$scope.editUsercredentialsData.password) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        var id = $scope.editUsercredentialsData.id;
        $ionicLoading.show({
            template: templateLoading
        });
        Usercredentials.update(id, $scope.editUsercredentialsData).success(function(data) {
            $ionicLoading.hide();
            $scope.getUsercredentials();
            $scope.closeTarget('#popupEmployeeLoginCredentialsEdit');
            if (data.status) {
                $scope.editUsercredentialsData = {};
                $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 Errror!!!');
        });
    }
    $scope.confrimUsercredentials = function(id) {
        $scope.deleteUsercredentialsData = {
            id: id
        };
        $scope.openByGetTemplate_menu('popupEmployeeLoginCredentialsDelete');
    }
    $scope.confrimActiveOrDeactiveUsercredentials = function(item) {
        $scope.activeOrDeactiveCredentialItem = item;
        $scope.deleteUsercredentialsData = {
            id: item.id
        };
        $scope.openByGetTemplate_menu('confirmActiveOrDeactiveCredential');
    }
    $scope.deleteUsercredentials = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Usercredentials.destroy($scope.deleteUsercredentialsData.id).success(function(data) {
            $ionicLoading.hide();
            $scope.deleteUsercredentialsData = {};
            $scope.closeTarget('#popupEmployeeLoginCredentialsDelete');
            $scope.getUsercredentials();
            if (data.status) {
                $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 Errror!!!');
        });
    }
    $scope.loadUserlogs = function(user_id) {
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.loadUserlogs(user_id).success(function(data) {
            $ionicLoading.hide();
            $scope.dataLog = data;
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Errror!!!');
        });
    };
    $scope.dataAddIssueLog = {};
    $scope.addIssueLog = function() {
        if (!$scope.dataAddIssueLog.contents || !$scope.dataAddIssueLog.description) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $scope.dataAddIssueLog.user_id = $scope.usersDetail.dataUser.id;
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.addIssueLog($scope.dataAddIssueLog).success(function(data) {
            $ionicLoading.hide();
            $scope.closeTarget('#popupEmployeeIssueLogAdd');
            if (data.status) {
                $scope.dataAddIssueLog = {};
                $scope.loadUserlogs($scope.usersDetail.dataUser.id);
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Errror!!!');
        });
    };
    $scope.getDataIssueLogById = function(id) {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.openByGetTemplate_menu('popupEmployeeIssueLogEdit');
        Userdetails.getDataIssueLogById(id).success(function(data) {
            $ionicLoading.hide();
            // data.contents = parseInt(data.contents);
            $scope.initialUsers = data.input.id;
            $scope.dataUpdateIssueLog = data;
            $scope.dataUpdateIssueLog.contents = $scope.dataUpdateIssueLog.contents.toString();
        });
    }
    $scope.updateIssueLog = function() {
        if (!$scope.dataUpdateIssueLog.contents || !$scope.dataUpdateIssueLog.description || !$scope.dataUpdateIssueLog.input || !$scope.dataUpdateIssueLog.date) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        var id = $scope.dataUpdateIssueLog.id;
        $scope.dataUpdateIssueLog.date = $('#dataUpdateIssueLogDate').html();
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.updateIssueLog(id, $scope.dataUpdateIssueLog).success(function(data) {
            $scope.closeTarget('#popupEmployeeIssueLogEdit');
            $ionicLoading.hide();
            if (data.status) {
                $scope.dataUpdateIssueLog = {};
                $scope.loadUserlogs($scope.usersDetail.dataUser.id);
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Errror!!!');
        });
    };
    $scope.userAutocompleteList = {};
    $scope.filterUsers = function(query, isInitializing) {
        if (!query) return;
        var returnValue = {
            items: []
        };
        var params = {
            search: query
        };
        Users.searchAllUser(params).success(function(data) {
            $scope.allUserSelect = data;
            var id = $scope.userAutocompleteList.id;
            $scope.allUserSelect.forEach(function(item) {
                if (id != item.id) {
                    if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    } else if (item.id.toString().indexOf(query) > -1) {
                        returnValue.items.push(item);
                    }
                }
            });
        })
        return returnValue;
    }
    $scope.getAllUsers = function() {
        if ($scope.disableListView_Search()) return;
        var params = {
            search: ''
        };
        Users.searchAllUser(params).success(function(data) {
            $scope.allUserSelect = data;
        })
    }
    $scope.modelToItemMethodUser = function(modelValue) {
        for (var i = 0; i < $scope.allUserSelect.length; i++) {
            if ($scope.allUserSelect[i].id == modelValue) {
                return $scope.allUserSelect[i];
            }
        }
        return {};
    };
    $scope.onSelectUser = function(callback) {
        $scope.dataUpdateIssueLog.input = callback.item;
        // console.log($scope.searchData.data);
    }
    $scope.onRemoveUser = function(callback) {
        $scope.dataUpdateIssueLog.input = [];
        // console.log($scope.searchData.data);
    }
    $scope.confirmlog = function(id) {
        $scope.dataDeleteLogIssue = {
            id: id
        };
        $scope.openByGetTemplate_menu('popupEmployeeIssueLogDelete');
    }
    $scope.deleteLogIssue = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.deleteLogIssue($scope.dataDeleteLogIssue.id).success(function(data) {
            $scope.closeTarget('#popupEmployeeIssueLogDelete');
            $ionicLoading.hide();
            if (data.status) {
                $scope.loadUserlogs($scope.usersDetail.dataUser.id);
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Errror!!!');
        });
    }
    $scope.getlist_fieldwork = function(id) {
        Userdetails.getlist_fieldwork(id).success(function(data) {
            $scope.listfieldwork = data.list_fieldwork;
            $scope.list_touser = {
                roles: data.list_touser
            };
        });
    }
    $scope.save_lisibility = function(id) {
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.save_lisibility(id, $scope.list_touser.roles).success(function(data) {
            $ionicLoading.hide();
            $scope.closeTarget('#popupEmployeeDetailVisibility');
            if (data.status) {
                $cordovaToast.showShortTop(data.msg);
            } else {
                $cordovaToast.showShortTop(data.msg);
            }
        });
    }
    $scope.changeDefaultListView = function(listview_id) {
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.changeDefaultListView(listview_id, $scope.usersDetail.dataUser.id).success(function(data) {
            $scope.closeTarget('#popupEmployeeDetailDefaultListView');
            $ionicLoading.hide();
            if (data.status) {
                try {
                    $scope.displayValue.defaultlistview = _.where($scope.ListView, {
                        id: $scope.usersDetail.dataUser.defaultlistview
                    })[0].name;
                } catch (e) {
                    $scope.displayValue.defaultlistview = "";
                }
                $cordovaToast.showShortTop(data.msg);
            } else {
                $cordovaToast.showShortTop(data.msg);
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Errror!!!');
        });
    }
    $scope.getListSkillEdtit = function() {
        // console.log($scope.editUsersData.dataUserPositiontitles.positiontitle_id);
        Skills.getListSkillEdtit($scope.editUsersData.dataUserPositiontitles.positiontitle_id).success(function(data) {
            $scope.listSkillCheckbox = data.data;
            $scope.editUsersData.dataUserSkill = data.data;
            // if ($.isNumeric($scope.editUsersData.dataUser.pushchatroom)) {
            //     $scope.editUsersData.dataUser.pushchatroom = parseInt($scope.editUsersData.dataUser.pushchatroom);
            // }
            // else {
            //     $scope.editUsersData.dataUser.pushchatroom = String($scope.editUsersData.dataUser.pushchatroom);
            // }
            if ($scope.roomsall == undefined) {
                $scope.getRooms();
            } else {
                $scope.getRoles();
            }
        });
    }
    $scope.getRoles = function() {
        if ($scope.activeRoles) return;
        Roles.getSelect().success(function(data) {
            $scope.roles = data;
            $scope.getAppointmentgroups();
            $scope.activeRoles = true;
        });
    }
    $scope.getRooms = function() {
        Rooms.getSelect().success(function(data) {
            $scope.roomsall = data;
            $scope.getRoles();
        });
    }
    $scope.getAppointmentgroups = function() {
        Appointmentgroups.getSelect().success(function(data) {
            $scope.appointmentgroups = data;
            $scope.rootAppGroups = _.filter($scope.appointmentgroups, function(val) {
                return val.department_id != null;
            });
            $scope.getUsersVisor();
        });
    }
    $scope.getAssignedlocations = function() {
        Users.getAssignedLocationsSelect().success(function(data) {
            $scope.assignedLocations = data;
            $scope.getWageDetails();
        });
    }
    $scope.getWageDetails = function() {
        Users.getWageDetailsSeletect().success(function(data) {
            $scope.wagedetails = data;
        });
    }
    $scope.getVehicles = function() {
        Users.getAllVehicles().success(function(data) {
            $scope.allVehicles = data;
            $scope.getAssignedlocations();
        });
    }
    $scope.getUsersVisor = function() {
        Users.getSelect().success(function(data) {
            // $scope.usersVisor = data;
            $scope.usersVisor = _.each(data, function(val) {
                return _.extend(val, {
                    name: val.first_name + val.last_name
                });
            });
            $scope.$broadcast('setConditionAdd', {});
            // add N/A
            $scope.createNA();
        });
    }
    $scope.createNA = function() {
        var na = {};
        na.nameWithpos = 'N/A';
        na.id = -1;
        na.supervisor_user1 = -1;
        na.supervisor_user2 = -1;
        _.where($scope.usersVisor, {
            id: -1
        }).length > 0 ? '' : $scope.usersVisor.unshift(na);
    }
    $scope.getSuppliersItem = function(query, isInitializing, style) {
        var returnValue = {
            items: []
        };
        var listIdArray = $scope.autocompleteList.dataUserSuppliersCreate;
        if (style != 'add') {
            listIdArray = $scope.autocompleteList.dataUserSuppliersEdit;
        }
        $scope.rootSupplieritems.forEach(function(item) {
            if (listIdArray.indexOf(item.id) < 0) {
                if (item.name && 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.setValueForInputSuppliersItem = function(modelValue) {
        for (var i = 0; i < $scope.rootSupplieritems.length; i++) {
            if ($scope.rootSupplieritems[i].id == modelValue) {
                // data={id:$scope.rootSupplieritems[i].id,name:$scope.rootSupplieritems[i].name};
                return $scope.rootSupplieritems[i];
            }
        }
        return {};
    };
    $scope.initialSuppliersItemEdit = [];
    $scope.setValueForInputSuppliersItemEdit = function(modelValue) {
        for (var i = 0; i < $scope.rootSupplieritems.length; i++) {
            if ($scope.rootSupplieritems[i].id == modelValue) {
                // data={id:$scope.rootSupplieritems[i].id,name:$scope.rootSupplieritems[i].name};
                return $scope.rootSupplieritems[i];
            }
        }
        return {};
    };
    $scope.clickedMethodSuppliersItem = function(callback, style) {
        if (style == 'add') {
            if ($scope.addUsersData.supplieritems.indexOf(callback.item) < 0) $scope.addUsersData.supplieritems.push(callback.item);
        } else {
            var flag = true;
            for (var i = $scope.editUsersData.dataSupplieritems.length - 1; i >= 0; i--) {
                if ($scope.editUsersData.dataSupplieritems[i].id == callback.item.id) {
                    flag = false;
                }
            }
            if (flag) $scope.editUsersData.dataSupplieritems.push(callback.item);
        }
    }
    $scope.removeMethodSuppliersItem = function(callback, style) {
        if (style == 'add') {
            var index = $scope.addUsersData.supplieritems.indexOf(callback.item);
            $scope.addUsersData.supplieritems.splice(index, 1);
        } else {
            for (var i = $scope.editUsersData.dataSupplieritems.length - 1; i >= 0; i--) {
                if ($scope.editUsersData.dataSupplieritems[i].id == callback.item.id) {
                    $scope.editUsersData.dataSupplieritems.splice(i, 1);
                }
            }
        }
    }
    $scope.getAppointmentGroup = function(query, isInitializing, style) {
        var listIdArray = $scope.autocompleteList.dataUserAppointmentGroupsCreate;
        var returnValue = {
            items: []
        };
        if (style != 'add') {
            listIdArray = $scope.autocompleteList.dataUserAppointmentGroupsEdit;
        }
        $scope.rootAppGroupsMobile.forEach(function(item) {
            if (listIdArray.indexOf(item.id) < 0) {
                if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    returnValue.items.push(item);
                } else if (item.id.indexOf(query) > -1) {
                    returnValue.items.push(item);
                }
            }
        });
        return returnValue;
    };
    $scope.setValueForAppointmentGroup = function(modelValue) {
        for (var i = 0; i < $scope.rootAppGroupsMobile.length; i++) {
            if ($scope.rootAppGroupsMobile[i].id == modelValue) {
                return $scope.rootAppGroupsMobile[i];
            }
        }
        return {};
    };
    $scope.initialAppointmentGroupEdit = [];
    $scope.setValueForAppointmentGroupEdit = function(modelValue) {
        for (var i = 0; i < $scope.rootAppGroupsMobile.length; i++) {
            if ($scope.rootAppGroupsMobile[i].id == modelValue) {
                return $scope.rootAppGroupsMobile[i];
            }
        }
        return {};
    };
    $scope.getAppointmentgroupsMobile = function() {
        Appointmentgroups.getSelect().success(function(data) {
            $scope.rootAppGroupsMobile = _.filter(data, function(val) {
                return val.department_id != null;
            });
        });
    }
    $scope.getAppointmentgroupsMobile();
    $scope.clickedMethodAppGroup = function(callback, style) {
        if (style == 'add') {
            if ($scope.addUsersData.appointmentgroup_id.indexOf(callback.item) < 0) $scope.addUsersData.appointmentgroup_id.push(callback.item);
        } else {
            var flag = true;
            for (var i = $scope.editUsersData.dataUserAppointmentGroups.length - 1; i >= 0; i--) {
                if ($scope.editUsersData.dataUserAppointmentGroups[i].id == callback.item.id) {
                    flag = false;
                }
            }
            if (flag) $scope.editUsersData.dataUserAppointmentGroups.push(callback.item);
        }
    }
    $scope.removeMethodAppGroup = function(callback, style) {
        if (style == 'add') {
            var index = $scope.addUsersData.appointmentgroup_id.indexOf(callback.item);
            $scope.addUsersData.appointmentgroup_id.splice(index, 1);
        } else {
            for (var i = $scope.editUsersData.dataUserAppointmentGroups.length - 1; i >= 0; i--) {
                if ($scope.editUsersData.dataUserAppointmentGroups[i].id == callback.item.id) {
                    $scope.editUsersData.dataUserAppointmentGroups.splice(i, 1);
                }
            }
        }
    }
    $scope.setValueForInput = function(arrData, id) {
        var result = '';
        var index = _.findLastIndex(arrData, {
            id: id
        });
        if (index >= 0) result = arrData[index];
        return result;
    }
    $scope.setValueDepartmentGroupInput = function(deparment_group_id) {
        $scope.Input_value.departmentGroup = "";
        $scope.Input_value.departmentGroup = $scope.setValueForInput($scope.departmentsGroup, deparment_group_id).name;
    }
    $scope.setValueRoleInput = function(role_id) {
        $scope.Input_value.role = "";
        $scope.Input_value.role = $scope.setValueForInput($scope.roles, role_id).name;
    }
    $scope.setValueSuperVisor1Input = function(supervisor_user1_id) {
        $scope.Input_value.supervisor_user1 = "";
        $scope.Input_value.supervisor_user1 = $scope.setValueForInput($scope.usersVisor, supervisor_user1_id).nameWithpos;
    }
    $scope.setValueSuperVisor2Input = function(supervisor_user2_id) {
        $scope.Input_value.supervisor_user2 = "";
        $scope.Input_value.supervisor_user2 = $scope.setValueForInput($scope.usersVisor, supervisor_user2_id).nameWithpos;
    }
    $scope.setValuePushChatRoomInput = function(pushChatRoom_id) {
        $scope.Input_value.pushchatroom = "";
        $scope.Input_value.pushchatroom = $scope.setValueForInput($scope.roomsall, pushChatRoom_id).name;
    }
    $scope.setValueUserType = function(usertype_id) {
        $scope.Input_value.usertype = "";
        $scope.Input_value.usertype = $scope.setValueForInput($scope.usertypes, usertype_id).name;
    }
    $scope.setValueAssignLocation = function(assigned_location_id) {
        $scope.Input_value.assigned_location = "";
        $scope.Input_value.assigned_location = $scope.setValueForInput($scope.assignedLocations, assigned_location_id).name;
    }
    $scope.setValueCurrentWageDetail = function(currentwage_detail_id) {
        $scope.Input_value.currentwage_detail_name = "";
        $scope.Input_value.currentwage_detail_name = $scope.setValueForInput($scope.wagedetails, currentwage_detail_id).name;
    }
    $scope.setValueStartingWageDetail = function(startwage_detail_id) {
        $scope.Input_value.startwage_detail_name = "";
        $scope.Input_value.startwage_detail_name = $scope.setValueForInput($scope.wagedetails, startwage_detail_id).name;
    }
    $scope.setValueDriverornot = function(driverornot){
        if(driverornot != undefined){
            $scope.Input_value.driverornot = "";
            $scope.Input_value.driverornot = $scope.setValueForInput($scope.driverOrNotSelect, driverornot).name;
        }else{
            $scope.Input_value.driverornot = "Select";
        }
    }
    $scope.data = {};
    $scope.callNumber = function(number, extension) {
        if (!isiOs) {
            if (extension) number = number + 'p' + extension;
            window.open('tel:' + number, '_system');
            return;
        }
        $scope.data.phoneNumber = number.replace(/[^0-9]/g, '');
        if (extension) $scope.data.phoneNumber = $scope.data.phoneNumber + ',' + extension;
        var myPopup = $ionicPopup.show({
            template: '<input type="tel" ng-model="data.phoneNumber">',
            scope: $scope,
            buttons: [{
                text: 'Cancel',
                onTap: function(e) {}
            }, {
                text: '<b>Call</b>',
                type: 'button-positive',
                onTap: function(e) {
                    window.open('tel:' + $scope.data.phoneNumber, '_system');
                }
            }]
        });
    }
    $scope.openGoogleMap = function(address) {
        
        if (isiOs) {
            launchnavigator.navigate(address,{TRANSPORT_MODE:launchnavigator.TRANSPORT_MODE.DRIVING});
        }  else {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    $scope.myLat = position.coords.latitude;
                    $scope.myLng = position.coords.longitude;
                    url = "https://www.google.com/maps/dir/" + $scope.myLat + "," + $scope.myLng + '/' + encodeURIComponent(address);
                    window.open(url, "_system", 'location=no');
                });
            }
        }
    }
    $scope.getDefaultSchedule = function(user_id) {
        $scope.openByGetTemplate_menu('popupEmployeeDefaultSchedule');
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.getDefaultSchedule(user_id).success(function(data) {
            $ionicLoading.hide();
            $scope.DefaultSchedule = data.data;
            $scope.DefaultScheduleNext = data.nextweek;
            $scope.checkpush = data.checkpush;
            for (var i = 0; i < $scope.DefaultSchedule.length; i++) {
                if ($scope.DefaultSchedule[i].from_hour != $scope.DefaultSchedule[i].to_hour) {
                    $scope.DefaultSchedule[i].checked = true;
                }
                $scope.DefaultSchedule[i].from_hour = moment($scope.DefaultSchedule[i].from_hour, 'hh:mm:ss').format('hh:mmA');
                $scope.DefaultSchedule[i].to_hour = moment($scope.DefaultSchedule[i].to_hour, 'hh:mm:ss').format('hh:mmA');
            }
            for (var i = 0; i < $scope.DefaultScheduleNext.length; i++) {
                if ($scope.DefaultScheduleNext[i].from_hour != $scope.DefaultScheduleNext[i].to_hour) {
                    $scope.DefaultScheduleNext[i].checked = true;
                }
                $scope.DefaultScheduleNext[i].from_hour = moment($scope.DefaultScheduleNext[i].from_hour, 'hh:mm:ss').format('hh:mmA');
                $scope.DefaultScheduleNext[i].to_hour = moment($scope.DefaultScheduleNext[i].to_hour, 'hh:mm:ss').format('hh:mmA');
            }
        });
    };
    $scope.updateDefaultSchedule = function() {
        var arrData = [];
        var arrDataNext = [];
        arrData = $scope.DefaultSchedule;
        arrDataNext = $scope.DefaultScheduleNext;
        var checked = 0;
        for (var i = 0; i < $scope.DefaultSchedule.length; i++) {
            if ($scope.DefaultSchedule[i].checked) {
                var flag = validateTime($scope.DefaultSchedule[i].from_hour, $scope.DefaultSchedule[i].to_hour);
                if (!flag.status) {
                    $scope.DefaultSchedule[i].to_hour = '00:00';
                    checked = 1;
                }
            }
        }
        for (var i = 0; i < $scope.DefaultScheduleNext.length; i++) {
            if ($scope.DefaultScheduleNext[i].checked) {
                var flag = validateTime($scope.DefaultScheduleNext[i].from_hour, $scope.DefaultScheduleNext[i].to_hour);
                if (!flag.status) {
                    $scope.DefaultScheduleNext[i].to_hour = '00:00';
                    checked = 1;
                }
            }
        }
        if (checked == 1) {
            $cordovaToast.showLongTop('End time must be greater than start time!!!');
            return;
        }
        for (var i = 0; i < arrData.length; i++) {
            if (arrData[i].checked) {
                var from = $('#dfBiweeksStart' + i).val();
                var to = $('#dfBiweeksEnd' + i).val();
                arrData[i].from_hour = moment(from, 'h:mmA').format('HH:mm:ss');
                arrData[i].to_hour = moment(to, 'h:mmA').format('HH:mm:ss');
            } else {
                arrData[i].from_hour = "00:00:00";
                arrData[i].to_hour = "00:00:00";
            }
        }
        for (var i = 0; i < arrDataNext.length; i++) {
            if (arrDataNext[i].checked) {
                var from = $('#dfBiweeksStartNext' + i).val();
                var to = $('#dfBiweeksEndNext' + i).val();
                arrDataNext[i].from_hour = moment(from, 'h:mmA').format('HH:mm:ss');
                arrDataNext[i].to_hour = moment(to, 'h:mmA').format('HH:mm:ss');
            } else {
                arrDataNext[i].from_hour = "00:00:00";
                arrDataNext[i].to_hour = "00:00:00";
            }
        }
        var AllSchedule = arrData.concat(arrDataNext);
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.updateDefaultSchedule(AllSchedule).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
            $scope.closeTarget('#popupEmployeeDefaultSchedule');
        });
    };
    $scope.pushschedulesingle = function(user_id) {
        Users.pushschedulesingle(user_id).success(function(data) {
            $scope.closeTarget('#defaultSchedule');
            // $('#pushschedulesingle').hide();
        });
    }
    $scope.showPipusExport = false;
    $scope.getPipus = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailPipusmodal.tpl').success(function(results) {
            $scope.menuHtml.popupEmployeePunchInOutHistory = results;
            $timeout(function() {
                $scope.showTarget('#popupEmployeePunchInOutHistory');
                // $scope.getUserLogin();
                $scope.searchPipus.start_time = $('#start_time').html();
                $scope.searchPipus.end_time = $('#end_time').html();
                $('#displayStartDate .day').html(moment($scope.searchPipus.start_time, 'MM/DD/YYYY').format('DD'));
                $('#displayStartDate .month').html(moment($scope.searchPipus.start_time, 'MM/DD/YYYY').format('MMMM'));
                $('#displayEndDate .day').html(moment($scope.searchPipus.end_time, 'MM/DD/YYYY').format('DD'));
                $('#displayEndDate .month').html(moment($scope.searchPipus.end_time, 'MM/DD/YYYY').format('MMMM'));
                $scope.searchPipus.userId = $scope.usersDetail.dataUser.id;
                Userdetails.pipusGetPaging($scope.searchPipus).success(function(data) {
                    $scope.setTime = true;
                    $ionicLoading.hide();
                    for (var i = 0; i < data.data.length; i++) {
                        data.data[i].orderBy = data.data[i].from_hour;
                        data.data[i].from_hour != null ? data.data[i].from_hour = moment(data.data[i].from_hour, 'hh:mm').format('hh:mmA') : '';
                        data.data[i].to_hour != null ? data.data[i].to_hour = moment(data.data[i].to_hour, 'hh:mm').format('hh:mmA') : '';
                        data.data[i].dateShow = moment(data.data[i].dateShow, 'MM/DD/YYYY').format('YYYY/MM/DD');
                    }
                    if (data.data.length > 0) {
                        $scope.showPipusExport = true;
                    } else {
                        $scope.showPipusExport = false;
                    }
                    data.data = _.sortBy(data.data, 'dateShow').reverse();
                    $scope.pipusForExport = data.data;
                    $scope.pipus = _.groupBy(data.data, 'dateShow');
                    $scope.totalTime = data.totalTime;
                    $ionicScrollDelegate.$getByHandle('scrollPipusManagerment').resize();
                    $ionicScrollDelegate.$getByHandle('scrollPipusManagerment').scrollTop(true);
                }).error(function() {
                    $ionicLoading.hide();
                    $cordovaToast.showLongTop('Connection error!!!');
                });
            })
        }, 1)
    };
    $scope.$watch('time.start', function(value) {
        if ($scope.setTime) {
            $('#start_time').html(moment(value).format('MM/DD/YYYY'));
            $scope.searchPipus.current_page = 1;
            $scope.getPipus();
        }
    })
    $scope.$watch('time.end', function(value) {
        if ($scope.setTime) {
            $('#end_time').html(moment(value).format('MM/DD/YYYY'));
            $scope.searchPipus.current_page = 1;
            $scope.getPipus();
        }
    })
    $scope.calculateTimeWorked = function(arr) {
        var totalTime = 0;
        arr.forEach(function(item) {
            var arrDuration = item.duration.split(' ');
            var duration = parseInt(arrDuration[0] * 60) + parseInt(arrDuration[2]);
            totalTime += duration;
        })
        var h = Math.floor(totalTime / 60);
        var m = totalTime % 60;
        return h + ' hours ' + m + ' minutes';
    }
    $scope.convertDate = function(value, format) {
        return moment(value).format(format);
    }
    $scope.createPipus = function() {
        if (!$scope.addPipusData.date || !$scope.addPipusData.from_hour) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        if ($scope.addPipusData.to_hour) {
            var check = validateTime($scope.addPipusData.from_hour, $scope.addPipusData.to_hour);
            if (!check.status) {
                $scope.addPipusData.to_hour = '';
                $cordovaToast.showLongTop('End time must be greater than start time');
                return;
            }
        }
        var objectData = $scope.addPipusData;
        objectData.hasPunchOut = true;
        objectData.user_id = $scope.usersDetail.dataUser.id;
        objectData.date_value = moment(objectData.date).format('YYYY-MM-DD');
        objectData.date = $('#addPipusDate').html();
        objectData.from_hour = $('#addPipusFromHour').html();
        if (check) {
            objectData.from_hour_value = check.start;
            objectData.to_hour_value = check.end;
            objectData.to_hour = $('#addPipusToHour').html();
            objectData.duration = moment(check.end, 'HH:mm').diff(moment(check.start, 'HH:mm'), 'minutes');
        } else {
            objectData.from_hour_value = moment(objectData.from_hour, 'hh:mmA').format('HH:mm:ss');
            objectData.hasPunchOut = false;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Pipus.save(objectData).success(function(data) {
            $ionicLoading.hide();
            $timeout(function() {
                $scope.closeTarget('#popupEmployeePunchInOutHistoryAdd')
            }, 2000);
            $scope.getPipus();
            if (data.status) {
                $scope.addPipusData = {};
                $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.editPipusData = {};
    $scope.editPipus = function(id) {
        $scope.openByGetTemplate_menu('popupEmployeePunchInOutHistoryEdit');
        $ionicLoading.show({
            template: templateLoading
        });
        Pipus.show(id).success(function(data) {
            $ionicLoading.hide();
            $scope.editPipusData = data;
            $scope.editPipusData.from_hour != null ? $scope.editPipusData.from_hour = moment($scope.editPipusData.from_hour, 'HH:mm:ss').format('h:mmA') : '';
            $scope.editPipusData.to_hour != null ? $scope.editPipusData.to_hour = moment($scope.editPipusData.to_hour, 'HH:mm:ss').format('h:mmA') : '';
            // $("#editPipusFromHour").val($scope.editPipusData.from_hour);
            // $("#editPipusToHour").val($scope.editPipusData.to_hour);
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.updatePipus = function() {
        if (!$scope.editPipusData.from_hour) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        if ($scope.editPipusData.to_hour && $scope.editPipusData.to_hour != "") {
            var check = validateTime($scope.editPipusData.from_hour, $scope.editPipusData.to_hour);
            if (!check.status) {
                $scope.editPipusData.to_hour = '';
                $cordovaToast.showLongTop('End time must be greater than start time');
                return;
            }
        }
        var objectData = $scope.editPipusData;
        objectData.from_hour = $('#editPipusFromHour').html();
        objectData.to_hour = $('#editPipusToHour').html();
        var id = objectData.id;
        $ionicLoading.show({
            template: templateLoading
        });
        Pipus.update(id, objectData).success(function(data) {
            $ionicLoading.hide();
            $scope.getPipus();
            $timeout(function() {
                $scope.closeTarget('#punchManagementEdit')
            }, 2000);
            if (data.status) {
                $scope.editPipusData = {};
                $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.confirmpipus = function(id) {
        $scope.openByGetTemplate_menu('popupEmployeePunchInOutHistoryDelete');
        $scope.selectedPipus = {
            id: id
        };
    }
    $scope.deletePipus = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Pipus.destroy($scope.selectedPipus.id).success(function(data) {
            $ionicLoading.hide();
            $scope.closeTarget("#popupEmployeePunchInOutHistoryDelete");
            $scope.getPipus();
            if (data.status) {
                $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.exportDataPipus = function() {
        $scope.dataExportPipus = {
            userId: $scope.searchPipus.userId,
            start_time: $scope.searchPipus.start_time,
            end_time: $scope.searchPipus.end_time,
            for_me: true
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Userdetails.exportPipus($scope.dataExportPipus).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.dataExportPipus = {};
                var link = data.link.replace('./../', url_site.replace('public', ''));
                $scope.cordovaBrowser(link, 'internal');
            }
        });
    }
    $scope.hideJobAndHrAndManager = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
        switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            if ($scope.currentIdLogin == userId) {
                return false;
            } else {
                return true;
            }
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                //admin
                case $scope.isAdmin:
                return false;
                break;
                //manager
                case $scope.isManager:
                if ($scope.currentIdLogin == userId) return false;
                if (parseInt(roleId) == 2) {
                    if ((parseInt(supervisorUser) == parseInt($scope.currentIdLogin) || parseInt(supervisorUser2) == parseInt($scope.currentIdLogin)) && departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                }
                break;
                //isReporter
                case $scope.isReporter:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                //isScheduler
                case $scope.isScheduler:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isWarehouse:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isInFieldSupervisor:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == userId || $scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isOutsideSales:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                default:
                return true;
            }
        }
        $scope.hideLoginCredential = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
                case $scope.isSalesman:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isFieldinstaller:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isStrategicDevelopment:
                if ($scope.currentIdLogin == userId) return false;
                if ($scope.users) {
                    if ($scope.users.dataRole.route_name == $scope.isAdmin) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }
                break;
                case $scope.isManager:
                if ($scope.currentIdLogin == userId) return false;
                if (parseInt(roleId) == 2) {
                    if ((parseInt(supervisorUser) == parseInt($scope.currentIdLogin) || parseInt(supervisorUser2) == parseInt($scope.currentIdLogin)) && departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                }
                break;
                case $scope.isReporter:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isScheduler:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isWarehouse:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isOutsideSales:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isInFieldSupervisor:
                if ($scope.currentIdLogin == userId || $scope.currentIdLogin == supervisorUser) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2 || $scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                default:
                return true;
            }
        }
        $scope.hideLoginCredentialAction = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            if ($scope.currentIdLogin == userId) {
                return false;
            } else {
                return true;
            }
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                if ($scope.currentIdLogin == userId) return false;
                return true;
                break;
                //admin
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isStrategicDevelopment:
                if ($scope.currentIdLogin == userId) return false;
                if ($scope.users) {
                    if ($scope.users.dataRole.route_name == $scope.isAdmin) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }
                break;
                //manager
                case $scope.isManager:
                if ($scope.currentIdLogin == userId) return false;
                if (parseInt(roleId) == 2) {
                    if ((parseInt(supervisorUser) == parseInt($scope.currentIdLogin) || parseInt(supervisorUser2) == parseInt($scope.currentIdLogin)) && departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                }
                break;
                //isReporter
                case $scope.isReporter:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                //isScheduler
                case $scope.isScheduler:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isWarehouse:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isOutsideSales:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isInFieldSupervisor:
                if ($scope.currentIdLogin == userId || $scope.currentIdLogin == supervisorUser) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2 || $scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                default:
                return true;
            }
        }
        $scope.hideDefaultListView = function(userId, departmentId) {
            switch ($scope.roleName) {
                case $scope.isSalesman:
                return true;
                break;
                case $scope.isFieldinstaller:
                if ($scope.currentIdLogin == userId) return false;
                return true;
                break;
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isManager:
                if (departmentId == $scope.departmentId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isReporter:
                return true;
                break;
                case $scope.isScheduler:
                return true;
                break;
                case $scope.isWarehouse:
                return true;
                break;
                case $scope.isStrategicDevelopment:
                return false;
                break;
                case $scope.isSupportAssistant:
                return true;
                break;
                case $scope.isOutsideSales:
                return true;
                break;
                case $scope.isInFieldSupervisor:
                return true;
                break;
            }
        }
        $scope.hideIssueLogAndVisibilty = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            return true;
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                return true;
                break;
                //admin
                case $scope.isAdmin:
                return false;
                break;
                //manager
                case $scope.isManager:
                if (parseInt(roleId) == 2) {
                    if ((parseInt(supervisorUser) == parseInt($scope.currentIdLogin) || parseInt(supervisorUser2) == parseInt($scope.currentIdLogin)) && departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                }
                break;
                //isReporter
                case $scope.isReporter:
                return true;
                break;
                //isScheduler
                case $scope.isScheduler:
                return true;
                break;
                case $scope.isWarehouse:
                return true;
                break;
                default:
                return true;
            }
        }
        $scope.hideFileManagement = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
                case $scope.isSalesman:
                return true;
                break;
                case $scope.isFieldinstaller:
                return true;
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isManager:
                return true;
                break;
                case $scope.isReporter:
                return true;
                break;
                case $scope.isScheduler:
                return true;
                break;
                case $scope.isWarehouse:
                return true;
                break;
                case $scope.isStrategicDevelopment:
                if ($scope.users) {
                    if ($scope.users.dataRole.route_name == $scope.isAdmin) {
                        return true;
                    } else {
                        return false;
                    }
                }
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isOutsideSales:
                return true;
                break;
                case $scope.isInFieldSupervisor:
                if ($scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                break;
                default:
                return true;
            }
        }
        $scope.editAblePipus = function(departmentId) {
            switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            return false;
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                return false;
                break;
                //admin
                case $scope.isAdmin:
                return true;
                break;
                //manager
                case $scope.isManager:
                if (departmentId == $scope.departmentId) {
                    return true;
                } else {
                    return false;
                }
                break;
                //isReporter
                case $scope.isReporter:
                return false;
                break;
                //isScheduler
                case $scope.isScheduler:
                return false;
                break;
                case $scope.isWarehouse:
                return false;
                break;
                default:
                return false;
            }
        }
        $scope.hideSettingTab = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            if ($scope.currentIdLogin == userId) {
                return false;
            } else {
                return true;
            }
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                //admin
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isStrategicDevelopment:
                // return false;
                if ($scope.currentIdLogin == supervisorUser) {
                    return false;
                } else {
                    return true;
                }
                break;
                //manager
                case $scope.isManager:
                if ($scope.currentIdLogin == userId) return false;
                if (parseInt(roleId) == 2) {
                    if ((parseInt(supervisorUser) == parseInt($scope.currentIdLogin) || parseInt(supervisorUser2) == parseInt($scope.currentIdLogin)) && departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                }
                break;
                //isReporter
                case $scope.isReporter:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                //isScheduler
                case $scope.isScheduler:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isWarehouse:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == userId || $scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isOutsideSales:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isInFieldSupervisor:
                if ($scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                break;
                default:
                return true;
            }
        }
        $scope.hideDefaultSchedules = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
                case $scope.isSalesman:
                return true;
                break;
                case $scope.isFieldinstaller:
                return true;
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isManager:
                return true;
                break;
                case $scope.isReporter:
                return true;
                break;
                case $scope.isScheduler:
                return true;
                break;
                case $scope.isWarehouse:
                return true;
                break;
                case $scope.isStrategicDevelopment:
                if ($scope.users) {
                    if ($scope.users.dataRole.route_name == $scope.isAdmin) {
                        return true;
                    } else {
                        return false;
                    }
                }
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isOutsideSales:
                return true;
                break;
                case $scope.isInFieldSupervisor:
                if ($scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                break;
                default:
                return true;
            }
        }
        $scope.hidePipus = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
                case $scope.isSalesman:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isFieldinstaller:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isStrategicDevelopment:
                if ($scope.users) {
                    if ($scope.users.dataRole.route_name == $scope.isAdmin) {
                        return true;
                    } else {
                        return false;
                    }
                }
                break;
                case $scope.isManager:
                if ($scope.currentIdLogin == userId) return false;
                if (parseInt(roleId) == 2) {
                    if ((parseInt(supervisorUser) == parseInt($scope.currentIdLogin) || parseInt(supervisorUser2) == parseInt($scope.currentIdLogin)) && departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                }
                break;
                case $scope.isReporter:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isScheduler:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isWarehouse:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isOutsideSales:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isInFieldSupervisor:
                if ($scope.currentIdLogin == userId || $scope.currentIdLogin == supervisorUser) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == userId || $scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                break;
                default:
                return true;
            }
        }
        $scope.hidePipusAction = function(userId, departmentId) {
            switch ($scope.roleName) {
                case $scope.isSalesman:
                return true;
                break;
                case $scope.isFieldinstaller:
                return true;
                break;
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isManager:
                if (departmentId == $scope.departmentId && userId != $scope.currentIdLogin) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isReporter:
                return true;
                break;
                case $scope.isScheduler:
                return true;
                break;
                case $scope.isWarehouse:
                return true;
                break;
                default:
                return true;
            }
        }
        $scope.hideActiveByRole = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            return true;
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                return true;
                break;
                //admin
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isStrategicDevelopment:
                if (parseInt(roleId) != 1 || $scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isManager:
                if (parseInt(roleId) == 2) {
                    if ((parseInt(supervisorUser) == parseInt($scope.currentIdLogin) || parseInt(supervisorUser2) == parseInt($scope.currentIdLogin)) && departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                }
                break;
                //isReporter
                case $scope.isReporter:
                if ($scope.currentIdLogin == userId) {
                    return false;
                } else {
                    return true;
                }
                break;
                //isScheduler
                case $scope.isScheduler:
                return true;
                break;
                case $scope.isWarehouse:
                return true;
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == userId || $scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                //return false;
                break;
                case $scope.isOutsideSales:
                return true;
                break;
                case $scope.isInFieldSupervisor:
                return true;
                break;
            }
        }
        $scope.hideNewfeedCheck = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            return true;
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                return true;
                break;
                //admin
                case $scope.isAdmin:
                return false;
                break;
                //manager
                case $scope.isManager:
                if (parseInt(roleId) == 2) {
                    if ((parseInt(supervisorUser) == parseInt($scope.currentIdLogin) || parseInt(supervisorUser2) == parseInt($scope.currentIdLogin)) && departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                }
                break;
                //isReporter
                case $scope.isReporter:
                return true;
                break;
                //isScheduler
                case $scope.isScheduler:
                return true;
                break;
                case $scope.isWarehouse:
                return true;
                break;
                case $scope.isStrategicDevelopment:
                return true;
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isOutsideSales:
                return true;
                break;
                case $scope.isInFieldSupervisor:
                return true;
                break;
            }
        }
        $scope.hideEditByRole = function(userId, departmentId, roleId, supervisorUser, supervisorUser2) {
            switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            return true;
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                return true;
                break;
                //admin
                case $scope.isAdmin:
                return false;
                break;
                case $scope.isStrategicDevelopment:
                if (parseInt(roleId) == 1 || parseInt(roleId) == 9) {
                    return true;
                } else {
                    return false;
                }
                break;
                case $scope.isManager:
                if (parseInt(roleId) == 2) {
                    if ((parseInt(supervisorUser) == parseInt($scope.currentIdLogin) || parseInt(supervisorUser2) == parseInt($scope.currentIdLogin)) && departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (departmentId == $scope.departmentId) {
                        return false;
                    } else {
                        return true;
                    }
                }
                break;
                //isReporter
                case $scope.isReporter:
                return true;
                break;
                //isScheduler
                case $scope.isScheduler:
                return true;
                break;
                case $scope.isWarehouse:
                return true;
                break;
                case $scope.isSupportAssistant:
                if ($scope.currentIdLogin == supervisorUser || $scope.currentIdLogin == supervisorUser2) {
                    return false;
                } else {
                    return true;
                }
                //return false;
                break;
                case $scope.isOutsideSales:
                return true;
                break;
                case $scope.isInFieldSupervisor:
                if ($scope.currentIdLogin == supervisorUser) {
                    return false;
                } else {
                    return true;
                }
                break;
            }
        }
    //role on app
    $scope.showTabByRole = function(userId, departmentId) {
        if (parseInt($scope.usersDetail.dataUser.id) == parseInt($scope.currentIdLogin)) {
            $scope.showJobInfor = true;
            $scope.showHrInfor = true;
            $scope.showNewFeed = true;
        } else {
            switch ($scope.roleName) {
                case $scope.isSalesman:
                $scope.showJobInfor = false;
                $scope.showHrInfor = false;
                $scope.showNewFeed = false;
                break;
                case $scope.isFieldinstaller:
                return true;
                break;
                case $scope.isAdmin:
                $scope.showJobInfor = true;
                $scope.showHrInfor = true;
                $scope.showNewFeed = true;
                break;
                case $scope.isManager:
                if (departmentId == $scope.departmentId && userId != $scope.currentIdLogin) {
                    return false;
                } else {
                    return true;
                }
                break;
                case $scope.isReporter:
                return true;
                break;
                case $scope.isScheduler:
                return true;
                break;
                case $scope.isWarehouse:
                return true;
                break;
                default:
                return true;
            }
        }
    }
    $scope.disableListView_Search = function() {
        switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            return true;
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                return true;
                break;
                //admin
                case $scope.isAdmin:
                return false;
                break;
                //manager
                case $scope.isManager:
                return false;
                break;
                //isReporter
                case $scope.isReporter:
                return false;
                break;
                //isScheduler
                case $scope.isScheduler:
                return false;
                break;
                case $scope.isWarehouse:
                return true;
                break;
            }
        }
    // end Userdetail
    // end userDetail
    // puchin CTRl
    $scope.dataUnplannedAbsenceAddTask = {};
    $scope.dataPunchInIssues = {};
    $scope.dataPunchOutIssues = {};
    $scope.dataLastPoutAddtask = {};
    $scope.loadAdminAndManager = false;
    $scope.showByWhom = false;
    $scope.showOther = false;
    $scope.timePickerShow = false;
    // $scope.getPipus = function() {
    //     $scope.timeData = [
    //         { id: 1, from: '06:00 AM', to: '07:00 AM', detail: [] }, { id: 2, from: '07:00 AM', to: '08:00 AM', detail: [] }, { id: 3, from: '08:00 AM', to: '09:00 AM', detail: [] },
    //         { id: 4, from: '09:00 AM', to: '10:00 AM', detail: [] }, { id: 5, from: '10:00 AM', to: '11:00 AM', detail: [] }, { id: 6, from: '11:00 AM', to: '12:00 AM', detail: [] },
    //         { id: 7, from: '00:00 PM', to: '01:00 PM', detail: [] }, { id: 8, from: '01:00 PM', to: '02:00 PM', detail: [] }, { id: 9, from: '02:00 PM', to: '03:00 PM', detail: [] },
    //         { id: 10, from: '03:00 PM', to: '04:00 PM', detail: [] }, { id: 11, from: '04:00 PM', to: '05:00 PM', detail: [] }, { id: 12, from: '05:00 PM', to: '06:00 PM', detail: [] },
    //         { id: 13, from: '06:00 PM', to: '07:00 PM', detail: [] }, { id: 14, from: '07:00 PM', to: '08:00 PM', detail: [] }, { id: 15, from: '08:00 PM', to: '09:00 PM', detail: [] },
    //         { id: 16, from: '09:00 PM', to: '10:00 PM', detail: [] }, { id: 17, from: '10:00 PM', to: '11:00 PM', detail: [] }, { id: 18, from: '11:00 PM', to: '00:00 AM', detail: [] }
    //     ];
    //     $ionicLoading.show({ template: templateLoading });
    //     $scope.searchPipus.start_time = moment().format('MM/DD/YYYY');
    //     $scope.searchPipus.end_time = moment().format('MM/DD/YYYY');
    //     // $scope.searchPipus.start_time = '01/08/2017';
    //     // $scope.searchPipus.end_time = '01/08/2017';
    //     Login.pipusGetPaging($scope.searchPipus).success(function(data) {
    //         $ionicLoading.hide();
    //         for (var i = 0; i < data.data.length; i++) {
    //             // data.data[i].from_hour != null ? data.data[i].from_hour = moment(data.data[i].from_hour, 'hh:mm').format('h:mm A') : '';
    //             // data.data[i].to_hour != null ? data.data[i].to_hour = moment(data.data[i].to_hour, 'hh:mm').format('h:mm A') : '';
    //             var from_hour = data.data[i].from_hour;
    //             var to_hour = data.data[i].to_hour;
    //             to_hour = !to_hour ? moment().format('HH:mm') : to_hour;
    //             var index = $scope.switchTimeToIndex(from_hour);
    //             if (index == -1) continue;
    //             var detail = $scope.calculateTimePercent(from_hour, to_hour, true);
    //             $scope.timeData[index].detail.push(detail.detail);
    //             // console.log(from_hour,to_hour);
    //             var stop = detail.stop;
    //             if (!stop) {
    //                 for (var j = 0; j < 1; j++) {
    //                     index++;
    //                     var arrHour = from_hour.split(':');
    //                     var hour = parseInt(arrHour[0]) + 1;
    //                     from_hour = hour + ":00";
    //                     var detail = $scope.calculateTimePercent(from_hour, to_hour, false);
    //                     $scope.timeData[index].detail.push(detail.detail);
    //                     stop = detail.stop;
    //                     if (!stop) j = -1;
    //                 }
    //             }
    //         }
    //         $scope.totalTime = data.totalTime;
    //     });
    // };
    $scope.checkPuchIn = function() {
        // $ionicLoading.show({template: templateLoading });
        Login.checkPuchIn().success(function(data) {
            $scope.countIncompleteTask = data.countIncompleteTask;
            // $ionicLoading.hide();
            $scope.pipusType = data.type;
            var timeArr = data.time.split(':');
            var date = new Date().setHours(timeArr[0], timeArr[1], '00')
            var timeformat = moment(date).format("h:mm A");
            if (data.type == 'punchin') {
                $scope.puchOutTime = '';
                $scope.puchInTime = timeformat;
            } else {
                $scope.puchOutTime = timeformat;
                $scope.puchInTime = '';
            }
        });
    }
    $scope.checkPuchIn();
    var myVarCheckPunchInOut = setInterval(function() {
        myTimerChekcPunchInOut()
    }, 100);
    function myTimerChekcPunchInOut() {
        if (request_check_punch_inout) {
            $scope.checkPuchIn();
            clearInterval(myVarCheckPunchInOut);
        }
    }
    $scope.typeIssueChange = function(type) {
        $scope.labelVal = 'Other';
        $scope.dataPunchInIssues.other = '';
        $scope.dataPunchOutIssues.other = '';
        switch (type) {
            case 'Was request to':
            if (!$scope.loadAdminAndManager) {
                $scope.getAdminAndManager();
            }
            $scope.showByWhom = true;
            $scope.showOther = true;
            $scope.timePickerShow = false;
            $scope.showByWhomEdit = true;
            $scope.showOtherEdit = true;
            $scope.timePickerShowEdit = false;
            break;
            case 'Tardy':
            $scope.showByWhom = false;
            $scope.showOther = false;
            $scope.timePickerShow = false;
            $scope.showByWhomEdit = false;
            $scope.showOtherEdit = false;
            $scope.timePickerShowEdit = false;
            break;
            case 'Forgot to punch in/out':
            $scope.showByWhom = false;
            $scope.showOther = false;
            $scope.timePickerShow = true;
            $scope.showByWhomEdit = false;
            $scope.showOtherEdit = false;
            $scope.timePickerShowEdit = true;
            break;
            case 'Approved time off':
            $scope.showByWhom = false;
            $scope.showOther = false;
            $scope.timePickerShow = false;
            $scope.showByWhomEdit = false;
            $scope.showOtherEdit = false;
            $scope.timePickerShowEdit = false;
            break;
            case 'Other':
            $scope.showByWhom = false;
            $scope.showOther = true;
            $scope.timePickerShow = false;
            $scope.showByWhomEdit = false;
            $scope.showOtherEdit = true;
            $scope.timePickerShowEdit = false;
            $scope.labelVal = 'Description';
            break;
            case '':
            $scope.showByWhom = false;
            $scope.showOther = false;
            $scope.timePickerShow = false;
            $scope.showByWhomEdit = false;
            $scope.showOtherEdit = false;
            $scope.timePickerShowEdit = false;
            break;
        }
    }
    $scope.changePerson = function(person) {
        $scope.dataPunchInIssues.other = $scope.dataPunchInIssues.byWhom;
    }
    $scope.changePersonEdit = function(person) {
        $scope.dataPunchOutIssues.other = $scope.dataPunchOutIssues.byWhom;
    }
    $scope.getAdminAndManager = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Login.getAdminAndManager().success(function(data) {
            $ionicLoading.hide();
            $scope.adminAndManager = data;
            $scope.loadAdminAndManager = true;
        });
    }
    $scope.punchInIssuesAddTask = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Login.punchInIssuesAddTask($scope.dataPunchInIssues).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.closeTarget('#popupPunchInIssue');
                $scope.dataPunchInIssues = {};
                $scope.dataAddpunchIn = {};
                $scope.dataAddpunchIn.punch_in_issue = 1;
                $scope.dataAddpunchIn.description = data.description;
                $scope.punchIn($scope.dataAddpunchIn);
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.punchOutIssuesAddTask = function() {
        if ($scope.dataPunchOutIssues.time) $scope.dataPunchOutIssues.time = $('#formPunchOutIssue input[name="time"]').val();
        $ionicLoading.show({
            template: templateLoading
        });
        Login.punchOutIssuesAddTask($scope.dataPunchOutIssues).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.closeTarget('#popupPunchOutIssue');
                $scope.typeIssueChange("");
                $scope.dataPunchOutIssues = {};
                $scope.dataAddpunchOut = {};
                $scope.dataAddpunchOut.punch_out_issue = 1;
                $scope.dataAddpunchOut.description = data.description;
                $scope.punchOut($scope.dataAddpunchOut);
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.lastPoutAddTask = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.dataLastPoutAddtask.time = $('#popupPunchLastPount input[name="time_input"]').val();
        Login.lastPoutAddTask($scope.dataLastPoutAddtask).success(function(data) {
            $ionicLoading.hide();
            myPopup.close();
            if (data.status) {
                $scope.dataLastPoutAddtask = {};
                $scope.checkFirstPin();
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function() {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Connection error!!!');
        });
    }
    $scope.checkLastAutoPunchOut = function() {
        if ($scope.pipusType == 'punchin') {
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Login.checkLastAutoPunchOut().success(function(data) {
            $ionicLoading.hide();
            if (data.exist) {
                $scope.dataLastPoutAddtask.date = data.date;
                $scope.dataLastPoutAddtask.userbiweeksId = data.userbiweeksId;
                $scope.openByGetTemplate_menu('popupPunchLastPount');
            } else {
                $scope.checkFirstPin();
            }
        }).error(function() {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Connection error!!!');
        });
    }
    $scope.checkFirstPin = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Login.checkFirstPin().success(function(data) {
            $ionicLoading.hide();
            if (data.notAllow) {
                $scope.openByGetTemplate_menu('popupPunchInIssue');
            } else {
                $scope.dataAddpunchIn = {};
                $scope.punchIn($scope.dataAddpunchIn);
            }
        }).error(function() {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Connection error!!!');
        });
    }
    $scope.punchIn = function(data_punch_in) {
        $ionicLoading.show({
            template: templateLoading
        });
        Login.punchIn(data_punch_in).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                var timeArr = data.timePunchIn.split(':');
                var date = new Date().setHours(timeArr[0], timeArr[1], '00')
                var timeformat = moment(date).format("h:mm A");
                $scope.puchInTime = timeformat;
                $scope.puchOutTime = '';
                $scope.pipusType = 'punchin';
                $scope.showByWhom = false;
                $scope.showOther = false;
                $scope.timePickerShow = false;
                $scope.showByWhomEdit = false;
                $scope.showOtherEdit = false;
                $scope.timePickerShowEdit = false;
                // $scope.getPipus();
                socket.emit('check_punch_in_out', {
                    userId: currentIdLogin
                });
            }
        }).error(function() {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Connection error!!!');
        });
    }
    $scope.checkBeforePunchOut = function(skip = false) {
        $ionicLoading.show({
            template: templateLoading
        });
        Login.checkBeforePunchOut().success(function(data) {
            $ionicLoading.hide();
            if(data.sendConsumable && !skip){
                $scope.consumableData = {};
                $scope.skipWarning = false;
                $scope.consumableTextRequired = false;
                $scope.punchoutBreakRequired = false;
                $scope.openByGetTemplate_menu('popupSendConsumableList');
            } else if (data.afterEndTime) {
                $scope.closeTarget('#popupSendConsumableList');
                $scope.openByGetTemplate_menu('popupPunchOutIssue');
            } else {
                $scope.closeTarget('#popupSendConsumableList');
                $scope.dataAddpunchOut = {};
                $scope.punchOut($scope.dataAddpunchOut);
            }
        }).error(function() {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Connection error!!!');
        });
    }
    $scope.onsubmitConsumable = function(){
        $scope.punchoutBreakRequired = false;
        if(!$scope.consumableData.consumable_text || $scope.consumableData.consumable_text.length == 0){
            $scope.consumableTextRequired = true;
        }else{
            if($scope.onsubmitPunchin){
                $cordovaToast.showLongTop('System is processing!');
                return;
            }
            $scope.onsubmitPunchin = true;
            $ionicLoading.show({
                template: templateLoading
            });
            Login.sendConsumableList($scope.consumableData).success(function(data) {
                $ionicLoading.hide();
                $scope.onsubmitPunchin = false;
                if(data.status){
                    $cordovaToast.showLongTop(data.msg);
                    $scope.checkBeforePunchOut(true);
                }else{
                    $cordovaToast.showLongTop(data.msg);
                }
            });
        }
    }
    $scope.punchoutforbreak = function(){
        if((!$scope.consumableData.consumable_text || $scope.consumableData.consumable_text.length == 0) && !$scope.skipWarning || $scope.skipWarning){
            $scope.checkBeforePunchOut(true);
        }else{
            $scope.consumableTextRequired = false;
            $scope.punchoutBreakRequired = true;
            $scope.skipWarning = true;
        }
    };
    $scope.punchOut = function(data_punch_out) {
        if ($scope.pipusType == 'punchout') {
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Login.punchOut(data_punch_out).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                var timeArr = data.timePouchOut.split(':');
                var date = new Date().setHours(timeArr[0], timeArr[1], '00')
                var timeformat = moment(date).format("h:mm A");
                $scope.puchOutTime = timeformat;
                $scope.puchInTime = '';
                $scope.pipusType = 'punchout';
                // $scope.getPipus();
                socket.emit('check_punch_in_out', {
                    userId: currentIdLogin
                });
            }
        }).error(function() {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Connection error!!!');
        });
    }
    $scope.auto = function() {
        openPopup('#remindPunchIn');
    }
    $scope.unplannedAbsenceAddTask = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Login.unplannedAbsenceAddTask($scope.dataUnplannedAbsenceAddTask).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.closeTarget('#popupPunchAbsence');
                $scope.dataUnplannedAbsenceAddTask = {}
                socket.emit('new message', {
                    from_user: data.fromId,
                    room_id: data.pushchatroom,
                    user_id: data.fromId,
                    contents: data.messageContents,
                    hashtag: '',
                    applicationtype: aplicationtype.text
                });
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function() {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Connection error!!!');
        });
    }
    // end Punch In out
    // file manager 
    $scope.dataUrlFileManager = {};
    $scope.getConfigS3 = function(userID) {
        var params = {};
        params.appMobile = true;
        Login.getConfigFileUpload(params).success(function(data) {
            $scope.bucketName = data.bucketName;
            $scope.userDataUrl = data.userDataUrl;
            $scope.dataUrlFileManager.rootUserDataUrl = $scope.userDataUrl + userID + '/';
            $scope.dataUrlFileManager.currenUserDataUrl = $scope.userDataUrl + userID + '/';
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.openFileManager = function(dataUrl) {
        $scope.openByGetTemplate_menu('popupUserFilemanagerContent');
        var params = {
            action: 'list',
            url: dataUrl
        };
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.listFilesUser = [];
        Login.actionFileManager(params).success(function(results) {
            $ionicLoading.hide();
            $scope.dataUrlFileManager.currenUserDataUrl = dataUrl;
            var arrData = $scope.dataUrlFileManager.currenUserDataUrl.split("/");
            arrData.splice(arrData.length - 2);
            $scope.dataUrlFileManager.preUserDataUrl = arrData.join("/") + "/";
            var data = {
                folders: [],
                files: []
            };
            if (results.CommonPrefixes) data.folders = results.CommonPrefixes;
            if (results.Contents) data.files = results.Contents;
            data.files.forEach(function(itm) {
                var arrData = itm.Key.split('/');
                var temp = arrData[arrData.length - 1].split('.');
                itm.name = temp[temp.length - 2];
                itm.extension = temp[temp.length - 1];
                itm.type = $scope.sortFiletypeAppointment(itm.extension);
                itm.url = 'https://rgdapp.s3.amazonaws.com/' + itm.Key;
            });
            data.folders.forEach(function(itm) {
                var arrData = itm.Prefix.split('/');
                itm.name = arrData[arrData.length - 2];
            });
            data.files = _.without(data.files, _.findWhere(data.files, {
                Size: 0
            }));
            data.files = _.without(data.files, _.findWhere(data.files, {
                name: ""
            }));
            data.files = _.without(data.files, _.findWhere(data.files, {
                name: undefined
            }));
            data.files = _.without(data.files, _.findWhere(data.files, {
                name: ""
            }));
            $scope.listFilesUser = data;
            $scope.resizeScroll('scrollFileManager');
            $ionicScrollDelegate.$getByHandle('scrollFileManager').scrollTop();
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.generateUrl = function(idx) {
        var arr = $scope.dataUrlFileManager.currenUserDataUrl.split('/');
        arr.splice(idx + 1);
        var url = arr.join("/") + "/";
        $scope.openFileManager(url);
    }
    $scope.createFolder = function() {
        if (!$scope.dataUrlFileManager.name) {
            return;
        } else {
            var flag = true;
            $scope.listFilesUser.folders.forEach(function(itm) {
                if (itm.name.toLowerCase() === $scope.dataUrlFileManager.name.toLowerCase()) {
                    flag = false;
                }
            })
            if (!flag) {
                $cordovaToast.showLongTop('Folder name is exist!!!');
                return;
            }
            var name_folder = $scope.dataUrlFileManager.currenUserDataUrl + $scope.dataUrlFileManager.name + '/';
            var params = {
                action: 'create',
                url: name_folder
            };
            $ionicLoading.show({
                template: templateLoading
            });
            Login.actionFileManager(params).success(function() {
                $scope.openFileManager($scope.dataUrlFileManager.currenUserDataUrl);
            }).error(function(data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        }
    }
    $scope.editObject = function(item) {
        $scope.openByGetTemplate_menu('popupEditFileFolderName');
        $scope.dataUrlFileManager.objectSelect = item;
        $scope.dataUrlFileManager.name = item.extension ? item.name + '.' + item.extension : item.name;
    }
    $scope.renameObject = function() {
        if (!$scope.dataUrlFileManager.name) {
            return;
        } else {
            var flag = true;
            $scope.listFilesUser.folders.forEach(function(itm) {
                if (itm.name === $scope.dataUrlFileManager.name) {
                    flag = false;
                }
            })
            $scope.listFilesUser.files.forEach(function(itm) {
                if (itm.name === $scope.dataUrlFileManager.name) {
                    flag = false;
                }
            })
            if (!flag) {
                $cordovaToast.showLongTop('Folder/File name is exist!!!');
                return;
            }
            var key = $scope.dataUrlFileManager.objectSelect.Key ? $scope.dataUrlFileManager.objectSelect.Key : $scope.dataUrlFileManager.objectSelect.Prefix;
            var newKey = $scope.dataUrlFileManager.currenUserDataUrl + $scope.dataUrlFileManager.name;
            if ($scope.dataUrlFileManager.objectSelect.Prefix) newKey = newKey + '/';
            var params = {
                action: 'rename',
                url: key,
                newUrl: newKey
            };
            $ionicLoading.show({
                template: templateLoading
            });
            Login.actionFileManager(params).success(function() {
                $scope.openFileManager($scope.dataUrlFileManager.currenUserDataUrl);
            }).error(function(data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        }
    }
    $scope.confirmObject = function(item) {
        $scope.openByGetTemplate_menu('confirmDeleteFolder');
        $scope.dataUrlFileManager.objectSelect = item;
    }
    $scope.deteleObject = function() {
        var key = $scope.dataUrlFileManager.objectSelect.Key ? $scope.dataUrlFileManager.objectSelect.Key : $scope.dataUrlFileManager.objectSelect.Prefix;
        var params = {
            action: 'delete',
            url: key
        };
        $ionicLoading.show({
            template: templateLoading
        });
        Login.actionFileManager(params).success(function() {
            $scope.openFileManager($scope.dataUrlFileManager.currenUserDataUrl);
            $scope.closeTarget("#confirmDeleteFolder");
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.openActionSheetFM = function() {
        var options = {
            // title: 'What do you want with this image?',
            buttonLabels: ['Video', 'Camera', 'Photo', 'File'],
            addCancelButtonWithLabel: 'Cancel',
            androidEnableCancelButton: true,
        };
        $cordovaActionSheet.show(options).then(function(index) {
            if (index == 2) {
                $scope.takePictureFM();
            } else if (index == 3) {
                $scope.openPickerFM();
            } else if (index == 4) {
                $scope.filePickerFM();
            } else {
                $scope.recordVideoFM();
            }
        });
    }
    $scope.phoneUploadFM = function(fileTransfers) {
        angular.forEach(fileTransfers, function(item) {
            $ionicLoading.show({
                template: templateLoading
            });
            var filename = item.name;
            $scope.fileUploadData = {};
            $scope.fileUploadData.type = item.type;
            $scope.fileUploadData.name = filename;
            $scope.fileUploadData.bucket = $scope.bucketName;
            $scope.fileUploadData.acl = aclConfig;
            $scope.fileUploadData.urlFolder = $scope.dataUrlFileManager.currenUserDataUrl.substring(0, $scope.dataUrlFileManager.currenUserDataUrl.length - 1);
            console.log($scope.fileUploadData.urlFolder);
            Login.getConfigFileUpload($scope.fileUploadData).success(function(data) {
                var Uoptions = {};
                Uoptions.fileKey = "file";
                Uoptions.fileName = data.folder + '/' + data.microtime + filename;
                Uoptions.mimeType = item.type;
                Uoptions.chunkedMode = false;
                Uoptions.headers = {
                    connection: "close"
                };
                Uoptions.params = {
                    "Key": data.folder + '/' + data.microtime + filename,
                    "AWSAccessKeyId": data.awsAccessKeyId,
                    "acl": data.acl,
                    "Policy": data.policy,
                    "Signature": data.signature,
                    "success_action_status": data.successActionStatus,
                    "Content-Type": item.type
                };
                $cordovaFileTransfer.upload('http://' + $scope.bucketName + '.s3.amazonaws.com/', item.localURL, Uoptions).then(function(return_data) {
                    $ionicLoading.hide();
                    $scope.openFileManager($scope.dataUrlFileManager.currenUserDataUrl);
                }, function(err) {
                    console.log(err);
                    $ionicLoading.hide();
                }, function(progress) {
                    $ionicLoading.show({
                        template: templateLoading
                    });
                });
            });
        });
    }
    $scope.recordVideoFM = function() {
        // capture callback
        var captureSuccess = function(mediaFiles) {
            console.log('dataVideo', mediaFiles);
            $scope.phoneUploadFM(mediaFiles);
        };
        // capture error callback
        var captureError = function(error) {
            navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
        };
        // start video capture
        navigator.device.capture.captureVideo(captureSuccess, captureError, {
            limit: 1
        });
    }
    $scope.openPickerFM = function() {
        var options = {
            maximumImagesCount: 50,
            width: 0,
            height: 0,
            quality: 100
        };
        var data = [];
        $cordovaImagePicker.getPictures(options).then(function(results) {
            results.forEach(function(itm) {
                var filename = itm.substr(itm.lastIndexOf('/') + 1);
                data.push({
                    name: filename,
                    type: 'image/jpeg',
                    localURL: itm
                });
            })
            console.log(data);
            $scope.phoneUploadFM(data);
        });
    }
    $scope.takePictureFM = function() {
        var options = {
            quality: 100,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.CAMERA,
            // allowEdit: true,
            // targetWidth: 500,
            // targetHeight: 500,
            encodingType: Camera.EncodingType.JPEG,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: true
        };
        $cordovaCamera.getPicture(options).then(function(imageData) {
            console.log(imageData);
            var filename = imageData.substr(imageData.lastIndexOf('/') + 1);
            $scope.phoneUploadFM([{
                name: filename,
                type: 'image/jpeg',
                localURL: imageData
            }]);
        }, function(err) {
            $cordovaToast.showLongTop(err);
            console.log(err);
        });
    }
    $scope.filePickerFM = function() {
        // for IOS
        FilePicker.pickFile(function(path) {
            var arrFileSplit = path.split(".");
            var type = getFileType(arrFileSplit[arrFileSplit.length - 1].toLowerCase());
            var filename = path.substr(path.lastIndexOf('/') + 1);
            console.log([{
                name: filename,
                type: type,
                localURL: path
            }]);
            $scope.phoneUploadFM([{
                name: filename,
                type: type,
                localURL: path
            }]);
            //if error change picker for android
        }, function(err) {
            fileChooser.open(function(uri) {
                // convert uri include extension
                window.FilePath.resolveNativePath(uri, function(path) {
                    var arrFileSplit = path.split(".");
                    var type = getFileType(arrFileSplit[arrFileSplit.length - 1].toLowerCase());
                    var filename = path.substr(path.lastIndexOf('/') + 1);
                    console.log([{
                        name: filename,
                        type: type,
                        localURL: path
                    }]);
                    $scope.phoneUploadFM([{
                        name: filename,
                        type: type,
                        localURL: path
                    }]);
                }, function(errer) {
                    console.log(uri);
                    $cordovaToast.showLongTop(errer);
                });
            }, function(err) {
                $cordovaToast.showLongTop(err);
            });
        });
    }
    $scope.downloadFileFM = function(url) {
        var urlFile = decodeURIComponent(url);
        var arrData = urlFile.split("/");
        var fileName = arrData[arrData.length - 1];
        var trustHosts = true;
        var options = {};
        //                $ionicLoading.show({template: templateLoading});
        if (isiOs) {
            $scope.cordovaBrowser(url);
        } else {
            var targetPath = cordova.file.externalRootDirectory + 'RGD/' + fileName;
            $cordovaFile.createDir(cordova.file.externalRootDirectory, "RGD", false).then(function(success) {
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            }, function(error) {
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            });
        }
    }
    $scope.cordovaDownload = function(urlFile, targetPath, options, trustHosts) {
        $ionicLoading.show({
            template: templateLoading
        });
        $cordovaFileTransfer.download(urlFile, targetPath, options, trustHosts).then(function(result) {
            $ionicLoading.hide();
            console.log(result);
            var path = result.fullPath;
            $cordovaToast.showLongTop('Download Successful!!! Path: ' + path);
        }, function(err) {
            $ionicLoading.hide();
            console.log(err);
        }, function(progress) {
            $ionicLoading.show({
                template: templateLoading
            });
        });
    }
    $scope.fileFolderViewer = function(index) {
        dataHtml.getTemplate('templates/dashboard/users/user-detail/user-detailFileManagermentViewFilemodal.tpl').success(function(results) {
            $scope.menuHtml.popupFileViewer = results;
            $timeout(function() {
                fileFolderViewer('#popupFileViewer', index);
            }, 1);
            $scope.showTarget('#popupFileViewer');
            $ionicLoading.hide();
        });
    }
    $scope.getFileType = function(url) {
        var result = {};
        result.extension = (url.split('.').pop() == url) ? '' : url.split("?")[0].split("#")[0].split('.').pop();
        //result.shortname = (url.length > 35) ? url.slice(0, 15) + ' ... ' + url.slice(-15) : url;
        result.icon = '<svg class="full" viewBox="0 0 58 58"> <polygon fill="#EDEADA" points="52,19 38,5 11,5 11,58 52,58 "/> <polygon fill="#C1BCA4" points="11,5 38,5 47,14 47,0 6,0 6,53 11,53 "/> <g> <path fill="#CEC9AE" d="M19,26h25c0.552,0,1-0.447,1-1s-0.448-1-1-1H19c-0.552,0-1,0.447-1,1S18.448,26,19,26z"/> <path fill="#CEC9AE" d="M19,18h10c0.552,0,1-0.447,1-1s-0.448-1-1-1H19c-0.552,0-1,0.447-1,1S18.448,18,19,18z"/> <path fill="#CEC9AE" d="M44,32H19c-0.552,0-1,0.447-1,1s0.448,1,1,1h25c0.552,0,1-0.447,1-1S44.552,32,44,32z"/> <path fill="#CEC9AE" d="M44,40H19c-0.552,0-1,0.447-1,1s0.448,1,1,1h25c0.552,0,1-0.447,1-1S44.552,40,44,40z"/> <path fill="#CEC9AE" d="M44,48H19c-0.552,0-1,0.447-1,1s0.448,1,1,1h25c0.552,0,1-0.447,1-1S44.552,48,44,48z"/> </g> <polygon fill="#CEC9AE" points="38,5 38,19 52,19 "/> </svg>';
        switch (result.extension.toLowerCase().trim()) {
            case "":
            result.type = "UNKNOWN";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <g> <circle fill="#FFFFFF" cx="25.5" cy="25" r="10"/> <path fill="#556080" d="M25.5,36c-6.065,0-11-4.935-11-11s4.935-11,11-11s11,4.935,11,11S31.565,36,25.5,36z M25.5,16    c-4.963,0-9,4.037-9,9s4.037,9,9,9s9-4.037,9-9S30.463,16,25.5,16z"/> </g> <path fill="#556080" d="M42.5,45c-0.256,0-0.512-0.098-0.707-0.293l-11-11c-0.391-0.391-0.391-1.023,0-1.414   s1.023-0.391,1.414,0l11,11c0.391,0.391,0.391,1.023,0,1.414C43.012,44.902,42.756,45,42.5,45z"/> <path fill="#D1D4D1" d="M25.5,22h-6c-0.553,0-1-0.447-1-1s0.447-1,1-1h6c0.553,0,1,0.447,1,1S26.053,22,25.5,22z"/> <path fill="#D1D4D1" d="M30.5,22h-2c-0.553,0-1-0.447-1-1s0.447-1,1-1h2c0.553,0,1,0.447,1,1S31.053,22,30.5,22z"/> <path fill="#D1D4D1" d="M24.5,30h-2c-0.553,0-1-0.447-1-1s0.447-1,1-1h2c0.553,0,1,0.447,1,1S25.053,30,24.5,30z"/> <path fill="#D1D4D1" d="M30.5,30h-2c-0.553,0-1-0.447-1-1s0.447-1,1-1h2c0.553,0,1,0.447,1,1S31.053,30,30.5,30z"/> <path fill="#D1D4D1" d="M23.5,26h-4c-0.553,0-1-0.447-1-1s0.447-1,1-1h4c0.553,0,1,0.447,1,1S24.053,26,23.5,26z"/> <path fill="#D1D4D1" d="M32.5,26h-5c-0.553,0-1-0.447-1-1s0.447-1,1-1h5c0.553,0,1,0.447,1,1S33.053,26,32.5,26z"/> </svg>';
            break;
            case "txt":
            result.type = "DOCUMENT";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#95A5A5" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M21.867,42.924v1.121h-3.008V53h-1.654v-8.955h-3.008v-1.121H21.867z"/> <path fill="#FFFFFF" d="M28.443,48.105L31,53h-1.9l-1.6-3.801h-0.137L25.641,53h-1.9l2.557-4.895l-2.721-5.182h1.873    l1.777,4.102h0.137l1.928-4.102h1.873L28.443,48.105z"/> <path fill="#FFFFFF" d="M40.529,42.924v1.121h-3.008V53h-1.654v-8.955h-3.008v-1.121H40.529z"/> </g> <path fill="#C8BDB8" d="M18.5,13h-6c-0.553,0-1-0.448-1-1s0.447-1,1-1h6c0.553,0,1,0.448,1,1S19.053,13,18.5,13z"/> <path fill="#C8BDB8" d="M21.5,18h-9c-0.553,0-1-0.448-1-1s0.447-1,1-1h9c0.553,0,1,0.448,1,1S22.053,18,21.5,18z"/> <path fill="#C8BDB8" d="M25.5,18c-0.26,0-0.521-0.11-0.71-0.29c-0.181-0.19-0.29-0.44-0.29-0.71s0.109-0.52,0.3-0.71   c0.36-0.37,1.04-0.37,1.41,0c0.18,0.19,0.29,0.45,0.29,0.71c0,0.26-0.11,0.52-0.29,0.71C26.02,17.89,25.76,18,25.5,18z"/> <path fill="#C8BDB8" d="M37.5,18h-8c-0.553,0-1-0.448-1-1s0.447-1,1-1h8c0.553,0,1,0.448,1,1S38.053,18,37.5,18z"/> <path fill="#C8BDB8" d="M12.5,33c-0.26,0-0.521-0.11-0.71-0.29c-0.181-0.19-0.29-0.45-0.29-0.71   c0-0.26,0.109-0.52,0.29-0.71c0.37-0.37,1.05-0.37,1.42,0.01c0.18,0.18,0.29,0.44,0.29,0.7c0,0.26-0.11,0.52-0.29,0.71   C13.02,32.89,12.76,33,12.5,33z"/> <path fill="#C8BDB8" d="M24.5,33h-8c-0.553,0-1-0.448-1-1s0.447-1,1-1h8c0.553,0,1,0.448,1,1S25.053,33,24.5,33z"/> <path fill="#C8BDB8" d="M43.5,18h-2c-0.553,0-1-0.448-1-1s0.447-1,1-1h2c0.553,0,1,0.448,1,1S44.053,18,43.5,18z"/> <path fill="#C8BDB8" d="M34.5,23h-22c-0.553,0-1-0.448-1-1s0.447-1,1-1h22c0.553,0,1,0.448,1,1S35.053,23,34.5,23z"/> <path fill="#C8BDB8" d="M43.5,23h-6c-0.553,0-1-0.448-1-1s0.447-1,1-1h6c0.553,0,1,0.448,1,1S44.053,23,43.5,23z"/> <path fill="#C8BDB8" d="M16.5,28h-4c-0.553,0-1-0.448-1-1s0.447-1,1-1h4c0.553,0,1,0.448,1,1S17.053,28,16.5,28z"/> <path fill="#C8BDB8" d="M30.5,28h-10c-0.553,0-1-0.448-1-1s0.447-1,1-1h10c0.553,0,1,0.448,1,1S31.053,28,30.5,28z"/> <path fill="#C8BDB8" d="M43.5,28h-9c-0.553,0-1-0.448-1-1s0.447-1,1-1h9c0.553,0,1,0.448,1,1S44.053,28,43.5,28z"/> </svg>';
            break;
            case "doc":
            case "docx":
            result.type = "DOCUMENT";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#8697CB" d="M18.5,13h-6c-0.552,0-1-0.448-1-1s0.448-1,1-1h6c0.552,0,1,0.448,1,1S19.052,13,18.5,13z"/> <path fill="#8697CB" d="M21.5,18h-9c-0.552,0-1-0.448-1-1s0.448-1,1-1h9c0.552,0,1,0.448,1,1S22.052,18,21.5,18z"/> <path fill="#8697CB" d="M25.5,18c-0.26,0-0.52-0.11-0.71-0.29c-0.18-0.19-0.29-0.45-0.29-0.71c0-0.26,0.11-0.52,0.29-0.71   c0.37-0.37,1.05-0.37,1.42,0c0.18,0.19,0.29,0.45,0.29,0.71c0,0.26-0.11,0.52-0.29,0.71C26.02,17.89,25.76,18,25.5,18z"/> <path fill="#8697CB" d="M37.5,18h-8c-0.552,0-1-0.448-1-1s0.448-1,1-1h8c0.552,0,1,0.448,1,1S38.052,18,37.5,18z"/> <path fill="#8697CB" d="M12.5,33c-0.26,0-0.52-0.11-0.71-0.29c-0.18-0.19-0.29-0.45-0.29-0.71c0-0.26,0.11-0.52,0.29-0.71   c0.37-0.37,1.05-0.37,1.42,0c0.18,0.19,0.29,0.44,0.29,0.71c0,0.26-0.11,0.52-0.29,0.71C13.02,32.89,12.76,33,12.5,33z"/> <path fill="#8697CB" d="M24.5,33h-8c-0.552,0-1-0.448-1-1s0.448-1,1-1h8c0.552,0,1,0.448,1,1S25.052,33,24.5,33z"/> <path fill="#8697CB" d="M43.5,18h-2c-0.552,0-1-0.448-1-1s0.448-1,1-1h2c0.552,0,1,0.448,1,1S44.052,18,43.5,18z"/> <path fill="#8697CB" d="M34.5,23h-22c-0.552,0-1-0.448-1-1s0.448-1,1-1h22c0.552,0,1,0.448,1,1S35.052,23,34.5,23z"/> <path fill="#8697CB" d="M43.5,23h-6c-0.552,0-1-0.448-1-1s0.448-1,1-1h6c0.552,0,1,0.448,1,1S44.052,23,43.5,23z"/> <path fill="#8697CB" d="M16.5,28h-4c-0.552,0-1-0.448-1-1s0.448-1,1-1h4c0.552,0,1,0.448,1,1S17.052,28,16.5,28z"/> <path fill="#8697CB" d="M30.5,28h-10c-0.552,0-1-0.448-1-1s0.448-1,1-1h10c0.552,0,1,0.448,1,1S31.052,28,30.5,28z"/> <path fill="#8697CB" d="M43.5,28h-9c-0.552,0-1-0.448-1-1s0.448-1,1-1h9c0.552,0,1,0.448,1,1S44.052,28,43.5,28z"/> <path fill="#0096E6" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M23.5,47.682c0,0.829-0.089,1.538-0.267,2.126s-0.403,1.08-0.677,1.477s-0.581,0.709-0.923,0.937    s-0.672,0.398-0.991,0.513c-0.319,0.114-0.611,0.187-0.875,0.219C19.503,52.984,19.307,53,19.18,53h-3.814V42.924H18.4    c0.848,0,1.593,0.135,2.235,0.403s1.176,0.627,1.6,1.073s0.74,0.955,0.95,1.524C23.395,46.494,23.5,47.08,23.5,47.682z     M18.633,51.797c1.112,0,1.914-0.355,2.406-1.066s0.738-1.741,0.738-3.09c0-0.419-0.05-0.834-0.15-1.244    c-0.101-0.41-0.294-0.781-0.581-1.114s-0.677-0.602-1.169-0.807s-1.13-0.308-1.914-0.308h-0.957v7.629H18.633z"/> <path fill="#FFFFFF" d="M33.475,47.914c0,0.848-0.107,1.595-0.321,2.242c-0.214,0.647-0.511,1.185-0.889,1.613    c-0.378,0.429-0.82,0.752-1.326,0.971s-1.06,0.328-1.661,0.328s-1.155-0.109-1.661-0.328s-0.948-0.542-1.326-0.971    c-0.378-0.429-0.675-0.966-0.889-1.613c-0.214-0.647-0.321-1.395-0.321-2.242s0.107-1.593,0.321-2.235    c0.214-0.643,0.51-1.178,0.889-1.606c0.378-0.429,0.82-0.754,1.326-0.978s1.06-0.335,1.661-0.335s1.155,0.111,1.661,0.335    s0.948,0.549,1.326,0.978c0.378,0.429,0.674,0.964,0.889,1.606C33.367,46.321,33.475,47.066,33.475,47.914z M29.236,51.729    c0.337,0,0.658-0.066,0.964-0.198c0.305-0.132,0.579-0.349,0.82-0.649c0.241-0.301,0.431-0.695,0.567-1.183    s0.209-1.082,0.219-1.784c-0.009-0.684-0.08-1.265-0.212-1.743c-0.132-0.479-0.314-0.873-0.547-1.183s-0.497-0.533-0.793-0.67    c-0.296-0.137-0.608-0.205-0.937-0.205c-0.337,0-0.659,0.063-0.964,0.191c-0.306,0.128-0.579,0.344-0.82,0.649    c-0.242,0.306-0.431,0.699-0.567,1.183s-0.21,1.075-0.219,1.777c0.009,0.684,0.08,1.267,0.212,1.75    c0.132,0.483,0.314,0.877,0.547,1.183s0.497,0.528,0.793,0.67C28.596,51.658,28.908,51.729,29.236,51.729z"/> <path fill="#FFFFFF" d="M42.607,51.975c-0.374,0.364-0.798,0.638-1.271,0.82c-0.474,0.183-0.984,0.273-1.531,0.273    c-0.602,0-1.155-0.109-1.661-0.328s-0.948-0.542-1.326-0.971c-0.378-0.429-0.675-0.966-0.889-1.613    c-0.214-0.647-0.321-1.395-0.321-2.242s0.107-1.593,0.321-2.235c0.214-0.643,0.51-1.178,0.889-1.606    c0.378-0.429,0.822-0.754,1.333-0.978c0.51-0.224,1.062-0.335,1.654-0.335c0.547,0,1.057,0.091,1.531,0.273    c0.474,0.183,0.897,0.456,1.271,0.82l-1.135,1.012c-0.228-0.265-0.481-0.456-0.759-0.574c-0.278-0.118-0.567-0.178-0.868-0.178    c-0.337,0-0.659,0.063-0.964,0.191c-0.306,0.128-0.579,0.344-0.82,0.649c-0.242,0.306-0.431,0.699-0.567,1.183    s-0.21,1.075-0.219,1.777c0.009,0.684,0.08,1.267,0.212,1.75c0.132,0.483,0.314,0.877,0.547,1.183s0.497,0.528,0.793,0.67    c0.296,0.142,0.608,0.212,0.937,0.212s0.636-0.06,0.923-0.178s0.549-0.31,0.786-0.574L42.607,51.975z"/> </g> </svg>';
            break;
            case "ppt":
            case "pptx":
            result.type = "DOCUMENT";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#F6712E" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M17.581,53H15.94V42.924h2.898c0.428,0,0.852,0.068,1.271,0.205    c0.419,0.137,0.795,0.342,1.128,0.615c0.333,0.273,0.602,0.604,0.807,0.991s0.308,0.822,0.308,1.306    c0,0.511-0.087,0.973-0.26,1.388c-0.173,0.415-0.415,0.764-0.725,1.046c-0.31,0.282-0.684,0.501-1.121,0.656    s-0.921,0.232-1.449,0.232h-1.217V53z M17.581,44.168v3.992h1.504c0.2,0,0.398-0.034,0.595-0.103    c0.196-0.068,0.376-0.18,0.54-0.335s0.296-0.371,0.396-0.649c0.1-0.278,0.15-0.622,0.15-1.032c0-0.164-0.023-0.354-0.068-0.567    c-0.046-0.214-0.139-0.419-0.28-0.615c-0.142-0.196-0.34-0.36-0.595-0.492c-0.255-0.132-0.593-0.198-1.012-0.198H17.581z"/> <path fill="#FFFFFF" d="M25.853,53h-1.641V42.924h2.898c0.428,0,0.852,0.068,1.271,0.205    c0.419,0.137,0.795,0.342,1.128,0.615c0.333,0.273,0.602,0.604,0.807,0.991s0.308,0.822,0.308,1.306    c0,0.511-0.087,0.973-0.26,1.388c-0.173,0.415-0.415,0.764-0.725,1.046c-0.31,0.282-0.684,0.501-1.121,0.656    s-0.921,0.232-1.449,0.232h-1.217V53z M25.853,44.168v3.992h1.504c0.2,0,0.398-0.034,0.595-0.103    c0.196-0.068,0.376-0.18,0.54-0.335s0.296-0.371,0.396-0.649c0.1-0.278,0.15-0.622,0.15-1.032c0-0.164-0.023-0.354-0.068-0.567    c-0.046-0.214-0.139-0.419-0.28-0.615c-0.142-0.196-0.34-0.36-0.595-0.492c-0.255-0.132-0.593-0.198-1.012-0.198H25.853z"/> <path fill="#FFFFFF" d="M39.606,42.924v1.121h-3.008V53h-1.654v-8.955h-3.008v-1.121H39.606z"/> </g> <path fill="#C8BDB8" d="M39.5,30h-24V14h24V30z M17.5,28h20V16h-20V28z"/> <path fill="#C8BDB8" d="M20.499,35c-0.175,0-0.353-0.046-0.514-0.143c-0.474-0.284-0.627-0.898-0.343-1.372l3-5   c0.284-0.474,0.898-0.627,1.372-0.343c0.474,0.284,0.627,0.898,0.343,1.372l-3,5C21.17,34.827,20.839,35,20.499,35z"/> <path fill="#C8BDB8" d="M34.501,35c-0.34,0-0.671-0.173-0.858-0.485l-3-5c-0.284-0.474-0.131-1.088,0.343-1.372   c0.474-0.283,1.088-0.131,1.372,0.343l3,5c0.284,0.474,0.131,1.088-0.343,1.372C34.854,34.954,34.676,35,34.501,35z"/> <path fill="#C8BDB8" d="M27.5,16c-0.552,0-1-0.447-1-1v-3c0-0.553,0.448-1,1-1s1,0.447,1,1v3C28.5,15.553,28.052,16,27.5,16   z"/> <rect x="17.5" y="16" fill="#D3CCC9" width="20" height="12"/> </svg>';
            break;
            case "xls":
            case "xlsx":
            result.type = "DOCUMENT";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#91CDA0" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M20.379,48.105L22.936,53h-1.9l-1.6-3.801h-0.137L17.576,53h-1.9l2.557-4.895l-2.721-5.182h1.873    l1.777,4.102h0.137l1.928-4.102H23.1L20.379,48.105z"/> <path fill="#FFFFFF" d="M27.037,42.924v8.832h4.635V53h-6.303V42.924H27.037z"/> <path fill="#FFFFFF" d="M39.041,50.238c0,0.364-0.075,0.718-0.226,1.06S38.453,51.94,38.18,52.2s-0.611,0.467-1.012,0.622    c-0.401,0.155-0.857,0.232-1.367,0.232c-0.219,0-0.444-0.012-0.677-0.034s-0.467-0.062-0.704-0.116    c-0.237-0.055-0.463-0.13-0.677-0.226c-0.214-0.096-0.399-0.212-0.554-0.349l0.287-1.176c0.127,0.073,0.289,0.144,0.485,0.212    c0.196,0.068,0.398,0.132,0.608,0.191c0.209,0.06,0.419,0.107,0.629,0.144c0.209,0.036,0.405,0.055,0.588,0.055    c0.556,0,0.982-0.13,1.278-0.39c0.296-0.26,0.444-0.645,0.444-1.155c0-0.31-0.105-0.574-0.314-0.793    c-0.21-0.219-0.472-0.417-0.786-0.595s-0.654-0.355-1.019-0.533c-0.365-0.178-0.707-0.388-1.025-0.629    c-0.319-0.241-0.583-0.526-0.793-0.854c-0.21-0.328-0.314-0.738-0.314-1.23c0-0.446,0.082-0.843,0.246-1.189    s0.385-0.641,0.663-0.882c0.278-0.241,0.602-0.426,0.971-0.554s0.759-0.191,1.169-0.191c0.419,0,0.843,0.039,1.271,0.116    c0.428,0.077,0.774,0.203,1.039,0.376c-0.055,0.118-0.119,0.248-0.191,0.39c-0.073,0.142-0.142,0.273-0.205,0.396    c-0.064,0.123-0.119,0.226-0.164,0.308c-0.046,0.082-0.073,0.128-0.082,0.137c-0.055-0.027-0.116-0.063-0.185-0.109    s-0.167-0.091-0.294-0.137c-0.128-0.046-0.296-0.077-0.506-0.096c-0.21-0.019-0.479-0.014-0.807,0.014    c-0.183,0.019-0.355,0.07-0.52,0.157s-0.31,0.193-0.438,0.321c-0.128,0.128-0.228,0.271-0.301,0.431    c-0.073,0.159-0.109,0.313-0.109,0.458c0,0.364,0.104,0.658,0.314,0.882c0.209,0.224,0.469,0.419,0.779,0.588    c0.31,0.169,0.647,0.333,1.012,0.492c0.364,0.159,0.704,0.354,1.019,0.581s0.576,0.513,0.786,0.854    C38.936,49.261,39.041,49.7,39.041,50.238z"/> </g> <path fill="#C8BDB8" d="M23.5,16v-4h-12v4v2v2v2v2v2v2v2v4h10h2h21v-4v-2v-2v-2v-2v-2v-4H23.5z M13.5,14h8v2h-8V14z    M13.5,18h8v2h-8V18z M13.5,22h8v2h-8V22z M13.5,26h8v2h-8V26z M21.5,32h-8v-2h8V32z M42.5,32h-19v-2h19V32z M42.5,28h-19v-2h19V28   z M42.5,24h-19v-2h19V24z M23.5,20v-2h19v2H23.5z"/> </svg>';
            break;
            case "csv":
            result.type = "DOCUMENT";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#F36FA0" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M21.58,51.975c-0.374,0.364-0.798,0.638-1.271,0.82c-0.474,0.183-0.984,0.273-1.531,0.273    c-0.602,0-1.155-0.109-1.661-0.328s-0.948-0.542-1.326-0.971c-0.378-0.429-0.675-0.966-0.889-1.613    c-0.214-0.647-0.321-1.395-0.321-2.242s0.107-1.593,0.321-2.235c0.214-0.643,0.51-1.178,0.889-1.606    c0.378-0.429,0.822-0.754,1.333-0.978c0.51-0.224,1.062-0.335,1.654-0.335c0.547,0,1.057,0.091,1.531,0.273    c0.474,0.183,0.897,0.456,1.271,0.82l-1.135,1.012c-0.228-0.265-0.481-0.456-0.759-0.574c-0.278-0.118-0.567-0.178-0.868-0.178    c-0.337,0-0.659,0.063-0.964,0.191c-0.306,0.128-0.579,0.344-0.82,0.649c-0.242,0.306-0.431,0.699-0.567,1.183    s-0.21,1.075-0.219,1.777c0.009,0.684,0.08,1.267,0.212,1.75c0.132,0.483,0.314,0.877,0.547,1.183s0.497,0.528,0.793,0.67    c0.296,0.142,0.608,0.212,0.937,0.212s0.636-0.06,0.923-0.178s0.549-0.31,0.786-0.574L21.58,51.975z"/> <path fill="#FFFFFF" d="M29.633,50.238c0,0.364-0.075,0.718-0.226,1.06s-0.362,0.643-0.636,0.902s-0.611,0.467-1.012,0.622    c-0.401,0.155-0.857,0.232-1.367,0.232c-0.219,0-0.444-0.012-0.677-0.034s-0.467-0.062-0.704-0.116    c-0.237-0.055-0.463-0.13-0.677-0.226c-0.214-0.096-0.399-0.212-0.554-0.349l0.287-1.176c0.127,0.073,0.289,0.144,0.485,0.212    c0.196,0.068,0.398,0.132,0.608,0.191c0.209,0.06,0.419,0.107,0.629,0.144c0.209,0.036,0.405,0.055,0.588,0.055    c0.556,0,0.982-0.13,1.278-0.39c0.296-0.26,0.444-0.645,0.444-1.155c0-0.31-0.105-0.574-0.314-0.793    c-0.21-0.219-0.472-0.417-0.786-0.595s-0.654-0.355-1.019-0.533c-0.365-0.178-0.707-0.388-1.025-0.629    c-0.319-0.241-0.583-0.526-0.793-0.854c-0.21-0.328-0.314-0.738-0.314-1.23c0-0.446,0.082-0.843,0.246-1.189    s0.385-0.641,0.663-0.882c0.278-0.241,0.602-0.426,0.971-0.554s0.759-0.191,1.169-0.191c0.419,0,0.843,0.039,1.271,0.116    c0.428,0.077,0.774,0.203,1.039,0.376c-0.055,0.118-0.119,0.248-0.191,0.39c-0.073,0.142-0.142,0.273-0.205,0.396    c-0.064,0.123-0.119,0.226-0.164,0.308c-0.046,0.082-0.073,0.128-0.082,0.137c-0.055-0.027-0.116-0.063-0.185-0.109    s-0.167-0.091-0.294-0.137c-0.128-0.046-0.296-0.077-0.506-0.096c-0.21-0.019-0.479-0.014-0.807,0.014    c-0.183,0.019-0.355,0.07-0.52,0.157s-0.31,0.193-0.438,0.321c-0.128,0.128-0.228,0.271-0.301,0.431    c-0.073,0.159-0.109,0.313-0.109,0.458c0,0.364,0.104,0.658,0.314,0.882c0.209,0.224,0.469,0.419,0.779,0.588    c0.31,0.169,0.647,0.333,1.012,0.492c0.364,0.159,0.704,0.354,1.019,0.581s0.576,0.513,0.786,0.854    C29.528,49.261,29.633,49.7,29.633,50.238z"/> <path fill="#FFFFFF" d="M34.035,53.055l-3.131-10.131h1.873l2.338,8.695l2.475-8.695h1.859l-3.281,10.131H34.035z"/> </g> <path fill="#C8BDB8" d="M23.5,16v-4h-12v4v2v2v2v2v2v2v2v4h10h2h21v-4v-2v-2v-2v-2v-2v-4H23.5z M13.5,14h8v2h-8V14z    M13.5,18h8v2h-8V18z M13.5,22h8v2h-8V22z M13.5,26h8v2h-8V26z M21.5,32h-8v-2h8V32z M42.5,32h-19v-2h19V32z M42.5,28h-19v-2h19V28   z M42.5,24h-19v-2h19V24z M23.5,20v-2h19v2H23.5z"/> </svg>';
            break;
            case "pdf":
            result.type = "DOCUMENT";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#CC4B4C" d="M19.514,33.324L19.514,33.324c-0.348,0-0.682-0.113-0.967-0.326   c-1.041-0.781-1.181-1.65-1.115-2.242c0.182-1.628,2.195-3.332,5.985-5.068c1.504-3.296,2.935-7.357,3.788-10.75   c-0.998-2.172-1.968-4.99-1.261-6.643c0.248-0.579,0.557-1.023,1.134-1.215c0.228-0.076,0.804-0.172,1.016-0.172   c0.504,0,0.947,0.649,1.261,1.049c0.295,0.376,0.964,1.173-0.373,6.802c1.348,2.784,3.258,5.62,5.088,7.562   c1.311-0.237,2.439-0.358,3.358-0.358c1.566,0,2.515,0.365,2.902,1.117c0.32,0.622,0.189,1.349-0.39,2.16   c-0.557,0.779-1.325,1.191-2.22,1.191c-1.216,0-2.632-0.768-4.211-2.285c-2.837,0.593-6.15,1.651-8.828,2.822   c-0.836,1.774-1.637,3.203-2.383,4.251C21.273,32.654,20.389,33.324,19.514,33.324z M22.176,28.198   c-2.137,1.201-3.008,2.188-3.071,2.744c-0.01,0.092-0.037,0.334,0.431,0.692C19.685,31.587,20.555,31.19,22.176,28.198z    M35.813,23.756c0.815,0.627,1.014,0.944,1.547,0.944c0.234,0,0.901-0.01,1.21-0.441c0.149-0.209,0.207-0.343,0.23-0.415   c-0.123-0.065-0.286-0.197-1.175-0.197C37.12,23.648,36.485,23.67,35.813,23.756z M28.343,17.174   c-0.715,2.474-1.659,5.145-2.674,7.564c2.09-0.811,4.362-1.519,6.496-2.02C30.815,21.15,29.466,19.192,28.343,17.174z    M27.736,8.712c-0.098,0.033-1.33,1.757,0.096,3.216C28.781,9.813,27.779,8.698,27.736,8.712z"/> <path fill="#CC4B4C" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M17.385,53h-1.641V42.924h2.898c0.428,0,0.852,0.068,1.271,0.205    c0.419,0.137,0.795,0.342,1.128,0.615c0.333,0.273,0.602,0.604,0.807,0.991s0.308,0.822,0.308,1.306    c0,0.511-0.087,0.973-0.26,1.388c-0.173,0.415-0.415,0.764-0.725,1.046c-0.31,0.282-0.684,0.501-1.121,0.656    s-0.921,0.232-1.449,0.232h-1.217V53z M17.385,44.168v3.992h1.504c0.2,0,0.398-0.034,0.595-0.103    c0.196-0.068,0.376-0.18,0.54-0.335c0.164-0.155,0.296-0.371,0.396-0.649c0.1-0.278,0.15-0.622,0.15-1.032    c0-0.164-0.023-0.354-0.068-0.567c-0.046-0.214-0.139-0.419-0.28-0.615c-0.142-0.196-0.34-0.36-0.595-0.492    c-0.255-0.132-0.593-0.198-1.012-0.198H17.385z"/> <path fill="#FFFFFF" d="M32.219,47.682c0,0.829-0.089,1.538-0.267,2.126s-0.403,1.08-0.677,1.477s-0.581,0.709-0.923,0.937    s-0.672,0.398-0.991,0.513c-0.319,0.114-0.611,0.187-0.875,0.219C28.222,52.984,28.026,53,27.898,53h-3.814V42.924h3.035    c0.848,0,1.593,0.135,2.235,0.403s1.176,0.627,1.6,1.073s0.74,0.955,0.95,1.524C32.114,46.494,32.219,47.08,32.219,47.682z     M27.352,51.797c1.112,0,1.914-0.355,2.406-1.066s0.738-1.741,0.738-3.09c0-0.419-0.05-0.834-0.15-1.244    c-0.101-0.41-0.294-0.781-0.581-1.114s-0.677-0.602-1.169-0.807s-1.13-0.308-1.914-0.308h-0.957v7.629H27.352z"/> <path fill="#FFFFFF" d="M36.266,44.168v3.172h4.211v1.121h-4.211V53h-1.668V42.924H40.9v1.244H36.266z"/> </g> </svg>';
            break;
            case "js":
            case "json":
            case "rtf":
            result.type = "DOCUMENT";
            break;
            case "bmp":
            case "gif":
            case "jpg":
            case "jpeg":
            case "png":
            result.type = "IMAGE";
            break;
            case "mp3":
            result.type = "AUDIO";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#7D6599" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <path fill="#C8BDB8" d="M35.67,14.986c-0.567-0.796-1.3-1.543-2.308-2.351c-3.914-3.131-4.757-6.277-4.862-6.738V5   c0-0.553-0.447-1-1-1s-1,0.447-1,1v1v8.359v9.053h-3.706c-3.882,0-6.294,1.961-6.294,5.117c0,3.466,2.24,5.706,5.706,5.706   c3.471,0,6.294-2.823,6.294-6.294V16.468l0.298,0.243c0.34,0.336,0.861,0.72,1.521,1.205c2.318,1.709,6.2,4.567,5.224,7.793   C35.514,25.807,35.5,25.904,35.5,26c0,0.43,0.278,0.826,0.71,0.957C36.307,26.986,36.404,27,36.5,27c0.43,0,0.826-0.278,0.957-0.71   C39.084,20.915,37.035,16.9,35.67,14.986z M26.5,27.941c0,2.368-1.926,4.294-4.294,4.294c-2.355,0-3.706-1.351-3.706-3.706   c0-2.576,2.335-3.117,4.294-3.117H26.5V27.941z M31.505,16.308c-0.571-0.422-1.065-0.785-1.371-1.081l-1.634-1.34v-3.473   c0.827,1.174,1.987,2.483,3.612,3.783c0.858,0.688,1.472,1.308,1.929,1.95c0.716,1.003,1.431,2.339,1.788,3.978   C34.502,18.515,32.745,17.221,31.505,16.308z"/> <g> <path fill="#FFFFFF" d="M22.4,42.924h1.668V53H22.4v-6.932l-2.256,5.605h-1.449l-2.27-5.605V53h-1.668V42.924h1.668    l2.994,6.891L22.4,42.924z"/> <path fill="#FFFFFF" d="M28.211,53H26.57V42.924h2.898c0.429,0,0.853,0.068,1.271,0.205s0.795,0.342,1.128,0.615    s0.602,0.604,0.807,0.991s0.308,0.822,0.308,1.306c0,0.511-0.087,0.973-0.26,1.388s-0.415,0.764-0.725,1.046    s-0.684,0.501-1.121,0.656s-0.921,0.232-1.449,0.232h-1.217V53z M28.211,44.168v3.992h1.504c0.2,0,0.398-0.034,0.595-0.103    s0.376-0.18,0.54-0.335s0.296-0.371,0.396-0.649s0.15-0.622,0.15-1.032c0-0.164-0.022-0.354-0.068-0.567s-0.139-0.419-0.28-0.615    s-0.34-0.36-0.595-0.492s-0.593-0.198-1.012-0.198H28.211z"/> <path fill="#FFFFFF" d="M38.615,47.695c0.21,0.027,0.426,0.096,0.649,0.205s0.431,0.265,0.622,0.465    s0.351,0.444,0.479,0.731s0.191,0.617,0.191,0.991c0,0.456-0.066,0.85-0.198,1.183s-0.299,0.608-0.499,0.827    s-0.426,0.395-0.677,0.526s-0.494,0.23-0.731,0.294s-0.453,0.104-0.649,0.123s-0.349,0.027-0.458,0.027    c-0.766,0-1.369-0.053-1.812-0.157s-0.75-0.212-0.923-0.321l0.369-1.176c0.082,0.046,0.159,0.096,0.232,0.15    s0.178,0.107,0.314,0.157s0.328,0.091,0.574,0.123s0.583,0.048,1.012,0.048c0.629,0,1.099-0.171,1.408-0.513    s0.465-0.772,0.465-1.292c0-0.492-0.142-0.907-0.424-1.244s-0.697-0.506-1.244-0.506h-1.395h0.014l-0.014-1.107h0.93    c0.2,0,0.403-0.005,0.608-0.014s0.398-0.06,0.581-0.15s0.333-0.246,0.451-0.465s0.178-0.533,0.178-0.943    c0-0.164-0.014-0.337-0.041-0.52s-0.103-0.351-0.226-0.506s-0.303-0.28-0.54-0.376s-0.565-0.144-0.984-0.144    s-0.754,0.039-1.005,0.116s-0.439,0.139-0.567,0.185l-0.479-1.23c0.219-0.063,0.49-0.132,0.813-0.205s0.791-0.109,1.401-0.109    c0.429,0,0.834,0.053,1.217,0.157s0.718,0.271,1.005,0.499s0.515,0.52,0.684,0.875s0.253,0.774,0.253,1.258    c0,0.282-0.05,0.54-0.15,0.772s-0.228,0.436-0.383,0.608s-0.328,0.316-0.52,0.431S38.779,47.659,38.615,47.695z"/> </g> </svg>';
            break;
            case "aac":
            case "au":
            case "flac":
            case "m4a":
            case "ogg":
            case "wav":
            case "wma":
            case "webm":
            result.type = "AUDIO";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#7D6599" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <path fill="#C8BDB8" d="M35.67,14.986c-0.567-0.796-1.3-1.543-2.308-2.351c-3.914-3.131-4.757-6.277-4.862-6.738V5   c0-0.553-0.447-1-1-1s-1,0.447-1,1v1v8.359v9.053h-3.706c-3.882,0-6.294,1.961-6.294,5.117c0,3.466,2.24,5.706,5.706,5.706   c3.471,0,6.294-2.823,6.294-6.294V16.468l0.298,0.243c0.34,0.336,0.861,0.72,1.521,1.205c2.318,1.709,6.2,4.567,5.224,7.793   C35.514,25.807,35.5,25.904,35.5,26c0,0.43,0.278,0.826,0.71,0.957C36.307,26.986,36.404,27,36.5,27c0.43,0,0.826-0.278,0.957-0.71   C39.084,20.915,37.035,16.9,35.67,14.986z M26.5,27.941c0,2.368-1.926,4.294-4.294,4.294c-2.355,0-3.706-1.351-3.706-3.706   c0-2.576,2.335-3.117,4.294-3.117H26.5V27.941z M31.505,16.308c-0.571-0.422-1.065-0.785-1.371-1.081l-1.634-1.34v-3.473   c0.827,1.174,1.987,2.483,3.612,3.783c0.858,0.688,1.472,1.308,1.929,1.95c0.716,1.003,1.431,2.339,1.788,3.978   C34.502,18.515,32.745,17.221,31.505,16.308z"/> </svg>';
            break;
            case "mp4":
            result.type = "VIDEO";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <path fill="#FF5364" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M22.4,42.924h1.668V53H22.4v-6.932l-2.256,5.605h-1.449l-2.27-5.605V53h-1.668V42.924h1.668    l2.994,6.891L22.4,42.924z"/> <path fill="#FFFFFF" d="M28.211,53H26.57V42.924h2.898c0.428,0,0.852,0.068,1.271,0.205    c0.419,0.137,0.795,0.342,1.128,0.615c0.333,0.273,0.602,0.604,0.807,0.991s0.308,0.822,0.308,1.306    c0,0.511-0.087,0.973-0.26,1.388c-0.173,0.415-0.415,0.764-0.725,1.046c-0.31,0.282-0.684,0.501-1.121,0.656    s-0.921,0.232-1.449,0.232h-1.217V53z M28.211,44.168v3.992h1.504c0.2,0,0.398-0.034,0.595-0.103    c0.196-0.068,0.376-0.18,0.54-0.335s0.296-0.371,0.396-0.649c0.1-0.278,0.15-0.622,0.15-1.032c0-0.164-0.023-0.354-0.068-0.567    c-0.046-0.214-0.139-0.419-0.28-0.615c-0.142-0.196-0.34-0.36-0.595-0.492c-0.255-0.132-0.593-0.198-1.012-0.198H28.211z"/> <path fill="#FFFFFF" d="M38.479,50.648h-4.361V49.35l4.361-6.426h1.668v6.426h1.053v1.299h-1.053V53h-1.668V50.648z     M38.479,49.35v-4.512L35.58,49.35H38.479z"/> </g> <path fill="#C8BDB8" d="M24.5,28c-0.166,0-0.331-0.041-0.481-0.123C23.699,27.701,23.5,27.365,23.5,27V13   c0-0.365,0.199-0.701,0.519-0.877c0.321-0.175,0.71-0.162,1.019,0.033l11,7C36.325,19.34,36.5,19.658,36.5,20   s-0.175,0.66-0.463,0.844l-11,7C24.874,27.947,24.687,28,24.5,28z M25.5,14.821v10.357L33.637,20L25.5,14.821z"/> <path fill="#C8BDB8" d="M28.5,35c-8.271,0-15-6.729-15-15s6.729-15,15-15s15,6.729,15,15S36.771,35,28.5,35z M28.5,7   c-7.168,0-13,5.832-13,13s5.832,13,13,13s13-5.832,13-13S35.668,7,28.5,7z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> </svg>';
            break;
            case "avi":
            result.type = "VIDEO";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#D75E72" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M16.361,53l3.527-10.063h1.627L25.016,53H23.32l-0.725-2.092h-3.787L18.07,53H16.361z     M19.191,49.801h3.008l-1.49-4.348L19.191,49.801z"/> <path fill="#FFFFFF" d="M29.828,53.055l-3.131-10.131h1.873l2.338,8.695l2.475-8.695h1.859l-3.281,10.131H29.828z"/> <path fill="#FFFFFF" d="M38.988,53H37.32V42.924h1.668V53z"/> </g> <polygon fill="#C8BDB8" points="23.5,28 23.5,20.954 23.5,14 34.5,21  "/> </svg>';
            break;
            case "mov":
            result.type = "VIDEO";
            break;
            case "psd":
            result.type = "GRAPHIC";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <path fill="#5889C4" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M17.385,53h-1.641V42.924h2.898c0.428,0,0.852,0.068,1.271,0.205    c0.419,0.137,0.795,0.342,1.128,0.615c0.333,0.273,0.602,0.604,0.807,0.991s0.308,0.822,0.308,1.306    c0,0.511-0.087,0.973-0.26,1.388c-0.173,0.415-0.415,0.764-0.725,1.046c-0.31,0.282-0.684,0.501-1.121,0.656    s-0.921,0.232-1.449,0.232h-1.217V53z M17.385,44.168v3.992h1.504c0.2,0,0.398-0.034,0.595-0.103    c0.196-0.068,0.376-0.18,0.54-0.335c0.164-0.155,0.296-0.371,0.396-0.649c0.1-0.278,0.15-0.622,0.15-1.032    c0-0.164-0.023-0.354-0.068-0.567c-0.046-0.214-0.139-0.419-0.28-0.615c-0.142-0.196-0.34-0.36-0.595-0.492    c-0.255-0.132-0.593-0.198-1.012-0.198H17.385z"/> <path fill="#FFFFFF" d="M29.73,50.238c0,0.364-0.075,0.718-0.226,1.06s-0.362,0.643-0.636,0.902s-0.611,0.467-1.012,0.622    c-0.401,0.155-0.857,0.232-1.367,0.232c-0.219,0-0.444-0.012-0.677-0.034s-0.467-0.062-0.704-0.116    c-0.237-0.055-0.463-0.13-0.677-0.226c-0.214-0.096-0.399-0.212-0.554-0.349l0.287-1.176c0.127,0.073,0.289,0.144,0.485,0.212    c0.196,0.068,0.398,0.132,0.608,0.191c0.209,0.06,0.419,0.107,0.629,0.144c0.209,0.036,0.405,0.055,0.588,0.055    c0.556,0,0.982-0.13,1.278-0.39c0.296-0.26,0.444-0.645,0.444-1.155c0-0.31-0.105-0.574-0.314-0.793    c-0.21-0.219-0.472-0.417-0.786-0.595s-0.654-0.355-1.019-0.533c-0.365-0.178-0.707-0.388-1.025-0.629    c-0.319-0.241-0.583-0.526-0.793-0.854c-0.21-0.328-0.314-0.738-0.314-1.23c0-0.446,0.082-0.843,0.246-1.189    s0.385-0.641,0.663-0.882c0.278-0.241,0.602-0.426,0.971-0.554s0.759-0.191,1.169-0.191c0.419,0,0.843,0.039,1.271,0.116    c0.428,0.077,0.774,0.203,1.039,0.376c-0.055,0.118-0.119,0.248-0.191,0.39c-0.073,0.142-0.142,0.273-0.205,0.396    c-0.064,0.123-0.119,0.226-0.164,0.308c-0.046,0.082-0.073,0.128-0.082,0.137c-0.055-0.027-0.116-0.063-0.185-0.109    s-0.167-0.091-0.294-0.137c-0.128-0.046-0.296-0.077-0.506-0.096c-0.21-0.019-0.479-0.014-0.807,0.014    c-0.183,0.019-0.355,0.07-0.52,0.157s-0.31,0.193-0.438,0.321c-0.128,0.128-0.228,0.271-0.301,0.431    c-0.073,0.159-0.109,0.313-0.109,0.458c0,0.364,0.104,0.658,0.314,0.882c0.209,0.224,0.469,0.419,0.779,0.588    c0.31,0.169,0.647,0.333,1.012,0.492c0.364,0.159,0.704,0.354,1.019,0.581s0.576,0.513,0.786,0.854    C29.625,49.261,29.73,49.7,29.73,50.238z"/> <path fill="#FFFFFF" d="M39.629,47.682c0,0.829-0.089,1.538-0.267,2.126s-0.403,1.08-0.677,1.477s-0.581,0.709-0.923,0.937    s-0.672,0.398-0.991,0.513c-0.319,0.114-0.611,0.187-0.875,0.219C35.632,52.984,35.436,53,35.309,53h-3.814V42.924h3.035    c0.848,0,1.593,0.135,2.235,0.403s1.176,0.627,1.6,1.073s0.74,0.955,0.95,1.524C39.524,46.494,39.629,47.08,39.629,47.682z     M34.762,51.797c1.112,0,1.914-0.355,2.406-1.066s0.738-1.741,0.738-3.09c0-0.419-0.05-0.834-0.15-1.244    c-0.101-0.41-0.294-0.781-0.581-1.114s-0.677-0.602-1.169-0.807s-1.13-0.308-1.914-0.308h-0.957v7.629H34.762z"/> </g> <path fill="#C8BDB8" d="M38.894,11.163c-0.463-0.301-1.082-0.171-1.384,0.291c-1.433,2.196-3.979,5.164-5.19,6.375   l-2.788,2.788l-2.828-2.828L29.49,15c1.771-1.771,6.271-5.442,8.116-6.102c0.04-0.006,0.091-0.015,0.112-0.02   c0.521-0.117,0.827-0.617,0.735-1.143c-0.093-0.526-0.616-0.885-1.143-0.814l-0.283,0.062c-2.439,0.813-7.457,5.108-8.952,6.604   l-7.185,7.185c-0.095-0.004-0.189-0.014-0.285-0.014c-2.971,0-5.463,2.125-5.983,5.016l-0.108,0.073l-0.02,0.536   c-0.034,0.942-0.302,4.052-2.343,4.546c-0.517,0.129-0.858,0.625-0.793,1.152L11.52,33h6.98l0.02,0v0l2.086-0.03   c3.367,0,6.107-2.74,6.107-6.107c0-0.193-0.011-0.383-0.029-0.572l7.049-7.048c1.305-1.305,3.925-4.358,5.451-6.696   C39.486,12.084,39.356,11.465,38.894,11.163z M20.606,30.97h-3.739L16.882,31h-1.661c0.887-1.341,1.161-3.037,1.244-4.045   l0.082-0.504c0.213-2.106,1.958-3.694,4.06-3.694c0.121,0,0.235,0.025,0.354,0.036l0.167,0.021c1.045,0.134,1.956,0.655,2.6,1.411   c0.058,0.069,0.118,0.135,0.171,0.208c0.082,0.11,0.155,0.227,0.226,0.345c0.05,0.085,0.097,0.172,0.142,0.26   c0.063,0.126,0.124,0.254,0.174,0.387c0.03,0.08,0.052,0.164,0.077,0.247c0.045,0.147,0.091,0.294,0.12,0.449l0.005,0.026   c0.041,0.234,0.072,0.471,0.072,0.716C24.713,29.127,22.871,30.97,20.606,30.97z M25.516,23.247   c-0.007-0.009-0.013-0.017-0.02-0.026c-0.605-0.811-1.405-1.465-2.332-1.895l2.123-2.123l2.828,2.828l-2.071,2.07   C25.893,23.801,25.715,23.516,25.516,23.247z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> </svg>';
            break;
            case "ai":
            case "eps":
            result.type = "GRAPHIC";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <path fill="#FFC14F" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M20.067,53l3.527-10.063h1.627L28.722,53h-1.695l-0.725-2.092h-3.787L21.776,53H20.067z     M22.897,49.801h3.008l-1.49-4.348L22.897,49.801z"/> <path fill="#FFFFFF" d="M32.536,53h-1.668V42.924h1.668V53z"/> </g> <path fill="#C8BDB8" d="M37.5,11v0.461c-3.071,0.968-5.503,3.382-6.502,6.44C30.311,17.346,29.45,17,28.5,17   c-1.859,0-3.411,1.28-3.858,3H21.5v-2h-6v6h6v-2h2.921c-0.336,2.663-1.985,4.978-4.389,6.163C19.364,26.884,18.04,26,16.5,26   c-2.206,0-4,1.794-4,4s1.794,4,4,4c2.146,0,3.888-1.702,3.982-3.825c2.655-1.151,4.647-3.387,5.524-6.073   C26.692,24.655,27.552,25,28.5,25c1.859,0,3.411-1.28,3.858-3H35.5v2h6v-6h-6v2h-2.931c0.379-3.019,2.444-5.514,5.222-6.518   C38.383,14.955,39.818,16,41.5,16c2.206,0,4-1.794,4-4v-1H37.5z M19.5,22h-2v-2h2V22z M16.5,32c-1.103,0-2-0.897-2-2s0.897-2,2-2   s2,0.897,2,2S17.603,32,16.5,32z M37.5,20h2v2h-2V20z M28.5,23c-1.103,0-2-0.897-2-2s0.897-2,2-2s2,0.897,2,2S29.603,23,28.5,23z    M41.5,14c-0.723,0-1.353-0.389-1.704-0.964C40.028,13.015,40.262,13,40.5,13h2.731C42.886,13.597,42.239,14,41.5,14z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> </svg>';
            break;
            case "zip":
            case "zipx":
            result.type = "COMPRESSION";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <path fill="#556080" d="M48.037,56H7.963C7.155,56,6.5,55.345,6.5,54.537V39h43v15.537C49.5,55.345,48.845,56,48.037,56z"/> <g> <path fill="#FFFFFF" d="M25.266,42.924v1.326l-4.799,7.205l-0.273,0.219h5.072V53h-6.699v-1.326l4.799-7.205l0.287-0.219    h-5.086v-1.326H25.266z"/> <path fill="#FFFFFF" d="M29.271,53h-1.668V42.924h1.668V53z"/> <path fill="#FFFFFF" d="M33.414,53h-1.641V42.924h2.898c0.428,0,0.852,0.068,1.271,0.205    c0.419,0.137,0.795,0.342,1.128,0.615c0.333,0.273,0.602,0.604,0.807,0.991s0.308,0.822,0.308,1.306    c0,0.511-0.087,0.973-0.26,1.388c-0.173,0.415-0.415,0.764-0.725,1.046c-0.31,0.282-0.684,0.501-1.121,0.656    s-0.921,0.232-1.449,0.232h-1.217V53z M33.414,44.168v3.992h1.504c0.2,0,0.398-0.034,0.595-0.103    c0.196-0.068,0.376-0.18,0.54-0.335s0.296-0.371,0.396-0.649c0.1-0.278,0.15-0.622,0.15-1.032c0-0.164-0.023-0.354-0.068-0.567    c-0.046-0.214-0.139-0.419-0.28-0.615c-0.142-0.196-0.34-0.36-0.595-0.492c-0.255-0.132-0.593-0.198-1.012-0.198H33.414z"/> </g> <g> <path fill="#C8BDB8" d="M28.5,24v-2h2v-2h-2v-2h2v-2h-2v-2h2v-2h-2v-2h2V8h-2V6h-2v2h-2v2h2v2h-2v2h2v2h-2v2h2v2h-2v2h2v2    h-4v5c0,2.757,2.243,5,5,5s5-2.243,5-5v-5H28.5z M30.5,29c0,1.654-1.346,3-3,3s-3-1.346-3-3v-3h6V29z"/> <path fill="#C8BDB8" d="M26.5,30h2c0.552,0,1-0.447,1-1s-0.448-1-1-1h-2c-0.552,0-1,0.447-1,1S25.948,30,26.5,30z"/> </g> </svg>';
            break;
            case "7z":
            case "cab":
            case "dmg":
            case "jar":
            case "rar":
            case "sxf":
            result.type = "COMPRESSION";
            result.icon = '<svg class="full" viewBox="0 0 56 56"> <path fill="#E9E9E0" d="M36.985,0H7.963C7.155,0,6.5,0.655,6.5,1.926V55c0,0.345,0.655,1,1.463,1h40.074   c0.808,0,1.463-0.655,1.463-1V12.978c0-0.696-0.093-0.92-0.257-1.085L37.607,0.257C37.442,0.093,37.218,0,36.985,0z"/> <polygon fill="#D9D7CA" points="37.5,0.151 37.5,12 49.349,12  "/> <g> <rect x="26.5" y="42" fill="#C8BDB8" width="2" height="14"/> <polygon fill="#C8BDB8" points="30.5,23 30.5,21 28.5,21 28.5,19 26.5,19 26.5,21 24.5,21 24.5,23 26.5,23 26.5,25     24.5,25 24.5,27 26.5,27 26.5,29 24.5,29 24.5,31 26.5,31 26.5,34 28.5,34 28.5,31 30.5,31 30.5,29 28.5,29 28.5,27 30.5,27     30.5,25 28.5,25 28.5,23   "/> </g> <g> <rect x="23.5" y="34" fill="#CBB292" width="8" height="8"/> <path fill="#5E5F62" d="M32.5,43h-10V33h10V43z M24.5,41h6v-6h-6V41z"/> </g> <rect x="23.5" y="36" fill="#5E5F62" width="8" height="2"/> </svg>';
            break;
            default:
            result.type = "OTHER";
            break;
        }
        return result;
    }
    $scope.iframeTrusted = function(url) {
        return $sce.trustAsResourceUrl(url);
    }
    $scope.fileView = function(url, $itemid) {
        var html = "";
        var type = $scope.getFileType(url).type;
        var urlTrusted = $scope.iframeTrusted(url);
        var urlTrustedDocument = $scope.iframeTrusted('http://docs.google.com/gview?url=' + url + '&embedded=true');
        var htmlOverLay = '<div style="position: relative;">';
        htmlOverLay += '<div style="background-color: transparent; height: 90vh; position: absolute; width: 100vw; z-index: -1;"></div>';
        htmlOverLay += '<div style="background-color: #d1d1d1; height: 100vh; position: absolute; left: 0px; width: 12px; z-index: -1;"></div>';
        htmlOverLay += '<div style="background-color: #d1d1d1; height: 12px; position: absolute; top: 0px; width: 100vw; z-index: -1;"></div>';
        htmlOverLay += '<div style="background-color: #d1d1d1; height: 100vh; position: absolute; right: 0px; width: 12px; z-index: -1;"></div>';
        switch (type) {
            case "DOCUMENT":
            html = htmlOverLay + '<iframe id="' + $itemid + '" style="position:relative; min-height: 100vh;width: 100vw; background: #d1d1d1;" data-tap-disabled="true" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen src="#" ngsrc="' + urlTrustedDocument + '"></iframe></div>';
            break;
            case "IMAGE": 
            html = '<img ng-src="' + url + '" />'; 
            break; 
            case "AUDIO": 
            html = '<audio controls="controls"><source ng-src="' + urlTrusted + '" /></audio>'; 
            break; 
            case "VIDEO": 
            html = '<video controls="controls"><source ng-src="' + urlTrusted + '" /></video>'; 
            break;
            case "OTHER":
            html = htmlOverLay + '<iframe id="' + $itemid + '" style="position:relative; min-height: 100vh;width: 100vw; background: #d1d1d1;" data-tap-disabled="true" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen src="#" ngsrc="' + urlTrustedDocument + '"></iframe></div>';
            break;
        }
        return html;
    }
    // end file manager
    window.addEventListener('native.keyboardhide', keyboardHideHandler);
    window.addEventListener('native.keyboardshow', keyboardShowHandler);
    $scope.openKeyboard = function(kh) {
        $(".app-content-popup.show").css("padding-bottom", kh + "px");
        $(".app-confirm-popup.show").css("bottom", kh + "px");
    }
    $scope.closeKeyboard = function() {
        //$(".app-content-popup.show").css("padding-bottom", 0);
        $(".app-content-popup").css("padding-bottom", 0);
        $(".app-confirm-popup").css("bottom", 0);
    }
    function keyboardShowHandler(e) {
        if (document.activeElement === document.body) {
            if (window.cordova) {
                window.cordova.plugins.Keyboard.close();
            }
        }
        if (isiOs) {
            angular.element('body').find('.pane').first().attr('style', 'height: ' + (($(window).height() - e.keyboardHeight) * 100) / $(window).height() + 'vh !important;');
            if (chat_head != null) {
                chat_head.show_keyboard = true;
                chat_head.keyboard_height = e.keyboardHeight;
                chat_head.overLapChat();
            }
        }
        if (document.activeElement.tagName == 'TEXTAREA' && document.activeElement.id == 'message') {
            return;
        }
        $scope.focusHandler(document.activeElement);
    }
    function keyboardHideHandler(e) {
        angular.element($scope.currentTarget).blur();
        $scope.currentTarget = null;
        if (isiOs) {
            angular.element('body').find('.pane').first().attr('style', 'height: 100vh !important;');
            if (chat_head != null) {
                chat_head.show_keyboard = false;
                chat_head.keyboard_height = 0;
                chat_head.overLapChat();
            }
        }
        var $lastPopup = angular.element('.dashboard .app-content-popup.show').last();
        var currentDelegateScroll = $lastPopup.find('ion-scroll');
        if ($lastPopup.find('ion-slides').length > 0) {
            currentDelegateScroll = $lastPopup.find('.swiper-slide-active').find('ion-scroll').attr('delegate-handle');
        } else {
            currentDelegateScroll = $lastPopup.find('ion-scroll').attr('delegate-handle');
        }
        $ionicScrollDelegate.$getByHandle(currentDelegateScroll).resize();
    }
    $interval(function() {
        $scope.classDevice = isiOs ? 'ios' : 'android';
    }, 5000);
    var currentScrollContentTop = 0;
    var previousScrollContentTop = 0;
    // move from focusHandle to here
    $scope.focusHandler = function($target) {
        if (angular.element($target).hasClass('sp-input')) return;
        if (angular.element($target).find('option').length) return;
        $scope.currentTarget = $target;
        var $lastPopup = angular.element('.dashboard .app-content-popup.show').last();
        var currentDelegateScroll = $lastPopup.find('ion-scroll');
        if ($lastPopup.find('ion-slides').length > 0) {
            currentDelegateScroll = $lastPopup.find('.swiper-slide-active').find('ion-scroll').attr('delegate-handle');
        } else {
            currentDelegateScroll = $lastPopup.find('ion-scroll').attr('delegate-handle');
        }
        var offsetTop = parseInt($ionicPosition.offset(angular.element($target).closest('.itm')).top);
        var scrollTop = parseInt($ionicScrollDelegate.$getByHandle(currentDelegateScroll).getScrollPosition().top);
        var contentTop = $ionicPosition.offset(angular.element($lastPopup.find('.app-content'))).top;
        var y = (offsetTop + scrollTop) - contentTop;
        $ionicScrollDelegate.$getByHandle(currentDelegateScroll).resize();
        $ionicScrollDelegate.$getByHandle(currentDelegateScroll).scrollTo(0, y, true);
    }
    $scope.scrollContent = function(scroller) {
        previousScrollContentTop = currentScrollContentTop;
        currentScrollContentTop = parseInt($ionicScrollDelegate.$getByHandle(scroller).getScrollPosition().top);
        var maxScrollContentTop = parseInt($ionicScrollDelegate.$getByHandle(scroller).getScrollView().__maxScrollTop);
        var $scroller = $('.app-content-popup.show').last().find('.app-header');
        if (previousScrollContentTop > 0 && currentScrollContentTop > 0 && currentScrollContentTop > 100 && previousScrollContentTop <= maxScrollContentTop && currentScrollContentTop <= maxScrollContentTop) {
            if (currentScrollContentTop > previousScrollContentTop) {
                if (!$scroller.hasClass('collapse-height')) {
                    $scroller.addClass('collapse-height');
                } else {
                    if (currentScrollContentTop == maxScrollContentTop) {
                        $ionicScrollDelegate.$getByHandle(scroller).scrollBottom(true);
                    }
                }
            } else if (currentScrollContentTop < previousScrollContentTop) {
                if ($scroller.hasClass('collapse-height')) {
                    $scroller.removeClass('collapse-height');
                }
            }
        }
        if(chat_head.show_keyboard == false){
            var _val = angular.element($scope.currentTarget).val() + "(-.-)";
            angular.element($scope.currentTarget).val(_val);
            angular.element($scope.currentTarget).val(_val.replace("(-.-)", ""));
        }
    }
    $scope.scrollContentBlur = function(scroller) {
        previousScrollContentTop = currentScrollContentTop;
        currentScrollContentTop = parseInt($ionicScrollDelegate.$getByHandle(scroller).getScrollPosition().top);
        var maxScrollContentTop = parseInt($ionicScrollDelegate.$getByHandle(scroller).getScrollView().__maxScrollTop);
        $('[delegate-handle="' + scroller + '"]').prev('.overlay-content').addClass('show');
        $('[delegate-handle="' + scroller + '"]').next('.overlay-content').addClass('show');
        if (currentScrollContentTop == 0) {
            $('[delegate-handle="' + scroller + '"]').prev('.overlay-content').removeClass('show');
        }
        if (currentScrollContentTop == maxScrollContentTop) {
            $('[delegate-handle="' + scroller + '"]').next('.overlay-content').removeClass('show');
        }
    }
    $scope.resizeScroll = function(id) {
        $ionicScrollDelegate.$getByHandle(id).resize();
    }
    $scope.sortFiletypeAppointment = function(ext) {
        switch (ext.toLowerCase()) {
            case "bmp":
            case "BMP":
            case "gif":
            case "GIF":
            case "jpeg":
            case "JPEG":
            case "jpg":
            case "JPG":
            case "png":
            case "PNG":
            return "Photo";
            break;
            case "pdf":
            case "PDF":
            return "PDFs"
            default:
            return "Other";
            break;
        }
    }
    // edit by haudao
    $scope.$on('sendGetUserData', function(e, data) {
        $scope.getUserData(data.data.id.toString(), false, data.data.status);
    });
    socket.on('check_punch_in_out', function(data) {
        if (data.userId == currentIdLogin) $scope.checkPuchIn();
    })
    // end edit
    $scope.$on('sendusertype', function(e, data) {
        $scope.usertypes = data.data;
    });
    $scope.sizeOf = function(obj) {
        return Object.keys(obj).length;
    };
    $scope.sizeHasValueOf = function(obj) {
        var count = 0;
        for (var prop in obj) {
            if (obj[prop] != '') {
                count++;
            }
        }
        return count;
    };
    $scope.clickOnlogo = function() {
        window.open('https://sites.google.com/reliablegaragedoor.com/intranet/home', '_system');
    }
    // document.addEventListener("deviceready", function () {
    //     var platform = $cordovaDevice.getPlatform();
    //     console.log(platform);
    //     if (platform == "iOS") {
    //         $timeout(function () {
    //             $("ion-content").css("margin-top", "20px");
    //             $(".app-dashboard-menu").css("margin-top", "20px");
    //         }, 500)
    //     }
    // }, false);
    $scope.$on('pushCounter', function(events, data) {
        console.log(data + "khogn co su kien nay");
        $scope.$broadcast('pushCounterChild', data);
    });
    $scope.$on('clickToCallNumber', function(e, data) {
        $scope.callNumber(data.phone_number);
    });
    $scope.$on('sentLatestMessage', function(events, data) {
        $scope.$broadcast('reciveLatestMessage', data);
    });
    $scope.loadAddress = function($query) {
        return LocationService.searchAddress($query);
    };
    $scope.selectAddress = function(value, type) {
        if (type == 'edituser') {
            if ($scope.holdValueAddress.editUserAddress.length > 0) {
                $scope.holdValueAddress.editUserAddress.splice(0, 1);
            }
        }
        if (type == 'edituserstarlocation') {
            if ($scope.holdValueAddress.editUserStarLocation.length > 0) {
                $scope.holdValueAddress.editUserStarLocation.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 == 'edituser') {
                data['locality'] ? $scope.editUsersData.dataUserDetail.city = data['locality'] : $scope.editUsersData.dataUserDetail.city = '';
                data['administrative_area_level_1'] ? $scope.editUsersData.dataUserDetail.state = data['administrative_area_level_1'] : $scope.editUsersData.dataUserDetail.state = '';
                data['postal_code'] ? $scope.editUsersData.dataUserDetail.zipcode = parseInt(data['postal_code']) : $scope.editUsersData.dataUserDetail.zipcode = '';
                $scope.editUsersData.dataUserDetail.street = location.formatted_address;
            }
            if (type == 'edituserstarlocation') {
                $scope.editUsersData.dataUserDetail.start_location = location.formatted_address;
            }
            if (type == 'edituserassignlocation') {
                $scope.editUsersData.dataUserDetail.assigned_location = location.formatted_address;
            }
        })
    };
    $scope.removetag = function(value, type) {
        if (type == 'edituser') {
            $scope.editUsersData.dataUserDetail.city = '';
            $scope.editUsersData.dataUserDetail.state = '';
            $scope.editUsersData.dataUserDetail.zipcode = '';
            $scope.editUsersData.dataUserDetail.street = '';
            $scope.holdValueAddress.editUserAddress = [];
        }
        if (type == 'edituserstarlocation') {
            $scope.editUsersData.dataUserDetail.start_location = '';
            $scope.holdValueAddress.editUserStarLocation = [];
        }
        if (type == 'edituserassignlocation') {
            $scope.editUsersData.dataUserDetail.assigned_location = '';
            $scope.holdValueAddress.editUserAssignLocation = [];
        }
    };
    //fix loi click xuyen thau va loi open keyboard
    $scope.closeTarget = function(t) {
        //$(window).trigger('native.keyboardhide');
        if (window.cordova) {
            window.cordova.plugins.Keyboard.close();
        }
        $(t + " ion-scroll").removeClass('currentScroll');
        $(t).removeClass('show');
    }
    $scope.showTarget = function(t, $callback = null) {
        if ($(t).length) {
            //$(window).trigger('native.keyboardhide'); 
            if (window.cordova) {
                window.cordova.plugins.Keyboard.close();
            }
            var isPopup = $(t).hasClass('app-content-popup') || $(t).hasClass('app-confirm-popup') || $(t).hasClass('app-setting');
            if (isPopup) {
                if ($(t).parent().hasClass('app-content-popup-area')) {
                    $(t).appendTo($(t).closest('.app-content-popup-area'));
                } else {
                    $(t).appendTo($(t).parent());
                    $(t).parent().appendTo($(t).closest('.app-content-popup-area'));
                }
                if ($(t).hasClass('popup-center')) {
                    setTimeout(function() {
                        var $contain = $(t).find('.content-area > .content');
                        $contain.find('> .content-inner').css({
                            height: "auto"
                        });
                        if (!$contain.find('> .content-inner').hasClass('auto')) {
                            var h = $contain.height();
                            $contain.find('> .content-inner').css({
                                height: h
                            });
                        }
                    }, 100);
                }
            }
            $(t).addClass('show');
            appDashboardMenuToggle('hide');
            if (chat_head == null) {
                return;
            }
            chat_head.bindOnHold();
        }
    }
    $scope.trustAsHtml = function(data) {
        if (data) {
            return $sce.trustAsHtml(data);
        }
    }
    $scope.setCustomerName = function(company_name, first_name, last_name) {
        var name = '';
        if (company_name && company_name.length > 0) {
            name = '(' + company_name + ') ' + first_name + ' ' + last_name;
        } else {
            name = first_name + ' ' + last_name;
        }
        return name;
    }
    $scope.getAutocompleteVehicles = function(query, isInitializing, style) {
        if (!query) return;
        var returnValue = {
            items: []
        };
        var params = {
            search: query
        };
        $scope.allVehicles.forEach(function(item) {
            if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                returnValue.items.push(item);
            } else if (item.id.toString().indexOf(query) > -1) {
                returnValue.items.push(item);
            }
        });
        return returnValue;
    };
    $scope.clickedMethodVehicles = function(callback, style) {
        if (style == 'edit') {
            $scope.editUsersData.assignedVehicle = callback.item;
        }
    }
    $scope.removeMethodVehicles = function(callback, style) {
        if (style == 'add') {
            $scope.addUsersData.assigned_vehicle = [];
        } else {
            $scope.editUsersData.assignedVehicle = [];
        }
    }
    $scope.setValueForVehiclesEdit = function(modelValue) {
        for (var i = 0; i < $scope.allVehicles.length; i++) {
            if ($scope.allVehicles[i].id == modelValue) {
                return $scope.allVehicles[i];
            }
        }
        return {};
    };
    $scope.checkViewClientRole = function(jsonDataObj) {
        $scope.viewInfo = jsonDataObj.child[0].check;
        $scope.showContact = jsonDataObj.child[0].child[0].check;
        $scope.contactUsers = jsonDataObj.child[0].child[0].child[0].check;
        $scope.contactMyprofile = jsonDataObj.child[0].child[0].child[1].check;
        $scope.contactUserOfDepartment = jsonDataObj.child[0].child[0].child[2].check;
        $scope.contactUserOfSupervisor = jsonDataObj.child[0].child[0].child[3].check;
        $scope.showJobInfo = jsonDataObj.child[0].child[1].check;
        $scope.jobInfoUsers = jsonDataObj.child[0].child[1].child[0].check;
        $scope.jobInfoMyprofile = jsonDataObj.child[0].child[1].child[1].check;
        $scope.jobInfoUserOfDepartment = jsonDataObj.child[0].child[1].child[2].check;
        $scope.jobInfoUserOfSupervisor = jsonDataObj.child[0].child[1].child[3].check;
        $scope.showHrInfo = jsonDataObj.child[0].child[2].check;
        $scope.hrInfoUsers = jsonDataObj.child[0].child[2].child[0].check;
        $scope.hrInfoMyprofile = jsonDataObj.child[0].child[2].child[1].check;
        $scope.hrInfoUserOfDepartment = jsonDataObj.child[0].child[2].child[2].check;
        $scope.hrInfoUserOfSupervisor = jsonDataObj.child[0].child[2].child[3].check;
        $scope.employeeManagement = jsonDataObj.child[0].child[3].check;
        $scope.employeeManagementUsers = jsonDataObj.child[0].child[3].child[0].check;
        $scope.employeeManagementMyprofile = jsonDataObj.child[0].child[3].child[1].check;
        $scope.employeeManagementUserOfDepartment = jsonDataObj.child[0].child[3].child[2].check;
        $scope.employeeManagementUserOfSupervisor = jsonDataObj.child[0].child[3].child[3].check;
        $scope.employeeIssueLog = jsonDataObj.child[0].child[4].check;
        $scope.IssueLogAllUser = jsonDataObj.child[0].child[4].child[0].check;
        $scope.IssueLogMyprofile = jsonDataObj.child[0].child[4].child[1].check;
        $scope.IssueLogUserOfDepartment = jsonDataObj.child[0].child[4].child[2].check;
        $scope.IssueLogUserOfSupervisor = jsonDataObj.child[0].child[4].child[3].check;
        $scope.viewVisibility = jsonDataObj.child[0].child[5].check;
        $scope.visibilityAllUser = jsonDataObj.child[0].child[5].child[0].check;
        $scope.visibilityMyprofile = jsonDataObj.child[0].child[5].child[1].check;
        $scope.visibilityUserOfDepartment = jsonDataObj.child[0].child[5].child[2].check;
        $scope.visibilityUserOfSupervisor = jsonDataObj.child[0].child[5].child[3].check;
        $scope.viewLoginCre = jsonDataObj.child[1].check;
        $scope.loginCreUsers = jsonDataObj.child[1].child[0].check;
        $scope.loginCreMyprofile = jsonDataObj.child[1].child[1].check;
        $scope.loginCreUserOfDepartment = jsonDataObj.child[1].child[2].check;
        $scope.loginCreUserOfSupervisor = jsonDataObj.child[1].child[3].check;
        $scope.viewFileManagement = jsonDataObj.child[2].check;
        $scope.fileUsers = jsonDataObj.child[2].child[0].check;
        $scope.fileMyprofile = jsonDataObj.child[2].child[1].check;
        $scope.fileUserOfDepartment = jsonDataObj.child[2].child[2].check;
        $scope.fileUserOfSupervisor = jsonDataObj.child[2].child[3].check;
        $scope.viewSettingTab = jsonDataObj.child[3].check;
        $scope.settingUsers = jsonDataObj.child[3].child[0].check;
        $scope.settingMyprofile = jsonDataObj.child[3].child[1].check;
        $scope.settingUserOfDepartment = jsonDataObj.child[3].child[2].check;
        $scope.settingUserOfSupervisor = jsonDataObj.child[3].child[3].check;
        $scope.viewPipus = jsonDataObj.child[4].check;
        $scope.viewPipusInfo = jsonDataObj.child[4].child[0].check;
        $scope.pipusInfoUsers = jsonDataObj.child[4].child[0].child[0].check;
        $scope.pipusInfoMyprofile = jsonDataObj.child[4].child[0].child[1].check;
        $scope.pipusInfoUserOfDepartment = jsonDataObj.child[4].child[0].child[2].check;
        $scope.pipusInfoUserOfSupervisor = jsonDataObj.child[4].child[0].child[3].check;
        $scope.pipusAction = jsonDataObj.child[4].child[1].check;
        $scope.pipusActionUsers = jsonDataObj.child[4].child[1].child[0].check;
        $scope.pipusActionMyprofile = jsonDataObj.child[4].child[1].child[1].check;
        $scope.pipusActionUserOfDepartment = jsonDataObj.child[4].child[1].child[2].check;
        $scope.pipusActionUserOfSupervisor = jsonDataObj.child[4].child[1].child[3].check;
        $scope.pipusExportt = jsonDataObj.child[4].child[2].check;
        $scope.pipusExportUsers = jsonDataObj.child[4].child[2].child[0].check;
        $scope.pipusExportMyprofile = jsonDataObj.child[4].child[2].child[1].check;
        $scope.pipusExportUserOfDepartment = jsonDataObj.child[4].child[2].child[2].check;
        $scope.pipusExportUserOfSupervisor = jsonDataObj.child[4].child[2].child[3].check;
        $scope.viewDefaultSchedules = jsonDataObj.child[5].check;
        $scope.scheduleUsers = jsonDataObj.child[5].child[0].check;
        $scope.scheduleMyprofile = jsonDataObj.child[5].child[1].check;
        $scope.scheduleUserOfDepartment = jsonDataObj.child[5].child[2].check;
        $scope.scheduleUserOfSupervisor = jsonDataObj.child[5].child[3].check;
    }
    $scope.getResultView = function(field, department_id, roleId, sup1, sup2) {
        switch (field) {
            case 'issuelog':
            var parentcheck = $scope.employeeIssueLog;
            var allUsers = $scope.IssueLogAllUser;
            var myProfile = $scope.IssueLogMyprofile;
            var userOfDepartment = $scope.IssueLogUserOfDepartment;
            var userOfSupervisor = $scope.IssueLogUserOfSupervisor;
            break;
            case 'employeemanagement':
            var parentcheck = $scope.employeeManagement;
            var allUsers = $scope.employeeManagementUsers;
            var myProfile = $scope.employeeManagementMyprofile;
            var userOfDepartment = $scope.employeeManagementUserOfDepartment;
            var userOfSupervisor = $scope.employeeManagementUserOfSupervisor;
            break;
            case 'hrinfo':
            var parentcheck = $scope.showHrInfo;
            var allUsers = $scope.hrInfoUsers;
            var myProfile = $scope.hrInfoMyprofile;
            var userOfDepartment = $scope.hrInfoUserOfDepartment;
            var userOfSupervisor = $scope.hrInfoUserOfSupervisor;
            break;
            case 'jobinfo':
            var parentcheck = $scope.showJobInfo;
            var allUsers = $scope.jobInfoUsers;
            var myProfile = $scope.jobInfoMyprofile;
            var userOfDepartment = $scope.jobInfoUserOfDepartment;
            var userOfSupervisor = $scope.jobInfoUserOfSupervisor;
            break;
            case 'contactinfo':
            var parentcheck = $scope.showContact;
            var allUsers = $scope.contactUsers;
            var myProfile = $scope.contactMyprofile;
            var userOfDepartment = $scope.contactUserOfDepartment;
            var userOfSupervisor = $scope.contactUserOfSupervisor;
            break;
            case 'logincredential':
            var parentcheck = $scope.viewLoginCre;
            var allUsers = $scope.loginCreUsers;
            var myProfile = $scope.loginCreMyprofile;
            var userOfDepartment = $scope.loginCreUserOfDepartment;
            var userOfSupervisor = $scope.loginCreUserOfSupervisor;
            break;
            case 'filemanger':
            var parentcheck = $scope.viewFileManagement;
            var allUsers = $scope.fileUsers;
            var myProfile = $scope.fileMyprofile;
            var userOfDepartment = $scope.fileUserOfDepartment;
            var userOfSupervisor = $scope.fileUserOfSupervisor;
            break;
            case 'setting':
            var parentcheck = $scope.viewSettingTab;
            var allUsers = $scope.settingUsers;
            var myProfile = $scope.settingMyprofile;
            var userOfDepartment = $scope.settingUserOfDepartment;
            var userOfSupervisor = $scope.settingUserOfSupervisor;
            break;
            case 'viewpipus':
            var parentcheck = $scope.viewPipusInfo;
            var allUsers = $scope.pipusInfoUsers;
            var myProfile = $scope.pipusInfoMyprofile;
            var userOfDepartment = $scope.pipusInfoUserOfDepartment;
            var userOfSupervisor = $scope.pipusInfoUserOfSupervisor;
            break;
            case 'pipusaction':
            var parentcheck = $scope.pipusAction;
            var allUsers = $scope.pipusActionUsers;
            var myProfile = $scope.pipusActionMyprofile;
            var userOfDepartment = $scope.pipusActionUserOfDepartment;
            var userOfSupervisor = $scope.pipusActionUserOfSupervisor;
            break;
            case 'exportpipus':
            var parentcheck = $scope.pipusExportt;
            var allUsers = $scope.pipusExportUsers;
            var myProfile = $scope.pipusExportMyprofile;
            var userOfDepartment = $scope.pipusExportUserOfDepartment;
            var userOfSupervisor = $scope.pipusExportUserOfSupervisor;
            break;
            case 'defaultschedule':
            var parentcheck = $scope.viewDefaultSchedules;
            var allUsers = $scope.scheduleUsers;
            var myProfile = $scope.scheduleMyprofile;
            var userOfDepartment = $scope.scheduleUserOfDepartment;
            var userOfSupervisor = $scope.scheduleUserOfSupervisor;
            break;
            case 'visibility':
            var parentcheck = $scope.viewVisibility;
            var allUsers = $scope.visibilityAllUser;
            var myProfile = $scope.visibilityMyprofile;
            var userOfDepartment = $scope.visibilityUserOfDepartment;
            var userOfSupervisor = $scope.visibilityUserOfSupervisor;
            break;
        }
        var datacheck = {
            parentcheck: parentcheck,
            allUsers: allUsers,
            myProfile: myProfile,
            userOfDepartment: userOfDepartment,
            userOfSupervisor: userOfSupervisor
        };
        var dataUser = {
            department_id: department_id,
            roleId: roleId,
            sup1: sup1,
            sup2: sup2
        };
        return $scope.getReturnResult(datacheck, dataUser);
    }
    ////
    $scope.getReturnResult = function(datacheck, dataUser) {
        var parentcheck = datacheck.parentcheck;
        var allUsers = datacheck.allUsers;
        var myProfile = datacheck.myProfile;
        var userOfDepartment = datacheck.userOfDepartment;
        var userOfSupervisor = datacheck.userOfSupervisor;
        var department_id = dataUser.department_id;
        var roleId = dataUser.roleId;
        var sup1 = dataUser.sup1;
        var sup2 = dataUser.sup2;
        if (parentcheck) {
            if (allUsers) {
                return true;
            } else if (myProfile && !userOfDepartment && !userOfSupervisor) {
                if ($scope.currentIdLogin == $scope.userData.dataUser.id) {
                    return checkAdminDetail(roleId);
                } else {
                    return false;
                }
            } else if (myProfile && userOfDepartment && userOfSupervisor) {
                if ($scope.currentIdLogin == $scope.userData.dataUser.id || department_id == $scope.departmentId || sup1 == $scope.currentIdLogin || sup2 == $scope.currentIdLogin) {
                    return checkAdminDetail(roleId);
                } else {
                    return false;
                }
            } else if (myProfile && userOfDepartment && !userOfSupervisor) {
                if ($scope.currentIdLogin == $scope.userData.dataUser.id || department_id == $scope.departmentId) {
                    return checkAdminDetail(roleId);
                } else {
                    return false;
                }
            } else if (myProfile && !userOfDepartment && userOfSupervisor) {
                if ($scope.currentIdLogin == $scope.userData.dataUser.id || sup1 == $scope.currentIdLogin || sup2 == $scope.currentIdLogin) {
                    return checkAdminDetail(roleId);
                } else {
                    return false;
                }
            } else if (!myProfile && userOfDepartment && userOfSupervisor) {
                if (department_id == $scope.departmentId || sup1 == $scope.currentIdLogin || sup2 == $scope.currentIdLogin) {
                    return checkAdminDetail(roleId);
                } else {
                    return false;
                }
            } else if (!myProfile && userOfDepartment && !userOfSupervisor) {
                if (department_id == $scope.departmentId) {
                    return checkAdminDetail(roleId);
                } else {
                    return false;
                }
            } else if (!myProfile && !userOfDepartment && userOfSupervisor) {
                if (sup1 == $scope.currentIdLogin || sup2 == $scope.currentIdLogin) {
                    return checkAdminDetail(roleId);
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    }
    function checkAdminDetail(roleId) {
        if ($scope.roleName == $scope.isAdmin) {
            return true;
        } else {
            if (roleId != '1') {
                return true;
            } else {
                return false;
            }
        }
    }

    $scope.showsInActiveLogincredential = function (status) {
        $scope.searchUsercredentials.show = status;
        $scope.getUsercredentials(true);
    }


    $scope.activeOrDeactiveCredential = function (id,status) {
        $ionicLoading.show({
            template: templateLoading
        });
        Usercredentials.activeAndInactiveUser(id, status).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $cordovaToast.showLongTop(data.msg);
                $scope.closeTarget('#confirmActiveOrDeactiveCredential');
                $scope.getUsercredentials();
            } else {
             $cordovaToast.showLongTop(data.msg);
         }
     });
    }

    $scope.callGetResultView = function(data) {
        $scope.userData = [];
        $scope.userData = data;
        $scope.pushResultView = {};
        $scope.viewContact = $scope.getResultView('contactinfo', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.viewJobInfo = $scope.getResultView('jobinfo', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.viewHrInfo = $scope.getResultView('hrinfo', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.showEmployeeManagement = $scope.getResultView('employeemanagement', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.showVisibility = $scope.getResultView('visibility', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.showIssueLogss = $scope.getResultView('issuelog', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.viewLoginCredential = $scope.getResultView('logincredential', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.showFileManager = $scope.getResultView('filemanger', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.showPipusInfo = $scope.getResultView('viewpipus', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.showPipusAction = $scope.getResultView('pipusaction', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.showExportPipus = $scope.getResultView('exportpipus', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
        $scope.showDefaultSchedules = $scope.getResultView('defaultschedule', data.dataUser.department_id, data.dataRole.role_id, data.dataUser.supervisor_user1, data.dataUser.supervisor_user2);
    }
    /*=====================================================*/
    /*for chat head*/
    $scope.objChatHead = function($chat_head_scope) {
        $scope.obj_chat_head = $chat_head_scope;
    };
});