// if (!app) {
//     var app = angular.module('App', [
//         //'ui.bootstrap',
//         'LoginService', 'appointmentgroupsService', 'appointmentgroupsCtrl', 'appointmentgroupsEditDirective', 'appointmentgroupsDeleteDirective', 'appointmentgroupsDirective', 'appointmentgroupsAddDirective', 'navDirective', 'ngFileUpload', 'ckDirective', 'datetimepicker', 'modalDirective', 'colorpickerDirective', 'departmentsService'
//         //'ngSanitize',
//         //'expDirective',// remove comment if use file explorer.
//         //'explorerDirective',
//         //'ui.select'
//     ]).config(['datetimepickerProvider',
//         function(datetimepickerProvider) {
//             datetimepickerProvider.setOptions({
//                 locale: 'en'
//             });
//         }
//     ]).run(['$rootScope',
//         function($rootScope) {
//             $rootScope.scoped = {
//                 format: 'HH:mm:ss'
//             };
//             $rootScope.vm = {
//                 datetime: '05/13/2011 6:30 AM'
//             }
//         }
//     ]);
// }
var appointmentgroups_pagesize = $('#appointmentgroups_pagesize');
angular.module('appointmentgroupsCtrl', []).controller('appointmentgroupsController', function($cordovaToast, $ionicPopup, $ionicLoading, $scope,
    $http, $window, $interval, Login, Appointmentgroups, Departments,$ionicScrollDelegate) {
    withoutPopup_AG = $scope;
    $scope.currentPage = 1;
    var pager = localStorage.getItem('appointmentgroups_pagesize');
    $scope.itemsPerPage = pager ? pager : 200;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchAppointmentgroups = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: "",
        show_all: false
    };
    /*$scope.getUsers = function(){
        User.get().success(function(data){
            $scope.users= data;
        });
    }
    $scope.getUsers();
    */
    $scope.getAppointmentgroups = function() {
        $ionicLoading.show({ template: templateLoading });
        Appointmentgroups.getPaging($scope.searchAppointmentgroups).success(function(data) {
            $scope.appointmentgroups = data.data;
            $scope.currentPage = data.page;
            $scope.itemsPerPage = $scope.searchAppointmentgroups.rows;
            appointmentgroups_pagesize.val($scope.itemsPerPage);
            $scope.totalItems = data.total_rows;
            $ionicLoading.hide();
            Login.checkLogin().success(function(data) {
                    $scope.getSelectDepartments();
                })
                //$scope.setColorPiker();
        });
    };

    // $scope.setColorPiker = function(){
    //     $("#addappgroupcolor").spectrum({
    //         color: "#ffffff",
    //         showInput: true,
    //         preferredFormat: "hex",
    //         change: function(color) {
    //             $scope.addAppointmentgroupsData.color = color.toHexString();
    //         }
    //     });
    // }
    $scope.inputChangeColor = function(color, type) {
        if (type == 'add') {
            $("#addappgroupcolor").spectrum("set", color);
        } else {
            $("#editappgroupcolor").spectrum("set", color);
        }
    }
    $scope.getSelectDepartments = function() {
        Departments.getSelect().success(function(data) {
            $scope.selectDepartments = data;
        });
    }
    $scope.searchChanged = function() {
        $scope.getAppointmentgroups();
    }
    $scope.ShowActive_AG = function(show_all) {
            $scope.searchAppointmentgroups.show_all = show_all;
            $scope.getAppointmentgroups();
        }
        /*$scope.getSelectAppointmentgroups = function(){
            Appointmentgroups.getSelect().success(function(data){
                $scope.selectAppointmentgroups = data;
            });
        }
        $scope.getSelecAppointmentgroups();
        /*
        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.searchAppointmentgroups.rows = $scope.entryLimit;
        appointmentgroups_pagesize.val($scope.searchAppointmentgroups.rows);
        localStorage.setItem('appointmentgroups_pagesize', $scope.searchAppointmentgroups.rows);
        $scope.searchAppointmentgroups.current_page = 1;
        $scope.getAppointmentgroups();
    }
    $scope.pageChanged = function() {
        console.log($scope.currentPage);
        $scope.searchAppointmentgroups.current_page = $scope.currentPage;
        $scope.getAppointmentgroups();
    };
    //$scope.getAppointmentgroups();
    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };
    $scope.addAppointmentgroupsData = {};
    $scope.createAppointmentgroups = function(formValidate) {
        if (formValidate.$invalid || !$scope.addAppointmentgroupsData.color) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Appointmentgroups.save($scope.addAppointmentgroupsData).success(function(data) {
            $scope.getAppointmentgroups();
            if (data.status) {
                closeTarget('#settingApptGroupManagementAdd')
                document.getElementById('formAddApptGroup').reset();
                $scope.addAppointmentgroupsData = {};
                $scope.Input_value = {};
                $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.editAppointmentgroupsData = {};
    $scope.editAppointmentgroups = function(id) {
        Appointmentgroups.show(id).success(function(data) {
            $scope.editAppointmentgroupsData = data;
            $scope.setValueForDepartment(data.department_id);
            $("#editappgroupcolor").spectrum("set", $scope.editAppointmentgroupsData.color);
        }).error(function (data, status, headers, config) {
                    $ionicLoading.hide();
                    console.log('error status: ' + status);
                    $cordovaToast.showLongTop('Connection Error!!!');
                });
    }
    $scope.updateAppointmentgroups = function(formValidate) {
        if (formValidate.$invalid || !$scope.editAppointmentgroupsData.color) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        var id = $scope.editAppointmentgroupsData.id;
        Appointmentgroups.update(id, $scope.editAppointmentgroupsData).success(function(data) {
            $scope.getAppointmentgroups();
             closeTarget('#settingApptGroupManagementEdit');
            if (data.status) {
                $scope.editAppointmentgroupsData = {};
                $scope.Input_value = {};
                $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.deleteAppointmentgroupsData = {};
    $scope.confrimAppointmentgroups = function(item) {
        $scope.deleteAppointmentgroupsData = item;
    }
    $scope.DeleteApptGroup = function() {
        var id=$scope.deleteAppointmentgroupsData.id;
        var status=$scope.deleteAppointmentgroupsData.status;
        $ionicLoading.show({
            template: templateLoading
        });
        Appointmentgroups.destroy(id, status).success(function(data) {
            $ionicLoading.hide();
            closeTarget('#settingApptGroupManagementDelete');
            var idx = _.findLastIndex($scope.appointmentgroups, { id: id.toString() });
            if (data.status) {
                if ($scope.searchAppointmentgroups.show_all) {
                    $scope.appointmentgroups[idx].status = status == "1" ? "0" : "1";
                } else {
                    $scope.appointmentgroups.splice(idx, 1);
                }
                $ionicScrollDelegate.$getByHandle('scrollAppointmentgroups').resize()
                $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.getUserLogin = function() {
        return Login.getUserLogin().success(function(data) {
            if (data == false) {
                localStorage.setItem("login_status", "0");
                redirectTo('index.html');
            } else {
                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.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.getUserLogin();
            }
        });
    }
    if ((window.location.pathname).substring((window.location.pathname).lastIndexOf('/') + 1) == 'appointmentgroups.html') {
        $scope.limitLoad = true;
        $scope.$on('$includeContentLoaded', function() {
            if ($scope.limitLoad) {
                $scope.getUserLogin();
                $scope.limitLoad = false;
                stopTime = $interval($scope.checkLogin, time_refresh);
            }
        });
    }
    // edit by haudao
    $scope.Input_value = {};
    $scope.setValueForDepartment = function(id) {
        $scope.Input_value.department = "";
        var index = _.findLastIndex($scope.selectDepartments, {
            id: id
        });
        if (index >= 0) $scope.Input_value.department = $scope.selectDepartments[index].name;
    }
    $scope.infoApptGroup = {};
    $scope.openPopupApptGroupOption = function(id, status) {
            $scope.infoApptGroup.id = parseInt(id);
            $scope.infoApptGroup.status = status;
            $scope.editAppointmentgroups(id);
            appDialogToggle('open', '#popupSettingApptGroupOption')
        }
        // end edit
})
