pipusApp.controller('pipusCtrl', function ($cordovaFile, $cordovaActionSheet, $cordovaCamera, $cordovaFileTransfer, $cordovaInAppBrowser, //
        $cordovaImagePicker, $ionicScrollDelegate, $location, $timeout, $cordovaToast, $ionicLoading, $ionicPopup, $scope, $http, //
        $window, $interval, Login, Pipus, Userbiweeks, Departments, dataHtml,Userdetails) {

    searchPipusHandle();

    function searchPipusHandle() {
        toggleDelegateHandle('#pipus_page', '.link-pipus-search', '.pipus-search');
        toggleDelegateHandle('#pipus_page', '.pipus-search .search-type .btn-close', '.pipus-search');
        toggleDelegateHandle('#pipus_page', '.pipus-search .search-content .btn-close', '.pipus-search');
        closeOutsideHandle('.link-pipus-search, .pipus-search', '.pipus-search');
    }

    $scope.searchPipus = {
        rows: 50,
        current_page: 1,
        search: ""
    };
    /*$scope.getUsers = function(){
     User.get().success(function(data){
     $scope.users= data;
     });
     }
     $scope.getUsers();
     */
     $scope.setTime = false;
     withoutPopup = $scope;
    // $scope.dataFilterLoaded = false;
    $scope.currentIdLogin = currentIdLogin;
    $scope.roleName = role;
    $scope.isAdmin = isAdmin;
    $scope.isManager = isManager;
    $scope.isReporter = isReporter;
    $scope.isScheduler = isScheduler;
    $scope.isFieldinstaller = isFieldinstaller;
    $scope.isSalesman = isSalesman;
    $scope.isWarehouse = isWarehouse;
    $scope.dataExportPipus = {};
    $scope.checkLoadMore = false;
    $scope.time = {};
    $scope.time.start = moment().day("Sunday").format('MM/DD/YYYY');
    $scope.time.end = moment().format('MM/DD/YYYY');
    $scope.displayFromDate = {day: moment().day("Sunday").format('DD'), month: moment().day("Sunday").format('MMMM')};
    $scope.displayToDate = {day: moment().format('DD'), month: moment().format('MMMM')};
    $scope.dataPipusHtml = {};
    $scope.dataPipusHtml.totalItems = 0;
    $scope.dataPipusHtml.currentCountItems = 0;
    $scope.getDeparment = true;
    $scope.dataFilterPipus = {};
    $scope.allUser=[];
    $scope.filterNoProcess = true;

    $scope.renderTemplateData = function () {
        dataHtml.getTemplate('templates/dashboard/pipus/pipusMenuHeadermodal.tpl').success(function (results) {
            $scope.dataPipusHtml.menuHeader = results;
            dataHtml.getTemplate('templates/dashboard/pipus/pipusContentmodal.tpl').success(function (results) {
                $scope.dataPipusHtml.pipusContent = results;
                dataHtml.getTemplate('templates/dashboard/pipus/pipusPopupFiltermodal.tpl').success(function (results) {
                    $scope.dataPipusHtml.pipusFilter = results;
                    dataHtml.getTemplate('templates/dashboard/pipus/pipusQueryTimemodal.tpl').success(function (results) {
                        $scope.dataPipusHtml.queryTime = results;
                        dataHtml.getTemplate('templates/dashboard/pipus/pipusPopupSearchmodal.tpl').success(function (results) {
                            $scope.dataPipusHtml.pipusSearch = results;
                            $scope.getUserLogin();
                        });
                    });
                });
            });
        });
    }
    $scope.openByGetTemplate = function (style) {
        $ionicLoading.show({template: templateLoading});
        $timeout(function () {
            switch (style) {
                case 'appointmentToSchedule':
                dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupAppointmentToSchedulemodal.tpl').success(function (results) {
                    $scope.dataPipusHtml.appointmentToSchedule = results;
                    $scope.showTarget('#appointmentToSchedule');
                    $ionicLoading.hide();
                });
                break;
                case 'pipusEdit':
                dataHtml.getTemplate('templates/dashboard/pipus/pipusManagermentEditmodal.tpl').success(function (results) {
                    $scope.dataPipusHtml.pipusEdit = results;
                    $scope.showTarget('#pipusEdit');
                    $ionicLoading.hide();
                });
                break;
                case 'confirmDeletePunchInOut':
                dataHtml.getTemplate('templates/dashboard/pipus/pipusManagermentDeletemodal.tpl').success(function (results) {
                    $scope.dataPipusHtml.confirmDeletePunchInOut = results;
                    $scope.showTarget('#confirmDeletePunchInOut');
                    $ionicLoading.hide();
                });
                break;
            }
        }, 500);
    }
    $scope.getUserbiweeks = function () {
        Userbiweeks.getSelect().success(function (data) {
            $scope.userbiweeks = data;
        });
    }
    $scope.filterData = function (arrData) {
        var dataGroupByDate = _.groupBy(arrData, 'dateShow');
        angular.forEach(dataGroupByDate, function (item) {
            item.childData = item;
            item.childData = _.sortBy(item, 'name');
            item.childData = _.groupBy(item.childData, 'name');
        })
        return dataGroupByDate;
    }
    $scope.getPipus = function () {
        if($scope.dataFilterPipus.start_time && $scope.dataFilterPipus.end_time){
            $scope.searchPipus.start_time = moment($scope.dataFilterPipus.start_time).format('MM/DD/YYYY');
            $scope.searchPipus.end_time = moment($scope.dataFilterPipus.end_time).format('MM/DD/YYYY');
        }
        else{
            if (!$scope.setTime) {
                $scope.searchPipus.start_time = moment().day("Sunday").format('MM/DD/YYYY');
                $scope.searchPipus.end_time = moment().format('MM/DD/YYYY');
            } else {
                $scope.searchPipus.start_time = $('#start_time').html().trim();
                $scope.searchPipus.end_time = $('#end_time').html().trim();
            }
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Pipus.getPaging($scope.searchPipus).success(function (data) {
            if(data.status == false){
                $cordovaToast.showLongCenter(data.msg);
            }
            else{
                $scope.dataFilterPipus = {};
                $scope.filterNoProcess = true;
                if (data.data.length == $scope.searchPipus.rows) {
                    $timeout(function () {
                        $scope.checkLoadMore = true;
                    }, 2000)
                }
                $ionicScrollDelegate.$getByHandle('pipusContent').scrollTop();
                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 = _.sortBy(data.data, 'dateShow');
    		    $scope.pipusForExport = data.data;
    		    $scope.filterClientdata = data.data;
    		    $scope.dataPipusHtml.totalItems=data.total_rows;
    		    $scope.dataPipusHtml.currentCountItems=data.data.length;
    		    $scope.pipus = $scope.filterData(data.data);
    		    //$scope.getAllUsers();
    		    $scope.setTime = true;
    		    $ionicLoading.hide();
    		    $scope.closeTarget(".pipus-search");
    		    $("#searchInput").blur();
    		    $scope.departLabel = 'All';
    		}
	    }).error(function (data, status, headers, config) {
		$ionicLoading.hide();
		$cordovaToast.showLongTop('Add Errror!!!');
	    });
	};
	$scope.getWorkedTime = function (arrayData) {
	    var returnHour = 0;
	    var returnMinutes = 0;
	    arrayData.forEach(function (item) {
		var hour = item.duration.split('hours')[0];
		returnHour += parseInt(hour);
		var minutes = item.duration.split('hours')[1].replace('minutes', '');
		returnMinutes += parseInt(minutes);
	    });
	    returnHour += parseInt(Math.floor(returnMinutes / 60));
	    returnMinutes = returnMinutes % 60;
	    return returnHour + ' hours ' + returnMinutes + ' minutes ';
	}
	$scope.convertDate = function (value, format) {
	    return moment(value).format(format);
	}
	$scope.LoadMorePipus = function () {
	    if (!$scope.checkLoadMore)
		return;
	    $scope.searchPipus.current_page++;
	    $ionicLoading.show({
		template: templateLoading
	    });
	    Pipus.getPaging($scope.searchPipus).success(function (data) {
    		$ionicLoading.hide();
    		$scope.dataPipusHtml.currentCountItems += data.data.length;

    		if (data.data.length == 0) {
    		    $scope.checkLoadMore = false;
    		}
    		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') : '';
    		}
    		var dataPush = arrayUnion($scope.pipusForExport, data.data, function (item1, item2) {
    		    return item1.id == item2.id;
    		});
    		dataPush = _.sortBy(dataPush, 'dateShow');
    		$scope.filterClientdata = dataPush;
    		$scope.pipusForExport = dataPush;
		    // var dataPush=$scope.filterData(data.data);
		    // $scope.pipus=$scope.filterData(dataPush);
		    $scope.getfilterClient();
		});
	    $timeout(function () {
		$scope.$broadcast('scroll.infiniteScrollComplete');
	    }, 2000);
	};
	$scope.exportPipus = function() {
	    $scope.dataExportPipus = $scope.searchPipus ;
	    $scope.dataExportPipus.rows=$scope.dataPipusHtml.currentCountItems;
	    $scope.dataExportPipus.userId='';
	    $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.searchPipus_ = function () {
	    $scope.searchPipus.current_page = 1;
	    $scope.checkLoadMore = false;
	    $scope.getPipus();
        //$scope.getDataFilter();
    }
    $scope.keypress = function () {
        var keysByCode = [9, 16, 17, 18, 20, 27, 32, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 144];
        if ($scope.searchPipus.search.keyCode >= 112 && $scope.searchPipus.search.keyCode <= 123)
            return;
        if (keysByCode.indexOf($scope.searchPipus.search.keyCode) > -1)
            return;
        $scope.coundown = 10;
        if ($scope.myTime != null)
            clearInterval($scope.myTime);
        $scope.downTimer();
    };
    $scope.downTimer = function () {
        $scope.myTime = setInterval(function () {
            $scope.coundown--;
            if ($scope.coundown <= 0) {
                $ionicLoading.show({
                    template: templateLoading
                });
                $scope.searchPipus_();
                clearInterval($scope.myTime);
            }
        }, 100);
    }
    $scope.clearSearch = function () {
        $scope.searchPipus.search = '';
        $scope.getPipus();
    }
    $scope.$watch('time.start', function (value) {
        if ($scope.setTime && $scope.filterNoProcess) {
            $('#start_time').html(moment(value).format('MM/DD/YYYY'));
            $scope.displayFromDate = {day: moment(value).format('DD'), month: moment(value).format('MMMM')};
            $scope.searchPipus_();
        }
    })
    $scope.$watch('time.end', function (value) {
        if ($scope.setTime && $scope.filterNoProcess) {
            $('#end_time').html(moment(value).format('MM/DD/YYYY'));
            $scope.displayToDate = {day: moment(value).format('DD'), month: moment(value).format('MMMM')};
            $scope.searchPipus_();
        }
    })
    $scope.repalaceres = function () {
        setTimeout(function () {
            $scope.$apply(function (val) {
                if (val) {
                    $('#tablePipus').tableRespondsive({
                        paging: true,
                        pagingArg: {
                            totalRow: 105,
                            rowPerPage: 50,
                            currentPage: 2
                        }
                    });
                    $('#document .tblloader').hide();
                    $('.content .row').show();
                }
            });
        }, 1);
    }
    $scope.getDataFilter = function () {
        // if (!$scope.dataFilterLoaded) {
            Departments.getSelectFilter().success(function (data) {
                $scope.departTitle = $scope.initNode('Department', data);
            // $scope.dataFilterLoaded = true;
        });
        // }
    }
    //$scope.getDataFilter();
    $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.changeCallback = function (node) {
        var __where = _.where(node[0].children, {
            selected: true
        });
        var __filter = new Array();
        for (var i = 0; i < __where.length; i++) {
            __filter = _.union(__filter, _.filter($scope.filterClientdata, function (item) {
                return item.departmentName === __where[i]['label'];
            }));
        }
        return _.intersection($scope.filterClientdata, __filter);
    }
    $scope.getfilterClient = function (style) {
        var _f1 = $scope.changeCallback($scope.departTitle);
        $scope.pipus = $scope.filterData(_f1);

        if (style == 'filter')
            $ionicScrollDelegate.$getByHandle('pipusContent').scrollTop();
        $scope.closeTarget('#popupPunchInOutFilter');
        // $scope.repalaceres();
    }
    $scope.setDueDate = function (index) {
        $timeout(function () {
            $('#taskDueDateAddTask').unbind();
            $('#taskDueDateAddTask').daterangepicker({
                ranges: {
                    'Yesterday': [moment().add(-1, 'days'), moment().add(-1, 'days')],
                    'This Week': [moment().day("Sunday"), moment()],
                    'Last Week': [moment().day("Sunday").subtract(1, 'weeks'), moment().day("Sunday").add(-1, 'days')],
                    'Last 2 Weeks': [moment().day("Sunday").subtract(2, 'weeks'), moment().day("Sunday").add(-1, 'days')],
                }
            }, function (start, end) {
                var time = {
                    start: start.format(conFig.formatDate.toUpperCase()),
                    end: end.format(conFig.formatDate.toUpperCase())
                }
                $('#start_time').val(time.start);
                $('#end_time').val(time.end);
                $scope.getPipus();
            });
        }, 500);
        $scope.setTime = true;
    }
    $scope.export = function () {
        //$('#document .tblloader').show();
        $scope.dataExportPipus.data = angular.copy($scope.pipusForExport);
        $scope.dataExportPipus.userId = '';
        for (var i = 0; i < $scope.dataExportPipus.data.length; i++) {
            $scope.dataExportPipus.data[i].from_hour = moment($scope.dataExportPipus.data[i].from_hour, 'h:mmA').format('HH:mm');
            $scope.dataExportPipus.data[i].to_hour = moment($scope.dataExportPipus.data[i].to_hour, 'h:mmA').format('HH:mm');
        }
        Pipus.exportPipus($scope.dataExportPipus).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                url_site = url_site.replace('/public', '');
                data.link = data.link.replace('./../', '')
                $scope.dataExportPipus = {};
                var options = {
                    location: 'yes',
                    clearcache: 'yes',
                    toolbar: 'yes'
                };
                console.log(url_site + '/' + data.link);
                if (isiOs) {
                    $cordovaInAppBrowser.open(url_site + '/' + data.link, '_blank', options);
                } else {
                    $cordovaInAppBrowser.open(url_site + '/' + data.link, '_system', options);
                }
                // window.location.href = data.link;
            }
            //window.location.href = data;
            //$('#document .tblloader').hide();
        });
    }
    $scope.searchChanged = function () {
        $scope.getPipus();
    }
    /*$scope.getSelectPipus = function(){
     Pipus.getSelect().success(function(data){
     $scope.selectPipus = data;
     });
     }
     $scope.getSelecPipus();*/
    /*
     xem demo upload file tai day:
     http://jsfiddle.net/danialfarid/1m6fn6re/
     $scope.upload = function (file) {
     Upload.upload({
     url: '/todo',
     fields: $scope.todoData,
     file: file
     }).progress(function (evt) {
     var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
     console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
     }).success(function (data, status, headers, config) {
     console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
     }).error(function (data, status, headers, config) {
     console.log('error status: ' + status);
     })
     };
     */
     $scope.sizeChanged = function () {
        $scope.searchPipus.rows = $scope.entryLimit;
        pipus_pagesize.val($scope.searchPipus.rows);
        localStorage.setItem('pipus_pagesize', $scope.searchPipus.rows);
        $scope.searchPipus.current_page = 1;
        $scope.getPipus();
    }
    $scope.pageChanged = function () {
        $scope.searchPipus.current_page = $scope.currentPage;
        $scope.getPipus();
    };
    $scope.setPage = function (pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };
    $scope.addPipusData = {};
    $scope.createPipus = function () {
        Pipus.save($scope.addPipusData).success(function (data) {
            $scope.addPipusData = {};
            $scope.getPipus();
            if (data.status) {
                toastr.success(data.msg);
            } else {
                toastr.error(data.msg);
            }
        });
    }
    $scope.validateForm = function (formValidate, style) {
        if (formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $scope.updatePipus();
    }
    $scope.editPipusData = {};
    $scope.editPipus = function (id) {
        $scope.openByGetTemplate("pipusEdit");
        $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') : '';
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Add Errror!!!');
        })
    }
    $scope.updatePipus = function () {
        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;
        }
        $scope.editPipusData.from_hour = $('#editPipusFromHour').val();
        $scope.editPipusData.to_hour = $('#editPipusToHour').val();
        var id = $scope.editPipusData.id;
        $ionicLoading.show({
            template: templateLoading
        });
        Pipus.update(id, $scope.editPipusData).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.closeTarget('#pipusEdit');
                var idx = _.findLastIndex($scope.filterClientdata, {id: id});
                $scope.filterClientdata[idx].from_hour = moment($scope.editPipusData.from_hour, "h:mmA").format("hh:mmA");
                $scope.filterClientdata[idx].to_hour = $scope.editPipusData.to_hour ? moment($scope.editPipusData.to_hour, "h:mmA").format("hh:mmA") : "";
                var strDuration = "00 hours 00 minutes";
                if ($scope.editPipusData.to_hour) {
                    var times = moment($scope.editPipusData.to_hour, 'hh:mmA').diff(moment($scope.editPipusData.from_hour, 'hh:mmA'), 'minutes');
                    var hours = Math.floor(times / 60);
                    var minutes = times - hours * 60;
                    hours = hours.toString().length == 1 ? "0" + hours.toString() : hours;
                    minutes = minutes.toString().length == 1 ? "0" + minutes.toString() : minutes;
                    strDuration = hours + " hours " + minutes + " minutes ";
                }
                $scope.filterClientdata[idx].duration = strDuration;
                $scope.pipus = $scope.filterData($scope.filterClientdata);
                $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('Add Errror!!!');
        })
    }
    $scope.deletePipusData = {};
    $scope.deletePipusData = {};
    $scope.confrimpipus = function (item) {
        $scope.openByGetTemplate('confirmDeletePunchInOut');
        $scope.deletePipusData = item;
    }
    $scope.deletePipus = function () {
        $ionicLoading.show({
            template: templateLoading
        });
        var id = $scope.deletePipusData.id;
        Pipus.destroy(id).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                var idx = _.findLastIndex($scope.filterClientdata, {
                    id: id
                });
                $scope.filterClientdata.splice(idx, 1);
                $scope.pipus = $scope.filterData($scope.filterClientdata);
                $scope.closeTarget('#confirmDeletePunchInOut');
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Add Errror!!!');
        })
    }
    $scope.getUserLogin = function () {
        return Login.getUserLogin().success(function (data) {
            if (data == false) {
                $scope.displayname = "Profile";
                localStorage.setItem("login_status", "0");
                redirectTo('index.html');
            } else {
                var index = _.findIndex(data.jsondata,{roletree_id:'93'});
                if(data.jsondata[index].check){
                    $scope.editAll = data.jsondata[index].child[1].child[0].check;
                    $scope.editInDepart = data.jsondata[index].child[1].child[1].check;
                    $scope.editBySup = data.jsondata[index].child[1].child[2].check;

                    $scope.deleteAll = data.jsondata[index].child[2].child[0].check;
                    $scope.deleteInDepart = data.jsondata[index].child[2].child[1].check;
                    $scope.deleteBySup = data.jsondata[index].child[2].child[2].check;

                    $scope.imagePath = pathToPublic + data.image_pic;
                    var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
                    if ($.trim(displayname) == "") {
                        $scope.displayname = "Hello, " + data.email;
                    } else {
                        $scope.displayname = "Hello, " + displayname;
                    }
                    $scope.departmentId = data.department_id;
                    $scope.getPipus();
                }else{
                    localStorage.setItem("login_status", "0");
                    redirectTo('index.html');
                }  
            }
        });
    }

    $scope.filterPipus = function(){
        $scope.searchPipus.departmentId = $scope.dataFilterPipus.departmentId;
        $scope.searchPipus.employees = $scope.converArrayToObj();
        $scope.time.start = $scope.dataFilterPipus.start_time;
        $scope.time.end = $scope.dataFilterPipus.end_time;
        $scope.displayFromDate = {day: moment($scope.time.start).format('DD'), month: moment($scope.time.start).format('MMMM')};
        $scope.displayToDate = {day: moment($scope.time.end).format('DD'), month: moment($scope.time.end).format('MMMM')};
        $scope.searchPipus.current_page= 1;
        $scope.filterNoProcess = false;
        $scope.getPipus();
        setTimeout(function() {
            $scope.closeTarget('#popupPunchInOutFilter');
        }, 100);
    }

    $scope.filterClick = function(){
        $scope.dataFilterPipus.departmentId = 'all';
        var _param = {
            rows: 'All'
        }
        if ($scope.allUser.length==0) {
            $scope.allUser = [];
            Pipus.getAllUsers(_param).success(function(data) {
                _.each(data.data, function(val, index) {
                    nick_name = val.first_name + ' ' + val.last_name;
                    var _item = {
                        id: val.id,
                        screen_name: nick_name + ' - ' + val.positiontitles_name,
                        name: nick_name
                    }
                    $scope.allUser.push(_item);
                });
            });
        }
        if ($scope.getDeparment) {
            Departments.getSelectFilter().success(function(data) {
                $scope.allDepartment = data;
                $scope.getDeparment = false;
            });
        }   
    }


    // $scope.getUserLogin();
    $scope.logout = function () {
        return Login.logout().success(function (data) {
            $window.location.href = url_login;
        });
    }
    $scope.checkLogin = function () {
        return Login.checkLogin().success(function (data) {
            if (data.status == false) {
                $window.location.href = url_login;
            } else {
                $scope.getPipus();
            }
        });
    }

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

    $scope.filterEmployeesSearchClicked = function(callback){

    }


    $scope.filterEmployeesSearchRemoved = function(callback){

    }

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


    // $scope.checkLogin();
    // stopTime = $interval($scope.checkLogin, time_refresh);
    // edit by haudao
    var myPopup;
    $scope.openIonicPopup = function (templateUrl, title) {
        myPopup = $ionicPopup.show({
            templateUrl: templateUrl,
            title: title,
            scope: $scope
        });
    }
    $scope.closeIonicPopup = function () {
        myPopup.close();
    }

    $scope.setValueForDepart = function (departId) {
        if(parseInt(departId)>0){
            $scope.departLabel = _.where($scope.allDepartment, {
                id: departId.toString()
            })[0].name;
        }
        else{
            $scope.departLabel = 'All';
        }
        
    }


    $scope.setViewMode = function(type,departId,supId,userId){
        if(type == 'edit'){
            return $scope.checkViewAction(departId,supId,userId,$scope.editAll,$scope.editInDepart,$scope.editBySup);
        }else{
            return $scope.checkViewAction(departId,supId,userId,$scope.deleteAll,$scope.deleteInDepart,$scope.deleteBySup);
        }
    }

    $scope.checkViewAction = function(departId,supId,userId,allAction,inderPart,bySup){
        $access = true;
        if(allAction){
            $access = true;
        }else{
            if(inderPart){
                if(parseInt(userId) != parseInt($scope.currentIdLogin)){
                    if($scope.departmentId != departId){
                        if(bySup){
                            if(parseInt(supId) != parseInt($scope.currentIdLogin)){
                                $access = false;
                            }
                        }
                        else{
                            $access = false;
                        }
                    }
                }
                else{
                    $access = false;
                }     
            }
            else{
                if(bySup){
                    if(parseInt(supId) != parseInt($scope.currentIdLogin)){
                        $access = false;
                    }
                }
                else{
                    $access = false;
                }
            }
        }
        return $access;
    }


    if (page == "pipus.html")
        $scope.renderTemplateData();
    // end edit
})
