'use strict'

angular.module('689Cloud', [
    'ngRoute', // Route
    'ngSanitize',
    'ui.router',
    // Animate
    'jm.i18next', // I18n
    'oc.lazyLoad', // ocLazy
    'session', // Session management
    'filters', // File size and more
    'ui.bootstrap', // UI bootstrap
    'ui.select', // UI select
    'utils', // Utilities
    'NotificationService',
    // 'vjs.video'
])

    // Config ocLazy loading
    .config([
        '$ocLazyLoadProvider',
        '$injector',
        function ($ocLazyLoadProvider, $injector) {

            var app = $injector.get('app')
            var modules = [
                //-------------------------AUTHORIZED-----------------------
                {
                    name: 'authorized',
                    files: [
                        'js/components/authorized/authorized.css',
                        'js/components/authorized/authorized-ctrl.js',
                    ],
                },
                {
                    name: 'unauthorized',
                    files: [
                        'js/components/authorized/authorized.css',
                    ],
                },
                // Download file
                {
                    name: 'download',
                    files: [
                        'js/components/download/download-file.js',
                    ],
                },
                //-------------------------ACCOUNT--------------------------
                // account
                {
                    name: 'userChangePasswordModule',
                    files: [
                        'js/aes256/AESUtil.js',
                        'js/aes256/aes.js',
                        'js/aes256/pbkdf2.js',
                        'js/components/account/password/change-password-ctrl.js',
                    ],
                },
                {
                    name: 'userChangeEmailModule',
                    files: [
                        'js/components/account/email/change-email-ctrl.js',
                    ],
                },
                {
                    name: 'userProfileModule',
                    files: [
                        'js/components/account/profile/user-profile-ctrl.js',
                    ],
                },
                //-------------------------TEAM-----------------------------
                {
                    name: 'teamListModule',
                    files: [
                        'js/components/team/list/team-list-ctrl.js',
                    ],
                },
                {
                    name: 'createTeamModule',
                    files: [
                        'js/components/import_user/list-email-modal.js',
                        'js/components/import_user/list-email-modal.css',
                        'css/custom/style.css',
                        'js/components/import_user/error-modal.js',
                        'js/common/directives/uploader/uploader-directive-css.css',
                        'js/components/team/create/create-team-ctrl.js',
                        'js/aes256/AESUtil.js',
                        'js/aes256/aes.js',
                        'js/aes256/pbkdf2.js',
                    ],
                },
                {
                    name: 'teamProfileModule',
                    files: [
                        'js/aes256/AESUtil.js',
                        'js/aes256/aes.js',
                        'js/aes256/pbkdf2.js',
                        'css/dev/shorter_text.css',
                        'js/components/team/profile/team-profile-ctrl.js',
                        'js/components/admin/password/change-team-password-ctrl.js',
                        'js/components/admin/email/change-team-email-ctrl.js',
                        'js/components/share/history-detail/history.css',
                        'js/components/share/history-detail/history-detail-ctrl.js',
                    ],
                },
                //-------------------------USAGE PACKAGE---------------------
                {
                    name: 'usagePackageModule',
                    files: [
                        'js/components/usage_package/list/usage-package-ctrl.js',
                        'js/components/usage_package/list/usage-package.css',
                    ],
                },
                //-------------------------TEAM MEMBER-----------------------
                {
                    name: 'createTeamMemberModule',
                    files: [
                        'js/components/import_user/error-modal.js',
                        'js/common/directives/uploader/uploader-directive-css.css',
                        'js/aes256/AESUtil.js',
                        'js/aes256/aes.js',
                        'js/aes256/pbkdf2.js',
                        'js/components/member/create/create-team-member-ctrl.js',
                        'js/components/invite/select_group_user_modal.js',
                    ],
                },
                {
                    name: 'memberProfileModule',
                    files: [
                        'js/aes256/AESUtil.js',
                        'js/aes256/aes.js',
                        'js/aes256/pbkdf2.js',
                        'js/components/member/profile/member-profile-ctrl.js',
                        'js/components/admin/password/change-member-password-ctrl.js',
                        'js/components/admin/email/change-member-email-ctrl.js',
                    ],
                },
                //-------------------------COMPANY---------------------------
                {
                    name: 'companyListModule',
                    files: [
                        'css/dev/shorter_text.css',
                        'js/components/company/list/company-list-ctrl.js',
                    ],
                },
                {
                    name: 'companyCreateModule',
                    files: [
                        'js/components/company/create/create-company-ctrl.js',
                        'js/aes256/AESUtil.js',
                        'js/aes256/aes.js',
                        'js/aes256/pbkdf2.js',
                    ],
                },
                {
                    name: 'companyProfileModule',
                    files: [
                        'css/dev/shorter_text.css',
                        'js/components/company/profile/company-profile-ctrl.js',
                    ],
                },
                {
                    name: 'changeCompanyPasswordModule',
                    files: [
                        'js/components/admin/password/change-company-password-ctrl.js',
                        'js/aes256/AESUtil.js',
                        'js/aes256/aes.js',
                        'js/aes256/pbkdf2.js',
                    ],
                },
                //-------------------------LOGIN------------------------------
                {
                    name: 'adminLoginModule',
                    files: [
                        'js/aes256/AESUtil.js',
                        'js/aes256/aes.js',
                        'js/aes256/pbkdf2.js',
                        'js/components/login/admin-login-ctrl.js',
                    ],
                },
                //-------------------------DASHBOARD--------------------------
                // Company's dashboard
                {
                    name: 'dashboardModule',
                    files: [
                        'js/components/dashboard/sb-admin-2.css',
                        'js/components/dashboard/timeline.css',
                        'bower_components/metisMenu/dist/metisMenu.min.css',

                        'js/components/dashboard/reseller/dashboard-ctrl.js',
                    ],
                },
                // SuperAdmin's dashboard
                {
                    name: 'adminDashboardModule',
                    files: [
                        // CSS
                        'js/components/dashboard/sb-admin-2.css',
                        'js/components/dashboard/timeline.css',
                        'bower_components/metisMenu/dist/metisMenu.min.css',
                        // JS
                        'js/components/dashboard/admin/admin-dashboard-ctrl.js',
                    ],
                },
            ]

            // Read config value
            if (angular.isDefined(app.OCLAZY_CACHE_MODULE)) {

                angular.forEach(modules, function (v) {

                    v.cache = app.OCLAZY_CACHE_MODULE
                })
            }

            // We define some files for a specific module
            $ocLazyLoadProvider.config({
                // Debug mode
                // debug: true,
                // events: true,
                modules: modules,
            })
        }])

    // Config route for app
    // We are now using $ocLazyload module
    // Refer to  ocLazy config to see the files for each module
    .config([
        '$stateProvider',
        '$injector',
        '$urlRouterProvider',
        function ($stateProvider, $injector, $urlRouterProvider) {

            var app = $injector.get('app')
            var redirectPath = '/admin/login'
            $urlRouterProvider.otherwise(redirectPath)

            $stateProvider
                //-------------------------AUTHORIZED-----------------------
                .state({
                    name: 'authorized',
                    abstract: true,
                    templateUrl: 'js/components/authorized/authorized-tmpl.html',
                    controller: 'UserCtrl as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('authorized')
                            }],
                        authen: [
                            '$q', 'session', function ($q, session) {
                                // Get token from cookie store
                                var cToken = $.cookie('t')

                                var deferred = $q.defer()
                                // Private route
                                if (cToken || session.isEnableCookieSession()) {
                                    // Get user info with this token
                                    session.getUserInfo(function (data) {
                                        // Check whether language is the same or not
                                        // Set lang
                                        session.changeLanguage(data.lang)
                                            .then(function () {
                                                deferred.resolve(data)
                                            })
                                    }, function () {
                                        // Invalid token
                                        deferred.reject('Unauthorized')
                                    })
                                } else {
                                    // preLoginPath = window.location.href;
                                    // Reset user info in case of token is expired
                                    session.reset()
                                    // Require authen - Redirect to login page
                                    session.authenticationRequiredHandler()
                                    // Reject this route
                                    deferred.reject('Unauthorized')
                                }
                                return deferred.promise
                            }],
                    },
                })
                .state({
                    name: 'unauthorized',
                    abstract: true,
                    templateUrl: 'js/components/authorized/unauthorized-tmpl.html',
                    controller: [
                        '$scope',
                        'session',
                        '$rootScope',
                        function ($scope, session, $rootScope) {
                            // TODO
                        }],
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('unauthorized')
                            }],
                        authen: [
                            '$q', 'session', function ($q, session) {
                                // Get token from cookie store
                                var cToken = $.cookie('t')
                                var deferred = $q.defer()
                                // Private route
                                if (cToken || session.isEnableCookieSession()) {
                                    // Get user info with this token
                                    session.getUserInfo(function (data) {
                                        // Check whether language is the same or not
                                        // Set lang
                                        session.changeLanguage(data.lang)
                                            .then(function () {
                                                deferred.resolve(data)
                                            })
                                    }, function () {
                                        // Invalid token
                                        deferred.reject('Unauthorized')
                                    })
                                } else {
                                    // preLoginPath = window.location.href;
                                    // Reset user info in case of token is expired
                                    session.reset()
                                    // Reject this route
                                    deferred.reject('Unauthorized')
                                }
                            }],
                    },
                })
                .state({
                    name: 'browserNotSupported',
                    url: '/browser-not-supported',
                    parent: 'unauthorized',
                    templateUrl: '../templates/browser_not_support.html',
                    controller: [
                        '$scope', function ($scope) {
                            // TODO
                        }],
                })
                //-------------------------ACCOUNT--------------------------
                .state({
                    name: 'changeEmail',
                    url: '/change-email/:confirm_code',
                    parent: 'unauthorized',
                    title: 'page_title.change_email',
                    templateUrl: 'js/components/account/email/change-email-tmpl.html',
                    autoRedirect: false, // Using when token existing
                    controller: 'ChangeEmailCtrl as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('userChangeEmailModule')
                            }],
                    },
                })
                .state({
                    name: 'userProfile',
                    url: '/profile',
                    parent: 'authorized',
                    title: 'page_title.user_profile',
                    templateUrl: 'js/components/account/profile/user-profile-tmpl.html',
                    controller: 'UserProfile as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('userProfileModule')
                            }],
                    },
                })
                .state({
                    name: 'userChangePass',
                    url: '/profile/change-password',
                    parent: 'authorized',
                    title: 'page_title.change_password',
                    templateUrl: 'js/components/account/password/change-password-tmpl.html',
                    controller: 'UserChangePassword as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('userChangePasswordModule')
                            }],
                    },
                })
                //-------------------------TEAM-----------------------------
                .state({
                    name: 'teamList',
                    url: '/admin/team-list',
                    parent: 'authorized',
                    menu: 5,
                    title: 'page_title.team_list',
                    templateUrl: 'js/components/team/list/team-list-tmpl.html',
                    controller: 'TeamList as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('teamListModule')
                            }],
                    },
                })
                .state({
                    name: 'teamCreate',
                    url: '/admin/create-team',
                    parent: 'authorized',
                    menu: 5,
                    title: 'page_title.create_new_team',
                    templateUrl: 'js/components/team/create/create-team-tmpl.html',
                    controller: 'CreateTeamCtrl as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('createTeamModule')
                            }],
                    },
                })
                .state({
                    name: 'adminChangeEmailTeam',
                    url: '/admin/change-email/:company_id/:id',
                    parent: 'authorized',
                    menu: 5,
                    title: 'page_title.team_profile_change_email',
                    templateUrl: 'js/components/admin/email/change-email-tmpl.html',
                    controller: 'ChangeEmailTeamCtrl as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('teamProfileModule')
                            }],
                    },
                })
                .state({
                    name: 'adminChangePasswordTeam',
                    url: '/admin/change-password/:company_id/:team_id',
                    parent: 'authorized',
                    menu: 5,
                    title: 'page_title.team_profile_change_password',
                    templateUrl: 'js/components/admin/password/change-password-tmpl.html',
                    controller: 'AdminChangePassword as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('teamProfileModule')
                            }],
                    },
                })
                .state({
                    name: 'adminTeamProfile',
                    url: '/admin/admin-team-profile/:company_id/:id',
                    parent: 'authorized',
                    menu: 5,
                    title: 'page_title.team_profile',
                    templateUrl: 'js/components/team/profile/team-profile-tmpl.html',
                    controller: 'AdminTeamProfile as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('teamProfileModule')
                            }],
                    },
                })
                .state({
                    name: 'teamCreateBySuperAdmin',
                    url: '/super-admin/company/:id/create-team',
                    parent: 'authorized',
                    menu: 7,
                    title: 'page_title.company_create_team',
                    templateUrl: 'js/components/team/create/create-team-tmpl.html',
                    controller: 'CreateTeamCtrl as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('createTeamModule')
                            }],
                    },
                })
                //-------------------------USAGE PACKAGE---------------------
                .state({
                    name: 'usagePackage',
                    url: '/admin/usage-package',
                    parent: 'authorized',
                    menu: 9,
                    title: 'page_title.usage_package',
                    templateUrl: 'js/components/usage_package/list/usage-package-tmpl.html',
                    controller: 'UsagePackageController as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('usagePackageModule')
                            }],
                    },
                })
                //-------------------------TEAM MEMBER-----------------------
                .state({
                    name: 'createTeamMember',
                    url: '/admin/create-team-member/:company_id/:team_id',
                    parent: 'authorized',
                    menu: 5,
                    title: 'page_title.create_team_member',
                    templateUrl: 'js/components/member/create/create-team-member-tmpl.html',
                    controller: 'CreateTeamMember as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('createTeamMemberModule')
                            }],
                    },
                })
                .state({
                    name: 'memberProfile',
                    url: '/admin/member-profile/:company_id/:team_id/:id',
                    parent: 'authorized',
                    menu: 5,
                    title: 'page_title.member_profile',
                    templateUrl: 'js/components/member/profile/member-profile-tmpl.html',
                    controller: 'MemberProfile as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('memberProfileModule')
                            }],
                    },
                })
                .state({
                    name: 'adminChangeEmailMember',
                    url: '/admin/change-member-email/:company_id/:team_id/:id',
                    parent: 'authorized',
                    menu: 5,
                    title: 'page_title.member_profile_change_email',
                    templateUrl: 'js/components/admin/email/change-email-tmpl.html',
                    controller: 'ChangeEmailMemberCtrl as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('memberProfileModule')
                            }],
                    },
                })
                .state({
                    name: 'adminChangePasswordMember',
                    url: '/admin/change-member-password/:company_id/:team_id/:id',
                    parent: 'authorized',
                    menu: 5,
                    title: 'page_title.member_profile_change_password',
                    templateUrl: 'js/components/admin/password/change-password-tmpl.html',
                    controller: 'AdminChangePasswordMember as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('memberProfileModule')
                            }],
                    },
                })
                //-------------------------COMPANY---------------------------
                .state({
                    name: 'companyList',
                    url: '/super-admin/company-list',
                    parent: 'authorized',
                    menu: 7,
                    title: 'page_title.company_list',
                    templateUrl: 'js/components/company/list/company-list-tmpl.html',
                    controller: 'CompanyList as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('companyListModule')
                            }],
                    },
                })
                .state({
                    name: 'companyCreate',
                    url: '/super-admin/create-company',
                    parent: 'authorized',
                    menu: 7,
                    title: 'page_title.create_new_company',
                    templateUrl: 'js/components/company/create/create-company-tmpl.html',
                    controller: 'CreateCompanyController as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('companyCreateModule')
                            }],
                    },
                })
                .state({
                    name: 'companyProfile',
                    url: '/super-admin/company-profile/:id',
                    parent: 'authorized',
                    menu: 7,
                    title: 'page_title.company_profile',
                    templateUrl: 'js/components/company/profile/company-profile-tmpl.html',
                    controller: 'CompanyProfileController as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('companyProfileModule')
                            }],
                    },
                })
                .state({
                    name: 'changeCompanyPassword',
                    url: '/super-admin/change-company-password/:id',
                    parent: 'authorized',
                    menu: 7,
                    title: 'page_title.company_profile_change_password',
                    templateUrl: 'js/components/admin/password/change-company-password-tmpl.html',
                    controller: 'ChangeCompanyPasswordCtrl as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('changeCompanyPasswordModule')
                            }],
                    },
                })
                //-------------------------LOGIN------------------------------
                .state({
                    name: 'adminLogin',
                    url: '/admin/login',
                    parent: 'unauthorized',
                    title: 'page_title.admin_login',
                    templateUrl: 'js/components/login/admin-login-html.html',
                    autoRedirect: true, // Using when token existing
                    controller: 'AdminLoginCtrl as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('adminLoginModule')
                            }],
                    },
                })
                //-------------------------DASHBOARD--------------------------
                // SuperAdmin's dashboard
                .state({
                    name: 'adminDashboard',
                    url: '/super-admin/dashboard',
                    parent: 'authorized',
                    menu: 8,
                    title: 'page_title.dashboard',
                    templateUrl: 'js/components/dashboard/admin/admin-dashboard-tmpl.html',
                    controller: 'adminDashboardCtrl as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('adminDashboardModule')
                            }],
                    },
                })
                // Company's dashboard
                .state({
                    name: 'dashboard',
                    url: '/admin/dashboard',
                    parent: 'authorized',
                    menu: 6,
                    title: 'page_title.dashboard',
                    templateUrl: 'js/components/dashboard/reseller/dashboard-tmpl.html',
                    controller: 'dashboardController as Ctrl',
                    resolve: {
                        loadModule: [
                            '$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('dashboardModule')
                            }],
                    },
                })
        }])

    // Config request
    // Set up interceptor
    .config([
        '$httpProvider', function ($httpProvider) {

            $httpProvider.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'

            // Auth interceptor
            $httpProvider.interceptors.push(
                function ($q, $injector, $rootScope) {

                    // Note:
                    // We config $http so that if we inject service that is using $http it will lead to circle deps
                    var $ = $injector.get('$'),
                        noty = $injector.get('noty'),
                        _ = $injector.get('_'),
                        $i18next = $injector.get('$i18next'),
                        error = $injector.get('error')

                    var apis = $injector.get('APIName')

                    return {

                        request: function (config) {
                            // We get token from $injector
                            var token = $.cookie('t')
                            if (token && !config.headers['auth-token'] &&
                                config.url.indexOf('googleapis') === -1)
                                config.headers['auth-token'] = token
                            return config
                        },

                        response: function (response) {
                            if (response.headers()['content-type'] ===
                                'application/json;charset=UTF-8') {
                                // Get status code
                                var status = response.data.status

                                var url = response.config.url

                                // Verify request
                                var api = _.find(apis, {
                                    'name': url,
                                    'method': response.config.method,
                                })
                                // function (api) {
                                //   if(api.method) {
                                //       return api.name === url && api.method === response.config.method
                                //   }
                                // }
                                // Success message
                                if (status === 200) {

                                    if (api &&
                                        api.hasOwnProperty('success_msg')) {

                                        noty({
                                            text: $i18next(api['success_msg']),
                                            type: 'success',
                                            theme: 'bootstrapTheme',
                                            layout: 'topCenter',
                                            timeout: 3000,
                                        })
                                    }
                                } else {
                                    // Check api allows to show message
                                    if (api &&
                                        (!api.hasOwnProperty('show_error') ||
                                            api['show_error'] === true)) {

                                        // Clean error or not
                                        var path = 'sever_errors.' + status

                                        // System error
                                        noty({
                                            text: $i18next(path),
                                            type: 'error',
                                            theme: 'bootstrapTheme',
                                            layout: 'topCenter',
                                            timeout: 3000,
                                        })
                                    }

                                    if (status === 401) {
                                        // Broadcast this event
                                        $rootScope.$broadcast('$cleanSession')
                                    } else if (status === 404) {
                                        // Handle 404 common error
                                        // Define Callback here
                                    }
                                }
                            }

                            return response || $q.when(response)
                        },

                        responseError: function (rejection) {
                            // Get status code
                            var status = rejection.status || 0

                            var url = rejection.config
                                ? rejection.config.url
                                : ''

                            // Verify request
                            var api = _.find(apis, {'name': url})
                            // Check api allows to show message
                            if (api && (!api.hasOwnProperty('show_error') ||
                                api['show_error'] === true)) {

                                // Clean error or not
                                var path = 'sever_errors.' + status

                                // System error
                                noty({
                                    text: $i18next(path),
                                    type: 'error',
                                    theme: 'bootstrapTheme',
                                    layout: 'topCenter',
                                    timeout: 3000,
                                })
                            }

                            return rejection || $q.reject(rejection)
                        },
                    }
                })
        }]).config([
    'uiSelectConfig', function (uiSelectConfig) {
        uiSelectConfig.appendToBody = true
    }])

    //where we will store the attempted url
    .value('redirectToUrlAfterLogin', {url: '/'})

    // Init HoGo app
    .run([
        '$rootScope',
        'session',
        'logo',
        'util',
        'plupload',
        'app',
        '$state',
        '$transitions',
        function (
            $rootScope, session, logo, util, plupload, app, $state,
            $transitions) {

            validateBrowser()

            // Start loading
            var siteTile = logo.TITLE

            // Init
            session.init()

            // Lang is ready
            $rootScope.$on('i18nextLanguageChange', function (t, v) {
                // Init lang validation
                $rootScope.lang = v

            })

            $transitions.onSuccess({}, function (trans) {
                var current = $state.current
                // We have to set title for every page
                var pageTitle = current.title
                // // Title of page
                $rootScope.title = (pageTitle !== undefined) ? util.translate(
                    pageTitle) + ' - ' + siteTile : siteTile
                // we can handle fix content here
                $rootScope.menu = current.menu
                // Route public or not
                $rootScope.public = (current.public) || false
                // Class is added to body tag
                $rootScope.bodyClass = current.$$state && current.bodyClass
                if (current.autoRedirect) {
                    session.authenticationSuccessHandler()
                }
                // scroll top page
                window.scrollTo(0, 0)
            })

            // Unauthorized event handler
            // This event is fired on $http interceptor
            // We can't inject the session because session is now using the interceptor
            $rootScope.$on('$cleanSession', function () {

                session.reset()
                session.authenticationRequiredHandler()
            })

            // Handle when user info change in profile
            $rootScope.$on('$userInfoHasChanged', function (event, user) {
                changeLanguages(user)
            })

            function changeLanguages(user) {
                var current = session.getUser()

                // Check whether language is the same or not
                // Dont put this compare in the changeLanguage method because
                // Maybe we make a mistake such as set user info first, so that it always equals
                if (current.lang !== user.lang) {

                    // Do change language
                    session.changeLanguage(user.lang)
                }
                // Set as new info
                session.setUser(user)
                // window.location.reload(true);
            }

            $transitions.onStart({}, function (trans) {
                validateBrowser()
            })

            $transitions.onError({}, function (trans) {
                // I think we should init all control that we have
                console.log("trans",trans)
                if (trans._error && trans._error.type === 6) {
                    console.log("here")
                    session.authenticationRequiredHandler()
                }
            })

            // Catch event change title
            $rootScope.$on('changeTitle', function (event, t) {
                t && ($rootScope.title = t + ' - ' + siteTile)
            })

            function validateBrowser() {
                var isIE9OrBelow = /MSIE\s/.test(navigator.userAgent) &&
                    parseFloat(navigator.appVersion.split('MSIE')[1]) < 10
                if (isIE9OrBelow) {
                    $state.go('browserNotSupported')
                }
            }
        }])
// Set fallback lang will be loaded
// Config i18next localize
let config1 = angular.module('jm.i18next').config([
    '$i18nextProvider', function ($i18nextProvider) {
        var lang = window.navigator.browserLanguage ||
            window.navigator.language // Language code: http://4umi.com/web/html/languagecodes.php || http://msdn.microsoft.com/en-us/library/ie/ms533052.aspx
        var language = lang.substr(0, 2)
        if (typeof language === 'undefined')
            language = 'en'// set as default

        $i18nextProvider.options = {
            lng: language,
            // selectorAttr: 'data-hg',
            fallbackLng: ['en'], // fallback
            resGetPath: 'i18n/app.' + language + '.json',
            debug: true,
            getAsync: true,
            // preload: ['en', 'ja'], // ['en', 'ja'],
            defaultLoadingValue: 'Loading',
        }
    }])
