/* Minification failed. Returning unminified contents.
(1,9): run-time error CSS1031: Expected selector, found '='
(1,9): run-time error CSS1025: Expected comma or open brace, found '='
(15,12): run-time error CSS1031: Expected selector, found '='
(15,12): run-time error CSS1025: Expected comma or open brace, found '='
(25,4): run-time error CSS1031: Expected selector, found '('
(25,4): run-time error CSS1025: Expected comma or open brace, found '('
(33,16): run-time error CSS1031: Expected selector, found '='
(33,16): run-time error CSS1025: Expected comma or open brace, found '='
(34,5): run-time error CSS1030: Expected identifier, found 'value('
(34,5): run-time error CSS1031: Expected selector, found 'value('
(34,5): run-time error CSS1025: Expected comma or open brace, found 'value('
(36,5): run-time error CSS1030: Expected identifier, found 'value('
(36,5): run-time error CSS1031: Expected selector, found 'value('
(36,5): run-time error CSS1025: Expected comma or open brace, found 'value('
(38,5): run-time error CSS1030: Expected identifier, found 'value('
(38,5): run-time error CSS1031: Expected selector, found 'value('
(38,5): run-time error CSS1025: Expected comma or open brace, found 'value('
(39,5): run-time error CSS1030: Expected identifier, found 'value('
(39,5): run-time error CSS1031: Expected selector, found 'value('
(39,5): run-time error CSS1025: Expected comma or open brace, found 'value('
(41,5): run-time error CSS1030: Expected identifier, found 'config('
(41,5): run-time error CSS1031: Expected selector, found 'config('
(41,5): run-time error CSS1025: Expected comma or open brace, found 'config('
(485,2): run-time error CSS1019: Unexpected token, found ')'
(487,5): run-time error CSS1030: Expected identifier, found 'run('
(487,5): run-time error CSS1031: Expected selector, found 'run('
(487,5): run-time error CSS1025: Expected comma or open brace, found 'run('
(505,2): run-time error CSS1019: Unexpected token, found ')'
(508,5): run-time error CSS1030: Expected identifier, found 'directive('
(508,5): run-time error CSS1031: Expected selector, found 'directive('
(508,5): run-time error CSS1025: Expected comma or open brace, found 'directive('
(527,2): run-time error CSS1019: Unexpected token, found ')'
(528,5): run-time error CSS1030: Expected identifier, found 'filter('
(528,5): run-time error CSS1031: Expected selector, found 'filter('
(528,5): run-time error CSS1025: Expected comma or open brace, found 'filter('
(533,2): run-time error CSS1019: Unexpected token, found ')'
(534,5): run-time error CSS1030: Expected identifier, found 'directive('
(534,5): run-time error CSS1031: Expected selector, found 'directive('
(534,5): run-time error CSS1025: Expected comma or open brace, found 'directive('
(629,2): run-time error CSS1019: Unexpected token, found ')'
(630,5): run-time error CSS1030: Expected identifier, found 'directive('
(630,5): run-time error CSS1031: Expected selector, found 'directive('
(630,5): run-time error CSS1025: Expected comma or open brace, found 'directive('
(652,2): run-time error CSS1019: Unexpected token, found ')'
(653,5): run-time error CSS1030: Expected identifier, found 'directive('
(653,5): run-time error CSS1031: Expected selector, found 'directive('
(653,5): run-time error CSS1025: Expected comma or open brace, found 'directive('
(665,2): run-time error CSS1019: Unexpected token, found ')'
(666,5): run-time error CSS1030: Expected identifier, found 'filter('
(666,5): run-time error CSS1031: Expected selector, found 'filter('
(666,5): run-time error CSS1025: Expected comma or open brace, found 'filter('
(674,2): run-time error CSS1019: Unexpected token, found ')'
(676,21): run-time error CSS1031: Expected selector, found '='
(676,21): run-time error CSS1025: Expected comma or open brace, found '='
(678,17): run-time error CSS1030: Expected identifier, found 'directive('
(678,17): run-time error CSS1031: Expected selector, found 'directive('
(678,17): run-time error CSS1025: Expected comma or open brace, found 'directive('
(969,5): run-time error CSS1030: Expected identifier, found 'service('
(969,5): run-time error CSS1031: Expected selector, found 'service('
(969,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1085,2): run-time error CSS1019: Unexpected token, found ')'
(1086,5): run-time error CSS1030: Expected identifier, found 'service('
(1086,5): run-time error CSS1031: Expected selector, found 'service('
(1086,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1145,2): run-time error CSS1019: Unexpected token, found ')'
(1146,5): run-time error CSS1030: Expected identifier, found 'service('
(1146,5): run-time error CSS1031: Expected selector, found 'service('
(1146,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1227,2): run-time error CSS1019: Unexpected token, found ')'
(1228,5): run-time error CSS1030: Expected identifier, found 'service('
(1228,5): run-time error CSS1031: Expected selector, found 'service('
(1228,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1250,2): run-time error CSS1019: Unexpected token, found ')'
(1251,5): run-time error CSS1030: Expected identifier, found 'service('
(1251,5): run-time error CSS1031: Expected selector, found 'service('
(1251,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1282,2): run-time error CSS1019: Unexpected token, found ')'
(1283,5): run-time error CSS1030: Expected identifier, found 'service('
(1283,5): run-time error CSS1031: Expected selector, found 'service('
(1283,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1344,2): run-time error CSS1019: Unexpected token, found ')'
(1345,5): run-time error CSS1030: Expected identifier, found 'service('
(1345,5): run-time error CSS1031: Expected selector, found 'service('
(1345,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1363,2): run-time error CSS1019: Unexpected token, found ')'
(1364,5): run-time error CSS1030: Expected identifier, found 'service('
(1364,5): run-time error CSS1031: Expected selector, found 'service('
(1364,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1374,2): run-time error CSS1019: Unexpected token, found ')'
(1375,5): run-time error CSS1030: Expected identifier, found 'service('
(1375,5): run-time error CSS1031: Expected selector, found 'service('
(1375,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1398,2): run-time error CSS1019: Unexpected token, found ')'
(1399,5): run-time error CSS1030: Expected identifier, found 'service('
(1399,5): run-time error CSS1031: Expected selector, found 'service('
(1399,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1406,2): run-time error CSS1019: Unexpected token, found ')'
(1407,5): run-time error CSS1030: Expected identifier, found 'service('
(1407,5): run-time error CSS1031: Expected selector, found 'service('
(1407,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1484,2): run-time error CSS1019: Unexpected token, found ')'
(1485,5): run-time error CSS1030: Expected identifier, found 'service('
(1485,5): run-time error CSS1031: Expected selector, found 'service('
(1485,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1497,2): run-time error CSS1019: Unexpected token, found ')'
(1498,5): run-time error CSS1030: Expected identifier, found 'service('
(1498,5): run-time error CSS1031: Expected selector, found 'service('
(1498,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1515,2): run-time error CSS1019: Unexpected token, found ')'
(1516,5): run-time error CSS1030: Expected identifier, found 'service('
(1516,5): run-time error CSS1031: Expected selector, found 'service('
(1516,5): run-time error CSS1025: Expected comma or open brace, found 'service('
(1555,2): run-time error CSS1019: Unexpected token, found ')'
(1556,5): run-time error CSS1030: Expected identifier, found 'controller('
(1556,5): run-time error CSS1031: Expected selector, found 'controller('
(1556,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(1582,2): run-time error CSS1019: Unexpected token, found ')'
(1583,5): run-time error CSS1030: Expected identifier, found 'controller('
(1583,5): run-time error CSS1031: Expected selector, found 'controller('
(1583,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(1604,2): run-time error CSS1019: Unexpected token, found ')'
(1605,5): run-time error CSS1030: Expected identifier, found 'controller('
(1605,5): run-time error CSS1031: Expected selector, found 'controller('
(1605,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(1617,2): run-time error CSS1019: Unexpected token, found ')'
(1618,5): run-time error CSS1030: Expected identifier, found 'controller('
(1618,5): run-time error CSS1031: Expected selector, found 'controller('
(1618,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(1736,2): run-time error CSS1019: Unexpected token, found ')'
(1737,5): run-time error CSS1030: Expected identifier, found 'controller('
(1737,5): run-time error CSS1031: Expected selector, found 'controller('
(1737,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(1970,2): run-time error CSS1019: Unexpected token, found ')'
(1971,5): run-time error CSS1030: Expected identifier, found 'controller('
(1971,5): run-time error CSS1031: Expected selector, found 'controller('
(1971,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(2102,2): run-time error CSS1019: Unexpected token, found ')'
(2103,5): run-time error CSS1030: Expected identifier, found 'controller('
(2103,5): run-time error CSS1031: Expected selector, found 'controller('
(2103,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(2178,2): run-time error CSS1019: Unexpected token, found ')'
(2179,5): run-time error CSS1030: Expected identifier, found 'controller('
(2179,5): run-time error CSS1031: Expected selector, found 'controller('
(2179,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(2461,2): run-time error CSS1019: Unexpected token, found ')'
(2462,5): run-time error CSS1030: Expected identifier, found 'controller('
(2462,5): run-time error CSS1031: Expected selector, found 'controller('
(2462,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(2535,2): run-time error CSS1019: Unexpected token, found ')'
(2536,5): run-time error CSS1030: Expected identifier, found 'controller('
(2536,5): run-time error CSS1031: Expected selector, found 'controller('
(2536,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(2584,2): run-time error CSS1019: Unexpected token, found ')'
(2586,5): run-time error CSS1030: Expected identifier, found 'controller('
(2586,5): run-time error CSS1031: Expected selector, found 'controller('
(2586,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(2608,2): run-time error CSS1019: Unexpected token, found ')'
(2609,5): run-time error CSS1030: Expected identifier, found 'controller('
(2609,5): run-time error CSS1031: Expected selector, found 'controller('
(2609,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(2865,2): run-time error CSS1019: Unexpected token, found ')'
(2866,5): run-time error CSS1030: Expected identifier, found 'controller('
(2866,5): run-time error CSS1031: Expected selector, found 'controller('
(2866,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(2966,2): run-time error CSS1019: Unexpected token, found ')'
(2968,5): run-time error CSS1030: Expected identifier, found 'controller('
(2968,5): run-time error CSS1031: Expected selector, found 'controller('
(2968,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(3008,2): run-time error CSS1019: Unexpected token, found ')'
(3011,5): run-time error CSS1030: Expected identifier, found 'controller('
(3011,5): run-time error CSS1031: Expected selector, found 'controller('
(3011,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(3050,2): run-time error CSS1019: Unexpected token, found ')'
(3051,5): run-time error CSS1030: Expected identifier, found 'controller('
(3051,5): run-time error CSS1031: Expected selector, found 'controller('
(3051,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(3675,2): run-time error CSS1019: Unexpected token, found ')'
(3676,5): run-time error CSS1030: Expected identifier, found 'controller('
(3676,5): run-time error CSS1031: Expected selector, found 'controller('
(3676,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(3714,2): run-time error CSS1019: Unexpected token, found ')'
(3715,5): run-time error CSS1030: Expected identifier, found 'controller('
(3715,5): run-time error CSS1031: Expected selector, found 'controller('
(3715,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(3725,2): run-time error CSS1019: Unexpected token, found ')'
(3726,5): run-time error CSS1030: Expected identifier, found 'controller('
(3726,5): run-time error CSS1031: Expected selector, found 'controller('
(3726,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(3768,2): run-time error CSS1019: Unexpected token, found ')'
(3769,5): run-time error CSS1030: Expected identifier, found 'controller('
(3769,5): run-time error CSS1031: Expected selector, found 'controller('
(3769,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(3795,2): run-time error CSS1019: Unexpected token, found ')'
(3797,5): run-time error CSS1030: Expected identifier, found 'controller('
(3797,5): run-time error CSS1031: Expected selector, found 'controller('
(3797,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(3888,2): run-time error CSS1019: Unexpected token, found ')'
(3889,5): run-time error CSS1030: Expected identifier, found 'controller('
(3889,5): run-time error CSS1031: Expected selector, found 'controller('
(3889,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(3991,2): run-time error CSS1019: Unexpected token, found ')'
(3993,5): run-time error CSS1030: Expected identifier, found 'controller('
(3993,5): run-time error CSS1031: Expected selector, found 'controller('
(3993,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(4063,2): run-time error CSS1019: Unexpected token, found ')'
(4066,5): run-time error CSS1030: Expected identifier, found 'controller('
(4066,5): run-time error CSS1031: Expected selector, found 'controller('
(4066,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(4396,2): run-time error CSS1019: Unexpected token, found ')'
(4398,5): run-time error CSS1030: Expected identifier, found 'controller('
(4398,5): run-time error CSS1031: Expected selector, found 'controller('
(4398,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(4544,2): run-time error CSS1019: Unexpected token, found ')'
(4545,5): run-time error CSS1030: Expected identifier, found 'controller('
(4545,5): run-time error CSS1031: Expected selector, found 'controller('
(4545,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(4602,2): run-time error CSS1019: Unexpected token, found ')'
(4603,5): run-time error CSS1030: Expected identifier, found 'controller('
(4603,5): run-time error CSS1031: Expected selector, found 'controller('
(4603,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(4733,2): run-time error CSS1019: Unexpected token, found ')'
(4735,5): run-time error CSS1030: Expected identifier, found 'controller('
(4735,5): run-time error CSS1031: Expected selector, found 'controller('
(4735,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(4853,2): run-time error CSS1019: Unexpected token, found ')'
(4854,5): run-time error CSS1030: Expected identifier, found 'controller('
(4854,5): run-time error CSS1031: Expected selector, found 'controller('
(4854,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(4866,2): run-time error CSS1019: Unexpected token, found ')'
(4867,5): run-time error CSS1030: Expected identifier, found 'controller('
(4867,5): run-time error CSS1031: Expected selector, found 'controller('
(4867,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(4968,2): run-time error CSS1019: Unexpected token, found ')'
(4970,5): run-time error CSS1030: Expected identifier, found 'controller('
(4970,5): run-time error CSS1031: Expected selector, found 'controller('
(4970,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(4978,2): run-time error CSS1019: Unexpected token, found ')'
(4981,5): run-time error CSS1030: Expected identifier, found 'controller('
(4981,5): run-time error CSS1031: Expected selector, found 'controller('
(4981,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(5192,2): run-time error CSS1019: Unexpected token, found ')'
(5195,5): run-time error CSS1030: Expected identifier, found 'controller('
(5195,5): run-time error CSS1031: Expected selector, found 'controller('
(5195,5): run-time error CSS1025: Expected comma or open brace, found 'controller('
(5388,2): run-time error CSS1019: Unexpected token, found ')'
 */
var app = angular.module('proPitich',
    [
        "ui.router",
        "ngCookies",
        "ngMap",
        "ui.bootstrap",
        "firebase",
        'ui.select',
        'ngSanitize',
        'chart.js',
        'textAngular', 'angularSpectrumColorpicker', 'ui.bootstrap.dropdownToggle', 'ui.calendar', 'angularjs-dropdown-multiselect'
    ]);


var config = {
    apiKey: "AIzaSyA0Y8y8wmZ4y1PWQUn-xnPD3UVX1dA7WYM",
    authDomain: "propitch-b81d0.firebaseapp.com",
    databaseURL: "https://propitch-b81d0.firebaseio.com",
    projectId: "propitch-b81d0",
    storageBucket: "propitch-b81d0.appspot.com",
    messagingSenderId: "153247740525"
};


if (!firebase.apps.length) {
    firebase.initializeApp(config);
}
//firebase.initializeApp(config);

//app.value('folderPath', '../../ProPitch/Areas/Client/ClientApp/');
//app.value('folderPath', 'Areas/Client/ClientApp/');

var folderPath = 'Areas/Client/ClientApp/';
app.value('folderPath', folderPath);

app.value('weatherAppId', 'ee0315be59594383e5833803668bf4a1');

app.value('baseUrl', Websitebaseurl);
app.value('Containerbaseurl', Containerbaseurl);
//app.value('baseUrl', 'http://windowsdemo.projectstatus.co.uk/ProPitch/');
app.config(function ($stateProvider, $urlRouterProvider, $provide, ChartJsProvider) {
    var folderPath = 'Areas/Client/ClientApp/';
    //var folderPath = '../../ProPitch/Areas/Client/ClientApp/';
    $stateProvider.state(
        'home', {
            views: {
                'body': {
                    template: '<div class="bg-white-arf arf-singin" ui-view="content"></div>',
                },
                'footer': {
                    templateUrl: folderPath + 'Shared/Home/footer.html',
                }
            }
        })
        .state('home.login', {
            url: '/login',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/Login/login.html',
                    controller: 'loginController'
                }
            }
        })
        .state('home.registration', {
            url: '/registration',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/Registration/Registration.html',
                    controller: 'registrationController'
                }
            }
        })
        .state('home.about', {
            url: '/about',
            views: {
                'content': {
                    templateUrl: folderPath + 'Shared/Home/about.html',
                }
            }
        }).state('home.forgotPassword', {
            url: '/forgotPassword',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/ForgotPassword/forgotPassword.html',
                    controller: 'forgotPasswordController'
                }
            }
        });

    $stateProvider.state(
        'user', {
            views: {
                'header': {
                    templateUrl: folderPath + 'Shared/UserPanel/header.html',
                    controller: 'mainController'
                },
                'body': {
                    templateUrl: folderPath + 'Shared/UserPanel/body.html',
                    controller: 'mainController'
                },
                'footer': {
                    templateUrl: folderPath + 'Shared/UserPanel/footer.html',
                    controller: 'mainController'
                }
            }
        })
        .state('user.dashboard', {
            url: '/dashboard',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/Dashboard/dashboard.html',
                    controller: 'dashboardController'
                }
            }
        })
        .state('user.venues', {
            url: '/venues',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/venue/list.html',
                    controller: 'venueController'
                }
            }
        })
        .state('user.manageVenue', {
            url: '/managevenue/:index',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/venue/manageVenue.html',
                    controller: 'ManageVenueController'
                }
            }
        })
        .state('user.venueDetail', {
            url: '/venuedetail/:index',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/VenueDetail/VenueDetail.html',
                    controller: 'VenueDetailController'
                }
            }
        })

        .state('user.groundManager', {
            url: '/groundmanager',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/GroundManager/List.html',
                    controller: 'groundManListController'
                }
            }
        })
        .state('user.pitchmatter', {
            url: '/pitchmatter',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/PitchMatter/pitchMatterList.html',
                    controller: 'pitchMatterController'
                }
            }
        })
        .state('user.createGroundManager', {
            url: '/creategroundmanager/:index',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/GroundManager/Create.html',
                    controller: 'groundManCreateController'
                }
            }
        })
        .state('user.subClient', {
            url: '/subusers',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/SubClient/List.html',
                    controller: 'SubClientListController'
                }
            }
        })
        .state('user.manageSubClient', {
            url: '/managesubusers/:index',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/SubClient/Create.html',
                    controller: 'ManageSubClientController'
                }
            }
        })
        .state('user.manageProfile', {
            url: '/manageprofile',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/ManageProfile/ManageProfile.html',
                    controller: 'ManageProfileController'
                }
            }
        })
        .state('user.editProfile', {
            url: '/editprofile',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/ManageProfile/EditProfile.html',
                    controller: 'ManageProfileController'
                }
            }
        })
        .state('user.requestAssessment', {
            url: '/requestassessment',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/RequestAssessment/List.html',
                    controller: 'assessmentController'
                }
            }
        })
        .state('user.support', {
            url: '/support',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/Support/support.html',
                    controller: 'supportController'
                }
            }
        })
        .state('user.groundManagerDetail', {
            url: '/groundmanagerdetail/:index',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/GroundManager/Detail.html',
                    controller: 'DetailController'
                }
            }
        }).state('user.message', {
            url: '/message',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/Message/message.html',
                    controller: 'MessageController'
                }
            }
        })
        .state('user.faq', {
            url: '/faq',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/FAQ/List.html',
                    controller: 'ListController'
                }
            }
        }).state('user.reportView', {
            url: '/reportview/:reportId',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: 'Content/CommonHtml/ReportView.html',
                    controller: 'reportViewController'
                }
            }
        })
        .state('user.report', {
            url: '/report',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/Reports/Reports.html',
                    controller: 'reportController'
                }
            }
        }).state('user.MatchDayreport', {
            url: '/MatchDayreport',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/MatchDayReports/MatchDayReports.html',
                    controller: 'MatchDayreportController'
                }
            }
        })
        .state('user.DataCollectionreport', {
            url: '/DataCollectionreport',
            views: {
                'content': {
                    templateUrl: folderPath + 'Components/DataAssessmentReport/DataAssessmentreport.html',
                    controller: 'DataAssessmentreportController'
                }
            }
        }).state('user.DataAssesmentviewreport', {
            url: '/DataAssesmentviewreport/:AssessmentId',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: 'Content/CommonHtml/DataAssessmentSummaryDetailsGraph.html',
                    controller: 'DataAssessmentReportSummaryPageController'
                }
            }
        }).state('user.datacollectionviewreport', {

            url: '/datacollectionviewreport/:Id',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: 'Content/CommonHtml/DataAssessmentViewReport.html',
                    controller: 'datacollectionviewreportController'
                }
            }
        }) 
        .state('user.MatchDayreportView', {
            url: '/MatchDayreportview/:reportId',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: 'Content/CommonHtml/MatchDayReportView.html',
                    controller: 'MatchDayreportViewController'
                }
            }
        }).state('user.reportSummary', {
            url: '/reportsummary/:reportId',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: 'Content/CommonHtml/ReportSummaryPage.html',
                    controller: 'reportSummaryController'
                }
            }
        }).state('user.MatchDayreportSummary', {
            url: '/MatchDayreportsummary/:reportId',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: 'Content/CommonHtml/MatchDayReportSummaryPage.html',
                    controller: 'MatchDayreportSummaryController'
                }
            }
        }).state('user.notification', {
            url: '/notification',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: folderPath + 'Components/Notification/notification.html',
                    controller: 'NotificationController'
                }
            }
        }).state('user.membership', {
            url: '/membership',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: folderPath + 'Components/Membership/Membership.html',
                    controller: 'membershipController'
                }
            }
        }).state('user.calendar', {
            url: '/calendar',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: folderPath + 'Components/calendar/calendar.html',
                    controller: 'CalendarController'
                }
            }
        }).state('user.venueDocument', {
            url: '/venueDocument',
            views: {
                'content': {
                    title: 'v',
                    templateUrl: folderPath + 'Components/venueDocument/VenueDocument.html',
                    controller: 'VenueDocumentController'
                }
            }
        })
        .state('user.venueInfo', {
            url: '/venueinfo',
            views: {
                'content': {
                    title: 'Venue Info',
                    templateUrl: folderPath + 'Components/VenueInfo/venueInfo.html',
                    controller: 'venueInfoController'
                }
            }
        });

    $urlRouterProvider.otherwise("/login");
    $provide.decorator('taOptions', ['taRegisterTool', '$delegate', function (taRegisterTool, taOptions) {
        // $delegate is the taOptions we are decorating
        // register the tool with textAngular

        taRegisterTool('backgroundColor', {
            display: "<div spectrum-colorpicker ng-model='color' on-change='!!color && action(color)' format='\"hex\"' options='options'></div>",
            action: function (color) {
                var me = this;
                if (!this.$editor().wrapSelection) {
                    setTimeout(function () {
                        me.action(color);
                    }, 100)
                } else {
                    return this.$editor().wrapSelection('backColor', color);
                }
            },
            options: {
                replacerClassName: 'fa fa-paint-brush', showButtons: false
            },
            color: "#fff"
        });
        taRegisterTool('fontColor', {
            display: "<spectrum-colorpicker trigger-id='{{trigger}}' ng-model='color' on-change='!!color && action(color)' format='\"hex\"' options='options'></spectrum-colorpicker>",
            action: function (color) {
                var me = this;
                if (!this.$editor().wrapSelection) {
                    setTimeout(function () {
                        me.action(color);
                    }, 100)
                } else {
                    return this.$editor().wrapSelection('foreColor', color);
                }
            },
            options: {
                replacerClassName: 'fa fa-font', showButtons: false
            },
            color: "#000"
        });


        taRegisterTool('fontName', {
            display: "<span class='bar-btn-dropdown dropdown'>" +
                "<button class='btn btn-blue dropdown-toggle' type='button' ng-disabled='showHtml()' style='padding-top: 4px'><i class='fa fa-font'></i><i class='fa fa-caret-down'></i></button>" +
                "<ul class='dropdown-menu'><li ng-repeat='o in options'><button class='btn btn-blue checked-dropdown' style='font-family: {{o.css}}; width: 100%' type='button' ng-click='action($event, o.css)'><i ng-if='o.active' class='fa fa-check'></i>{{o.name}}</button></li></ul></span>",
            action: function (event, font) {
                //Ask if event is really an event.
                if (!!event.stopPropagation) {
                    //With this, you stop the event of textAngular.
                    event.stopPropagation();
                    //Then click in the body to close the dropdown.
                    $("body").trigger("click");
                }
                return this.$editor().wrapSelection('fontName', font);
            },
            options: [
                { name: 'Sans-Serif', css: 'Arial, Helvetica, sans-serif' },
                { name: 'Serif', css: "'times new roman', serif" },
                { name: 'Wide', css: "'arial black', sans-serif" },
                { name: 'Narrow', css: "'arial narrow', sans-serif" },
                { name: 'Comic Sans MS', css: "'comic sans ms', sans-serif" },
                { name: 'Courier New', css: "'courier new', monospace" },
                { name: 'Garamond', css: 'garamond, serif' },
                { name: 'Georgia', css: 'georgia, serif' },
                { name: 'Tahoma', css: 'tahoma, sans-serif' },
                { name: 'Trebuchet MS', css: "'trebuchet ms', sans-serif" },
                { name: "Helvetica", css: "'Helvetica Neue', Helvetica, Arial, sans-serif" },
                { name: 'Verdana', css: 'verdana, sans-serif' },
                { name: 'Proxima Nova', css: 'proxima_nova_rgregular' }
            ]
        });


        taRegisterTool('fontSize', {
            display: "<span class='bar-btn-dropdown dropdown'>" +
                "<button class='btn btn-blue dropdown-toggle' type='button' ng-disabled='showHtml()' style='padding-top: 4px'><i class='fa fa-text-height'></i><i class='fa fa-caret-down'></i></button>" +
                "<ul class='dropdown-menu'><li ng-repeat='o in options'><button class='btn btn-blue checked-dropdown' style='font-size: {{o.css}}; width: 100%' type='button' ng-click='action($event, o.value)'><i ng-if='o.active' class='fa fa-check'></i> {{o.name}}</button></li></ul>" +
                "</span>",
            action: function (event, size) {
                //Ask if event is really an event.
                if (!!event.stopPropagation) {
                    //With this, you stop the event of textAngular.
                    event.stopPropagation();
                    //Then click in the body to close the dropdown.
                    $("body").trigger("click");
                }
                return this.$editor().wrapSelection('fontSize', parseInt(size));
            },
            options: [
                { name: 'xx-small', css: 'xx-small', value: 1 },
                { name: 'x-small', css: 'x-small', value: 2 },
                { name: 'small', css: 'small', value: 3 },
                { name: 'medium', css: 'medium', value: 4 },
                { name: 'large', css: 'large', value: 5 },
                { name: 'x-large', css: 'x-large', value: 6 },
                { name: 'xx-large', css: 'xx-large', value: 7 }

            ]
        });


        // add the button to the default toolbar definition
        taOptions.toolbar[1].push('backgroundColor', 'fontColor', 'fontName', 'fontSize');
        return taOptions;
    }]);
});

app.run(function ($http, $cookies, $state, $rootScope, $location, $window) {
    $http.defaults.headers.post = { 'Content-Type': 'application/json' };

    $rootScope.$on('$locationChangeSuccess', function ($event, next, current, userServices, ) {
        var loginDetail = $cookies.get("loginDetail");
        if ($state.current.name.indexOf("home.") === -1) {
            if (!loginDetail) {
                $state.go('home.login');
            }
        }
    });


    $rootScope.$on('$viewContentLoaded', function () {

        $window.scrollTo(0, 0);

    });
});


app.directive('numbersOnly', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {
            function fromUser(text) {
                if (text) {
                    var transformedInput = text.replace(/[^0-9]/g, '');

                    if (transformedInput !== text) {
                        ngModelCtrl.$setViewValue(transformedInput);
                        ngModelCtrl.$render();
                    }
                    return transformedInput;
                }
                return undefined;
            }
            ngModelCtrl.$parsers.push(fromUser);
        }
    };
});
app.filter('titleCase', function () {
    return function (input) {
        input = input || '';
        return input.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
    };
});
app.directive('datePicker', function () {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ngModelController) {

            // Private variables
            var datepickerFormat = 'dd/M/yyyy',
                momentFormat = 'DD/MMM/YYYY',
                datepicker,
                elPicker;

            // Init date picker and get objects http://bootstrap-datepicker.readthedocs.org/en/release/index.html
            datepicker = element.datepicker({
                autoclose: true,
                keyboardNavigation: false,
                todayHighlight: true,
                format: datepickerFormat,
                startDate: new Date()
            });
            elPicker = datepicker.data('datepicker').picker;

            // Adjust offset on show
            datepicker.on('show', function (evt) {
                elPicker.css('left', parseInt(elPicker.css('left')) + +attrs.offsetX);
                elPicker.css('top', parseInt(elPicker.css('top')) + +attrs.offsetY);
            });

            // Only watch and format if ng-model is present https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
            if (ngModelController) {
                // So we can maintain time
                var lastModelValueMoment;

                ngModelController.$formatters.push(function (modelValue) {
                    //
                    // Date -> String
                    //

                    // Get view value (String) from model value (Date)
                    var viewValue,
                        m = moment(modelValue);
                    if (modelValue && m.isValid()) {
                        // Valid date obj in model
                        lastModelValueMoment = m.clone(); // Save date (so we can restore time later)
                        viewValue = m.format(momentFormat);
                    } else {
                        // Invalid date obj in model
                        lastModelValueMoment = undefined;
                        viewValue = undefined;
                    }

                    // Update picker
                    element.datepicker('update', viewValue);

                    // Update view
                    return viewValue;
                });

                ngModelController.$parsers.push(function (viewValue) {
                    //
                    // String -> Date
                    //

                    // Get model value (Date) from view value (String)
                    var modelValue,
                        m = moment(viewValue, momentFormat, true);
                    if (viewValue && m.isValid()) {
                        // Valid date string in view
                        if (lastModelValueMoment) { // Restore time
                            m.hour(lastModelValueMoment.hour());
                            m.minute(lastModelValueMoment.minute());
                            m.second(lastModelValueMoment.second());
                            m.millisecond(lastModelValueMoment.millisecond());
                        }
                        modelValue = m;
                    } else {
                        // Invalid date string in view
                        modelValue = undefined;
                    }

                    // Update model
                    return modelValue;
                });

                datepicker.on('changeDate', function (evt) {
                    // Only update if it's NOT an <input> (if it's an <input> the datepicker plugin trys to cast the val to a Date)
                    if (evt.target.tagName !== 'INPUT') {
                        ngModelController.$setViewValue(moment(evt.date).format(momentFormat)); // $seViewValue basically calls the $parser above so we need to pass a string date value in
                        ngModelController.$render();
                    }
                });
            }

        }
    };
});
app.directive('imagePopup', function ($uibModal) {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, elem, attrs, ngModelController) {
            elem.bind('click', function () {
                $uibModal.open({
                    template: '<i class="fa fa-times" ng-click="close()" style="cursor: pointer;position:absolute;margin-top:-15px;font-size:19px;right:-15px;"></i><img src="' + elem[0].currentSrc + '" style="width: 100%;">',
                    controller: function ($uibModalInstance, $scope) {
                        $scope.close = function () {
                            $uibModalInstance.close();
                        }
                    }
                }).result.then(function () {

                }, function (reason) {

                });
            });
        }

    }
});
app.directive('ngEnter', function () { //a directive to 'enter key press' in elements with the "ng-enter" attribute
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});
app.filter('positive', function () {
    return function (input) {
        if (!input) {
            return 0;
        }

        return Math.abs(input);
    };
});

var directiveModule = angular.module('angularjs-dropdown-multiselect', []);

directiveModule.directive('ngDropdownMultiselect', ['$filter', '$document', '$compile', '$parse',

    function ($filter, $document, $compile, $parse) {

        return {
            restrict: 'AE',
            scope: {
                selectedModel: '=',
                options: '=',
                extraSettings: '=',
                events: '=',
                searchFilter: '=?',
                translationTexts: '=',
                groupBy: '@'
            },
            template: function (element, attrs) {
                var checkboxes = attrs.checkboxes ? true : false;
                var groups = attrs.groupBy ? true : false;

                var template = '<div class="multiselect-parent btn-group dropdown-multiselect">';
                template += '<button type="button" class="dropdown-toggle" ng-class="settings.buttonClasses" ng-click="toggleDropdown()">{{getButtonText()}}&nbsp;<span class="caret"></span></button>';
                template += '<ul class="dropdown-menu dropdown-menu-form" ng-style="{display: open ? \'block\' : \'none\', height : settings.scrollable ? settings.scrollableHeight : \'auto\' }" style="overflow: scroll" >';
                template += '<li ng-hide="!settings.showCheckAll || settings.selectionLimit > 0"><a data-ng-click="selectAll()"><span class="glyphicon glyphicon-ok"></span>  {{texts.checkAll}}</a>';
                template += '<li ng-show="settings.showUncheckAll"><a data-ng-click="deselectAll();"><span class="glyphicon glyphicon-remove"></span>   {{texts.uncheckAll}}</a></li>';
                template += '<li ng-hide="(!settings.showCheckAll || settings.selectionLimit > 0) && !settings.showUncheckAll" class="divider"></li>';
                template += '<li ng-show="settings.enableSearch"><div class="dropdown-header"><input type="text" class="form-control" style="width: 100%;" ng-model="searchFilter" placeholder="{{texts.searchPlaceholder}}" /></li>';
                template += '<li ng-show="settings.enableSearch" class="divider"></li>';

                if (groups) {
                    template += '<li ng-repeat-start="option in orderedItems | filter: searchFilter" ng-show="getPropertyForObject(option, settings.groupBy) !== getPropertyForObject(orderedItems[$index - 1], settings.groupBy)" role="presentation" class="dropdown-header">{{ getGroupTitle(getPropertyForObject(option, settings.groupBy)) }}</li>';
                    template += '<li ng-repeat-end role="presentation">';
                } else {
                    template += '<li role="presentation" ng-repeat="option in options | filter: searchFilter">';
                }

                template += '<a role="menuitem" tabindex="-1" ng-click="setSelectedItem(getPropertyForObject(option,settings.idProp))">';

                if (checkboxes) {
                    template += '<div class="checkbox"><label><input class="checkboxInput" type="checkbox" ng-click="checkboxClick($event, getPropertyForObject(option,settings.idProp))" ng-checked="isChecked(getPropertyForObject(option,settings.idProp))" /> {{getPropertyForObject(option, settings.displayProp)}}</label></div></a>';
                } else {
                    template += '<span data-ng-class="{\'glyphicon glyphicon-ok\': isChecked(getPropertyForObject(option,settings.idProp))}"></span> {{getPropertyForObject(option, settings.displayProp)}}</a>';
                }

                template += '</li>';

                template += '<li class="divider" ng-show="settings.selectionLimit > 1"></li>';
                template += '<li role="presentation" ng-show="settings.selectionLimit > 1"><a role="menuitem">{{selectedModel.length}} {{texts.selectionOf}} {{settings.selectionLimit}} {{texts.selectionCount}}</a></li>';

                template += '</ul>';
                template += '</div>';

                element.html(template);
            },
            link: function ($scope, $element, $attrs) {
                var $dropdownTrigger = $element.children()[0];

                $scope.toggleDropdown = function () {
                    $scope.open = !$scope.open;
                };

                $scope.checkboxClick = function ($event, id) {
                    $scope.setSelectedItem(id);
                    $event.stopImmediatePropagation();
                };

                $scope.externalEvents = {
                    onItemSelect: angular.noop,
                    onItemDeselect: angular.noop,
                    onSelectAll: angular.noop,
                    onDeselectAll: angular.noop,
                    onInitDone: angular.noop,
                    onMaxSelectionReached: angular.noop
                };

                $scope.settings = {
                    dynamicTitle: true,
                    scrollable: false,
                    scrollableHeight: '300px',
                    closeOnBlur: true,
                    displayProp: 'label',
                    idProp: 'id',
                    externalIdProp: 'id',
                    enableSearch: false,
                    selectionLimit: 0,
                    showCheckAll: true,
                    showUncheckAll: true,
                    closeOnSelect: false,
                    buttonClasses: 'btn btn-default',
                    closeOnDeselect: false,
                    groupBy: $attrs.groupBy || undefined,
                    groupByTextProvider: null,
                    smartButtonMaxItems: 0,
                    smartButtonTextConverter: angular.noop
                };

                $scope.texts = {
                    checkAll: 'Check All',
                    uncheckAll: 'Uncheck All',
                    selectionCount: 'checked',
                    selectionOf: '/',
                    searchPlaceholder: 'Search...',
                    buttonDefaultText: 'Select',
                    dynamicButtonTextSuffix: 'checked'
                };

                $scope.searchFilter = $scope.searchFilter || '';

                if (angular.isDefined($scope.settings.groupBy)) {
                    $scope.$watch('options', function (newValue) {
                        if (angular.isDefined(newValue)) {
                            $scope.orderedItems = $filter('orderBy')(newValue, $scope.settings.groupBy);
                        }
                    });
                }

                angular.extend($scope.settings, $scope.extraSettings || []);
                angular.extend($scope.externalEvents, $scope.events || []);
                angular.extend($scope.texts, $scope.translationTexts);

                $scope.singleSelection = $scope.settings.selectionLimit === 1;

                function getFindObj(id) {
                    var findObj = {};

                    if ($scope.settings.externalIdProp === '') {
                        findObj[$scope.settings.idProp] = id;
                    } else {
                        findObj[$scope.settings.externalIdProp] = id;
                    }

                    return findObj;
                }

                function clearObject(object) {
                    for (var prop in object) {
                        delete object[prop];
                    }
                }

                if ($scope.singleSelection) {
                    if (angular.isArray($scope.selectedModel) && $scope.selectedModel.length === 0) {
                        clearObject($scope.selectedModel);
                    }
                }

                if ($scope.settings.closeOnBlur) {
                    $document.on('click', function (e) {
                        var target = e.target.parentElement;
                        var parentFound = false;

                        while (angular.isDefined(target) && target !== null && !parentFound) {
                            if (_.contains(target.className.split(' '), 'multiselect-parent') && !parentFound) {
                                if (target === $dropdownTrigger) {
                                    parentFound = true;
                                }
                            }
                            target = target.parentElement;
                        }

                        if (!parentFound) {
                            $scope.$apply(function () {
                                $scope.open = false;
                            });
                        }
                    });
                }

                $scope.getGroupTitle = function (groupValue) {
                    if ($scope.settings.groupByTextProvider !== null) {
                        return $scope.settings.groupByTextProvider(groupValue);
                    }

                    return groupValue;
                };

                $scope.getButtonText = function () {
                    if ($scope.settings.dynamicTitle && ($scope.selectedModel.length > 0 || (angular.isObject($scope.selectedModel) && _.keys($scope.selectedModel).length > 0))) {
                        if ($scope.settings.smartButtonMaxItems > 0) {
                            var itemsText = [];

                            angular.forEach($scope.options, function (optionItem) {
                                if ($scope.isChecked($scope.getPropertyForObject(optionItem, $scope.settings.idProp))) {
                                    var displayText = $scope.getPropertyForObject(optionItem, $scope.settings.displayProp);
                                    var converterResponse = $scope.settings.smartButtonTextConverter(displayText, optionItem);

                                    itemsText.push(converterResponse ? converterResponse : displayText);
                                }
                            });

                            if ($scope.selectedModel.length > $scope.settings.smartButtonMaxItems) {
                                itemsText = itemsText.slice(0, $scope.settings.smartButtonMaxItems);
                                itemsText.push('...');
                            }

                            return itemsText.join(', ');
                        } else {
                            var totalSelected;

                            if ($scope.singleSelection) {
                                totalSelected = ($scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp])) ? 1 : 0;
                            } else {
                                totalSelected = angular.isDefined($scope.selectedModel) ? $scope.selectedModel.length : 0;
                            }

                            if (totalSelected === 0) {
                                return $scope.texts.buttonDefaultText;
                            } else {
                                return totalSelected + ' ' + $scope.texts.dynamicButtonTextSuffix;
                            }
                        }
                    } else {
                        return $scope.texts.buttonDefaultText;
                    }
                };

                $scope.getPropertyForObject = function (object, property) {
                    if (angular.isDefined(object) && object.hasOwnProperty(property)) {
                        return object[property];
                    }

                    return '';
                };

                $scope.selectAll = function () {
                    $scope.deselectAll(false);
                    $scope.externalEvents.onSelectAll();

                    angular.forEach($scope.options, function (value) {
                        $scope.setSelectedItem(value[$scope.settings.idProp], true);
                    });
                };

                $scope.deselectAll = function (sendEvent) {
                    sendEvent = sendEvent || true;

                    if (sendEvent) {
                        $scope.externalEvents.onDeselectAll();
                    }

                    if ($scope.singleSelection) {
                        clearObject($scope.selectedModel);
                    } else {
                        $scope.selectedModel.splice(0, $scope.selectedModel.length);
                    }
                };

                $scope.setSelectedItem = function (id, dontRemove) {
                    var findObj = getFindObj(id);
                    var finalObj = null;

                    if ($scope.settings.externalIdProp === '') {
                        finalObj = _.find($scope.options, findObj);
                    } else {
                        finalObj = findObj;
                    }

                    if ($scope.singleSelection) {
                        clearObject($scope.selectedModel);
                        angular.extend($scope.selectedModel, finalObj);
                        $scope.externalEvents.onItemSelect(finalObj);
                        if ($scope.settings.closeOnSelect) $scope.open = false;

                        return;
                    }

                    dontRemove = dontRemove || false;

                    var exists = _.findIndex($scope.selectedModel, findObj) !== -1;

                    if (!dontRemove && exists) {
                        $scope.selectedModel.splice(_.findIndex($scope.selectedModel, findObj), 1);
                        $scope.externalEvents.onItemDeselect(findObj);
                    } else if (!exists && ($scope.settings.selectionLimit === 0 || $scope.selectedModel.length < $scope.settings.selectionLimit)) {
                        $scope.selectedModel.push(finalObj);
                        $scope.externalEvents.onItemSelect(finalObj);
                    }
                    if ($scope.settings.closeOnSelect) $scope.open = false;
                };

                $scope.isChecked = function (id) {
                    if ($scope.singleSelection) {
                        return $scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp]) && $scope.selectedModel[$scope.settings.idProp] === getFindObj(id)[$scope.settings.idProp];
                    }

                    return _.findIndex($scope.selectedModel, getFindObj(id)) !== -1;
                };

                $scope.externalEvents.onInitDone();
            }
        };
    }]);
app.service('httpService', function ($http, baseUrl, $cookies, $q, $state, $rootScope) {

    function login(url, postData) {
        var loginDetail = $cookies.get("loginDetail");
        if (loginDetail) {
            $http.defaults.headers.Authorization = loginDetail;
        }
        $rootScope.isLoading = true;
        return $http.post(baseUrl + url, postData)
    }

    function post(url, postData) {
        var defferd = $q.defer();

        var loginDetail = $cookies.get("loginDetail");
        if (loginDetail) {
            $http.defaults.headers.Authorization = loginDetail;
        }
        $rootScope.isLoading = true;
        $http.defaults.headers.post = { 'Content-Type': 'application/json' }
        $http.post(baseUrl + url, postData).then(function (res, err) {
            $rootScope.isLoading = false;
            if (res.status === 200) {
                switch (res.data.StatusCode) {
                    case 201:
                    case 200:
                        defferd.resolve(res.data);
                        break;
                    case 401:
                        toastr.error(res.data.Message, "Error");
                        $state.go('home.login');
                        break;
                    case 404:
                        toastr.warning(res.data.Message, "Information");
                        break;
                    default:
                        toastr.error(res.data.Message, "Error");
                        break;
                }
            }
        }, function errorCallback(response) {
            toastr.error("Server not responding", "Error");
            $rootScope.isLoading = false;
        });
        return defferd.promise;
    }

    function get(url) {
        var defferd = $q.defer();

        var loginDetail = $cookies.get("loginDetail");
        if (loginDetail) {
            $http.defaults.headers.Authorization = loginDetail;
        }
        $rootScope.isLoading = true;
        $http.get(baseUrl + url).then(function (res, err) {
            $rootScope.isLoading = false;
            if (res.status === 200) {
                switch (res.data.StatusCode) {
                    case 201:
                    case 200:
                        defferd.resolve(res.data);
                        break;
                    case 401:
                        toastr.error(res.data.Message, "Error");
                        $state.go('home.login');
                        break;
                    case 404:
                        toastr.warning(res.data.Message, "Information");
                        break;
                    default:
                        toastr.error(res.data.Message, "Error");
                        break;
                }
            }
        }, function errorCallback(response) {
            toastr.error("Server not responding", "Error");
            $rootScope.isLoading = false;
        });
        return defferd.promise;
    }

    function fileUpload(url, postData) {
        var defferd = $q.defer();

        var loginDetail = $cookies.get("loginDetail");
        if (loginDetail) {
            $http.defaults.headers.Authorization = loginDetail;
        }
        $http.defaults.headers.post = { 'Content-Type': undefined };
        $rootScope.isLoading = true;

        $http.post(baseUrl + url, postData).then(function (res, err) {
            $rootScope.isLoading = false;
            if (res.status === 200) {
                switch (res.data.StatusCode) {
                    case 201:
                    case 200:
                        defferd.resolve(res.data);
                        break;
                    default:
                        toastr.error(res.data.Message, "Error");
                        break;
                }
            }
        }, function errorCallback(response) {
            toastr.error("Server not responding", "Error");
            $rootScope.isLoading = false;
        });
        return defferd.promise;
    }

    this.login = login;
    this.post = post;
    this.get = get;
    this.fileUpload = fileUpload;
});
app.service('userServices', function (httpService, $httpParamSerializerJQLike, $state, $cookies, $http) {

    function login(postData) {
        var requestData = $httpParamSerializerJQLike(postData);
        $http.defaults.headers.post = { 'Content-Type': 'application/x-www-form-urlencoded' }
        return httpService.login("Token", requestData);
    }

    function setCookie(data) {
        $cookies.put("loginDetail", data.token_type + ' ' + data.access_token);
    }

    function forgotPassword(email) {
        return httpService.post("/api/User/ForgotPassword", { Email: email });
    }

    function registration(postModel) {
        return httpService.post("/api/Client/Registration", postModel);
    }


    function getUserDetail(email) {
        return httpService.get("/api/Client/GetUserDetail");
    }    
    function AllowViewReportsToSubclientIfClientHasMembershipData() {
        return httpService.get("/api/Client/AllowViewReportsToSubclientIfClientHasMembershipData");
    } 
    function saveUserDetail(user) {
        $cookies.put("userDetail", JSON.stringify(user));
    }

    function getCurentUser() {
        if ($cookies.get("userDetail")) {
            return JSON.parse($cookies.get("userDetail"));
        } else {
            $state.go("home.login");
            return {};
        }
    }

    function removeCookies() {
        $cookies.remove("loginDetail");
        $cookies.remove("userDetail");
    }

    function changePassword(model) {
        return httpService.post("/api/Client/ChangePassword", model);
    }

    this.login = login;
    this.setCookie = setCookie;
    this.forgotPassword = forgotPassword;
    this.getUserDetail = getUserDetail;
    this.saveUserDetail = saveUserDetail;
    this.getCurentUser = getCurentUser;
    this.removeCookies = removeCookies;
    this.registration = registration;
    this.changePassword = changePassword;  
    this.AllowViewReportsToSubclientIfClientHasMembershipData = AllowViewReportsToSubclientIfClientHasMembershipData;
});
app.service('venueServices', function (httpService) {

    function getVenuesList(model) {
        return httpService.post("/api/Client/GetVenuesList", model);
    }

    function CanActiveOrCreateVenue() {
        return httpService.get("/api/Client/CanActiveOrCreateVenue");
    }

    function getCountryList(email) {
        return httpService.get("/api/Client/GetCountryList");
    }

    function getConstructionTypesList(email) {
        return httpService.get("/api/Client/GetConstructionTypesList");
    }

    function manageVenueDetail(model) {
        return httpService.post("/api/Client/ManageVenueDetail", model);
    }

    function getVenueDetailById(id) {
        return httpService.get("/api/Client/GetVenueDetailById?id=" + id);
    }

    function deleteVenue(id) {
        return httpService.get("/api/Client/DeleteVenue?id=" + id);
    }

    function DeleteVenueImage(id, type) {
        return httpService.post("api/Client/DeleteVenueImage?id=" + id + "&type=" + type);
    }


    function getGroundManagers(model) {
        return httpService.post("/Api/Client/GetGroundMans", model);
    }

    function getVenueAssessmentSummary(venueId) {
        return httpService.get("/api/Client/VenueAssessmentSummaries?venueId=" + venueId);
    }

    function FilterVenueAssessmentSummaries(model) {
        return httpService.post("/api/Client/FilterVenueAssessmentSummaries", model);
    }

    function getLightingHourGraph(venueId) {
        return httpService.get("/api/Client/Stats/LightingHourGraph?venueId=" + venueId);
    }

    function getTrendGraph(venueId) {
        return httpService.get("/api/Client/Stats/TrendGraph?venueId=" + venueId);
    }

    function getScoring(venueId) {
        return httpService.get("/api/Client/Stats/Scoring?venueId=" + venueId);
    }


    function activeDeactiveVenue(venueId) {
        return httpService.get("/api/Client/ActiveDeactiveVenue?venueId=" + venueId);
    }

    this.CanActiveOrCreateVenue = CanActiveOrCreateVenue;
    this.activeDeactiveVenue = activeDeactiveVenue;
    this.getScoring = getScoring;
    this.getLightingHourGraph = getLightingHourGraph;
    this.getTrendGraph = getTrendGraph;
    this.getVenuesList = getVenuesList;
    this.getCountryList = getCountryList;
    this.getConstructionTypesList = getConstructionTypesList;
    this.manageVenueDetail = manageVenueDetail;
    this.getVenueDetailById = getVenueDetailById;
    this.deleteVenue = deleteVenue;
    this.getGroundManagers = getGroundManagers;
    this.getVenueAssessmentSummary = getVenueAssessmentSummary;

    this.FilterVenueAssessmentSummaries = FilterVenueAssessmentSummaries;
    this.DeleteVenueImage = DeleteVenueImage;

});
app.service('groundManagerServices', function (httpService, $httpParamSerializerJQLike, $cookies, $http) {
    function createGroundMan(formData) {
        return httpService.fileUpload("/Api/Client/CreateGroundMan", formData);
    }

    function getGroundManagers(model) {
        return httpService.post("/Api/Client/GetGroundMans", model);
    }

    function getGroundManagerById(id) {
        return httpService.get("Api/Client/getGroundManagerById?id=" + id);
    }

    function deleteGroundManager(id) {
        return httpService.get("Api/Client/DeleteGroundMan?id=" + id);
    }

    this.createGroundMan = createGroundMan;
    this.getGroundManagers = getGroundManagers;
    this.getGroundManagerById = getGroundManagerById;
    this.deleteGroundManager = deleteGroundManager;

});
app.service('subClientServices', function (httpService, $httpParamSerializerJQLike, $cookies, $http) {
    function createSubClient(formData) {
        return httpService.fileUpload("/Api/Client/CreateSubClient", formData);
    }

    function getSubClients(model) {
        return httpService.post("/Api/Client/GetSubClients", model);
    }

    function getSubClientById(id) {
        return httpService.get("Api/Client/getSubClientById?id=" + id);
    }

    function deleteSubClient(id) {
        return httpService.get("Api/Client/DeleteSubClient?id=" + id);
    }

    function disableSubClient(id) {
        return httpService.get("Api/Client/DisableSubClient?id=" + id);
    }
    function getUserType() {
        return httpService.get("Api/Client/UserType");
    }
    this.disableSubClient = disableSubClient;
    this.createSubClient = createSubClient;
    this.getSubClients = getSubClients;
    this.getSubClientById = getSubClientById;
    this.deleteSubClient = deleteSubClient;

    this.getUserType = getUserType;

});
app.service('assessmentServices', function (httpService, $cookies, $http, weatherAppId) {
    function getAssessmentList(model) {
        return httpService.post("/api/Client/AssessmentRequestList", model);
    }
    function createAssessmentRequest(model) {
        return httpService.post("/api/Client/AssessmentRequest/Create", model);
    }

    function deleteAssessmentRequest(id) {
        return httpService.get("/api/Client/AssessmentRequest/Delete?id=" + id);
    }
    function editAssessmentRequest(model) {
        return httpService.post("/api/Client/AssessmentRequest/Edit", model);
    }

    function getAssessmentInfoById(id) {
        return httpService.get("/Api/Client/Assessment/GetAssessmentInfoById?requestId=" + id);
    }

    function setAssessmentType(type) {
        $cookies.put("AssessmentType", type);
    }
    function getAssessmentType() {
        return $cookies.get("AssessmentType");
    }

    function getWeatherData(lat, lang) {
        return $http.get("https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lang + "&units=Metric&appid=" + weatherAppId);
    }

    function saveVenueInfo(postData) {
        return httpService.post("/Api/Client/Assessment/SaveVenueInfo", postData);
    }

    function submitAssessment(postData) {
        return httpService.post("/Api/Client/Assessment/Submit", postData);
    }

    function getSharedAssessmentbyVenue(id) {
        return httpService.get("/Api/Client/Assessment/GetSharedUsersListByVenue?id=" + id);
    }

    function getMetadata(id) {
        return httpService.get("/Api/Client/Assessment/GetMetadata?assessmentTypeId=" + id);
    }


    this.setAssessmentType = setAssessmentType;
    this.getAssessmentType = getAssessmentType;
    this.editAssessmentRequest = editAssessmentRequest;
    this.deleteAssessmentRequest = deleteAssessmentRequest;
    this.getAssessmentList = getAssessmentList;
    this.createAssessmentRequest = createAssessmentRequest;
    this.getAssessmentInfoById = getAssessmentInfoById;

    this.getSharedAssessmentbyVenue = getSharedAssessmentbyVenue;
    this.getMetadata = getMetadata;
    this.saveVenueInfo = saveVenueInfo;
    this.getWeatherData = getWeatherData;
    this.submitAssessment = submitAssessment;

});
app.service('supportServices', function (httpService, $cookies) {


    function getQueries(postData) {
        return httpService.post("/Api/Client/Support/web/List", postData);
    }

    function saveSupportQuery(postData) {
        return httpService.post("/Api/Client/Support/Create", postData);
    }

    function threadList(id) {
        return httpService.get("/Api/Client/Support/ThreadList?parentId=" + id);
    }

    this.getQueries = getQueries;
    this.saveSupportQuery = saveSupportQuery;
    this.threadList = threadList;
});
app.service('commonServices', function (httpService, $cookies) {

    function uploadDocument(postData) {
        return httpService.fileUpload("/Api/Client/UploadDocument", postData);
    }
    function saveBrowserToken(postData) {
        return httpService.post("/api/Client/BrowserToken", postData);
    }
    this.uploadDocument = uploadDocument;
    this.saveBrowserToken = saveBrowserToken;
});
app.service('messageServices', function (httpService, $cookies) {


    function getQueries(postData) {
        return httpService.post("/Api/Client/Message/web/List", postData);
    }

    function saveMessageQuery(postData) {
        return httpService.post("/Api/Client/Message/Create", postData);
    }

    function threadList(id) {
        return httpService.get("/Api/Client/Message/ThreadList?parentId=" + id);
    }

    function GetMessageUsers() {
        return httpService.get("/Api/Client/Message/GetMessageUsers");
    }

    this.getQueries = getQueries;
    this.saveMessageQuery = saveMessageQuery;
    this.threadList = threadList;
    this.GetMessageUsers = GetMessageUsers;
});
app.service("faqServices", function (httpService, $cookies) {
    function getFaqList() {
        return httpService.get("/Api/Client/FAQ/List");
    }


    this.getFaqList = getFaqList;
});
app.service('reportServices', function (httpService, $cookies) {

    function getByVenueId(id) {
        return httpService.get("/Api/Client/Report/GetByVenueId?venueId=" + id);
    }
    function GetMatchDayByVenueId(id) {
        return httpService.get("/Api/Client/Report/GetMatchDayByVenueId?venueId=" + id);
    }
    function GetMatchDayWithPaggingByVenueId(postData) {
        console.log("Post");
        console.log(postData);
        return httpService.post("/Api/Client/Report/GetMatchDayWithPaggingByVenueId", postData);
    }
    function getReportDetailById(id) {
        return httpService.get("/Api/Client/Report/GetDetailById?id=" + id);
    }
    function getAssessemntReportSummuryById(id) {
        return httpService.get("/Api/Client/Report/GetSummaryById?id=" + id);
    }
    function getImages(assessmentRequestId) {
        return httpService.get("/Api/Client/Assessment/GetImages?assessmentRequestId=" + assessmentRequestId);
    }
    function downloadReport(id) {
        return httpService.get("/Api/Client/DownloadReport?id=" + id);
    }
    function downloadMatchDayReport(id) {
        return httpService.get("/Api/Client/DownloadMatchDayReport?id=" + id);
    }
    function sendReportToMail(postData) {
        return httpService.post("/Api/Client/ReportSendOnMail", postData);
    }

    function getReportsByVenueId(id) {
        return httpService.get("/Api/Client/Report/GetByVenueId?venueId=" + id);
    }

    function getCommentsByReportId(id) {
        return httpService.get("/Api/Client/Report/Comments?reportId=" + id);
    }

    function AddCommentOnReports(postData) {
        return httpService.post("/Api/Client/Report/AddComment", postData);
    }

    function getReportSummaryPageDetail(id) {
        return httpService.get("/Api/Client/ReportSummaryPageDetail?reportId=" + id);
    }

    function filterRatingGraph(postData) {
        return httpService.post("/Api/Client/Report/FilterRatingGraph", postData);
    }

    function filterCustomRatingGraph(postData) {
        return httpService.post("/Api/Client/Report/FilterCustomRatingGraph", postData);
    }

    function filterQuestionRatingGraph(postData) {
        return httpService.post("/Api/Client/Report/FilterQuestionRatingGraph", postData);
    }

    this.filterQuestionRatingGraph = filterQuestionRatingGraph;
    this.filterCustomRatingGraph = filterCustomRatingGraph;
    this.sendReportToMail = sendReportToMail;
    this.downloadReport = downloadReport;
    this.downloadMatchDayReport = downloadMatchDayReport;
    this.getImages = getImages;
    this.getByVenueId = getByVenueId;
    this.getReportDetailById = getReportDetailById;
    this.getAssessemntReportSummuryById = getAssessemntReportSummuryById;
    this.getReportsByVenueId = getReportsByVenueId;
    this.getCommentsByReportId = getCommentsByReportId;
    this.AddCommentOnReports = AddCommentOnReports;
    this.getReportSummaryPageDetail = getReportSummaryPageDetail;
    this.filterRatingGraph = filterRatingGraph;

    this.GetMatchDayByVenueId = GetMatchDayByVenueId;
    this.GetMatchDayWithPaggingByVenueId = GetMatchDayWithPaggingByVenueId;
});
app.service('pitchMatterService', function (httpService) {

    function getPitchMatterByVenueId(postData) {
        return httpService.post("/Api/Client/PitchMatters", postData);
    }

    function updatePitchMatter(postData) {
        return httpService.post("/Api/Client/PitchMatter/Edit", postData);
    }

    this.getPitchMatterByVenueId = getPitchMatterByVenueId;
    this.updatePitchMatter = updatePitchMatter;
});
app.service('notificationServices', function (httpService, $cookies) {


    function getNotifications(id) {
        return httpService.get("/Api/Client/Notification/List");
    }
       
    function updateNotificationStatus(id) {
        return httpService.post("/Api/Client/Notification/UpdateReadStatus?id=" + id);
    }

    function deleteNotifications(ids) {
        return httpService.post("/Api/Client/Notification/Delete?ids=" + ids);
    }
    this.getNotifications = getNotifications;
    this.updateNotificationStatus = updateNotificationStatus;
    this.deleteNotifications = deleteNotifications;
});
app.service('membershipServices', function (httpService, $cookies) {


    function getPlans(id) {
        return httpService.get("/Api/Client/Membership/GetPlans");
    }

    function detail(postData) {
        return httpService.get("/Api/Client/Membership/Detail");
    }

    function payment(postData) {
        return httpService.post("/Api/Client/Membership/Payment", postData);
    }

    function AddonPayment(postData) {

        return httpService.post("/Api/Client/Membership/AddOnPayment", postData);
    }

    function getClientToken() {
        return httpService.get("/Api/Client/Membership/GetClientToken");
    }

    function unsubscribe(postData) {
        return httpService.post("/Api/Client/Membership/Unsubscribe", postData);
    }

    function SendMail(postData) {
        return httpService.post("/Api/Client/Membership/EmailNotification", postData);
    }

    this.unsubscribe = unsubscribe;
    this.payment = payment;
    this.getPlans = getPlans;
    this.detail = detail;
    this.getClientToken = getClientToken;
    this.AddonPayment = AddonPayment;
    this.SendMail = SendMail;
});
app.controller("loginController", function ($scope, userServices, $state, $rootScope, $location) {
    $scope.user = {
        grant_type: 'password'
    };

    userServices.removeCookies();
    $location.replace("");

    $scope.login = function (form) {
        if (form) {
            userServices.login($scope.user).then(function (res, err) {
                userServices.setCookie(res.data);
                $scope.GetUserDetail(res.data.userName);
            }, function errorCallback(response) {
                toastr.error(response.data.error_description, "Error");
                $rootScope.isLoading = false;
            });
        }
    }

    $scope.GetUserDetail = function (email) {
        userServices.getUserDetail(email).then(function (res, err) {
            userServices.saveUserDetail(res.Data);
            $state.go('user.dashboard');
        });
    }
});
app.controller("registrationController", function ($scope, userServices, $state, $rootScope) {
    $scope.user = {
        IsTermAndConditionAccepted: false
    };

    userServices.removeCookies();

    $scope.registration = function (form) {
        if ($scope.user.Password !== $scope.user.ConfirmPassword) {
            return false;
        }

        if (form) {
            userServices.registration($scope.user).then(function (res, err) {
                toastr.success("User registered successfully", "Success");

                $state.go('home.login');
            });
        }
    }

});
app.controller("forgotPasswordController", function ($scope, userServices, $state) {

    $scope.handleSubmit = function (form) {
        if (form) {
            userServices.forgotPassword($scope.email).then(function (res, err) {
                toasterType = "success";
                toasterText = "Email Sent Successfully";
                toastr.success(toasterText, toasterType);
                $state.go('home.login');
            });
        }
    }
});
app.controller("venueController", function ($scope, venueServices, $window, $location) {
    $location.replace("");
    $scope.canCreate = false;
    $scope.headings = [
        { headingName: "VenueId", name: "Id", orderBy: 0 },
        { headingName: "VenueName", name: "Venue Name", orderBy: 1 },
        { headingName: "CompleteAddress", name: "Address", orderBy: 0 },
        { headingName: "City", name: "City", orderBy: 0 },
        { headingName: "TypeofSport", name: "Sports Type", orderBy: 0 },
        { headingName: "Grounds Manager", name: "Grounds Manager", orderBy: 3},
        { headingName: "ApprovalStatus", name: "Approval Status", orderBy: 0 },
        { headingName: "Status", name: "Status", orderBy: 3 },
        { headingName: "Action", name: "Action", orderBy: 3 }
    ];
    function init() {
        $scope.clientGroundManager = [];
        $scope.venues = [];
        $scope.filter = {
            page: 1,
            PageSize: '10',
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };
        $scope.pageCount = 0;
        $scope.getVenues();
        $scope.canCreate = true;
        venueServices.CanActiveOrCreateVenue().then(function (res) {
            if (res.IsSuccess) {
                $scope.canCreate = true;
              /*  $scope.getVenues();*/
               // $scope.getGroundMans();
            }
        });
    }

    $scope.getVenues = function () {
        venueServices.getVenuesList($scope.filter).then(function (res) {
            $scope.venues = res.Data.Venues;
            $scope.pageCount = res.Data.PageCount;
            $scope.venue = {};
        });
    }

    $scope.disableVenue = function (venue) {
        var text = venue.IsActive ? "deactivate" : "activate"
        if (venue.IsActive) {
            toastr.success("Please contact to admin for deactive venue.", "Warning");
        } else {
            if ($window.confirm("Do you want to " + text + " this venue")) {
                $scope.Message = "You clicked YES.";
                venueServices.activeDeactiveVenue(venue.Id).then(function (res) {
                    if (res.IsSuccess) {
                        $scope.getVenues();
                     /*   init();*/
                    } else {
                        toastr.info(res.Message);
                    }
                });
            }
        }
    }

    $scope.clearFilters = function () {
        init();
    }

    $scope.searchVenue = function () {
        $scope.filter.Search = JSON.stringify($scope.search);
        $scope.getVenues();

    }

    $scope.deleteVenue = function (id) {
        if ($window.confirm("Are you sure you want to delete this venue?")) {
            venueServices.deleteVenue(id).then(function (res) {
                $scope.getVenues();
            });
        }
    }

    $scope.pageChanged = function () {
        $scope.getVenues();
    }

    $scope.getGroundMans = function () {
        var filter = {
            page: 0,
            PageSize: '1000',
            Search: null,
            orderBy: null,
            orderByAsc: 2,
            IsPostBack: false
        };
        venueServices.getGroundManagers(filter).then(function (res) {
            $scope.clientGroundManager = res.Data.Data;
        });
    }

    $scope.sortVenueDetails = function (index) {
        if ($scope.headings[index].orderBy < 3) {
            angular.forEach($scope.headings, function (value, key) {
                if (key === index) {
                    value.orderBy = value.orderBy === 0 || value.orderBy === 2 ? 1 : 2;
                } else if(value.orderBy !== 3) {
                    value.orderBy = 0;
                }
            });

            $scope.filter.orderByAsc = $scope.headings[index].orderBy;
            $scope.filter.orderBy = $scope.headings[index].headingName;
            $scope.filter.page = 1;
            $scope.getVenues();
        }
    }

    init();
});
app.controller("ManageVenueController", function ($scope, $window, venueServices, $state, commonServices, $stateParams) {

    $scope.countries = [];
    $scope.constructionTypes = [];
    $scope.venue = {};
    $scope.center = [51.53010529323175, -0.11055069726558031];
    $scope.latlng = [51.53010529323175, -0.11055069726558031];
    $scope.venue.Latitude = "51.53010529323175";
    $scope.venue.Longitude = "-0.11055069726558031";
    $scope.file = undefined;
    let isfirsttimeLoad = true;

    $scope.onSelectFile = function (model) {
        $scope.file = model.files[0];
        var extension = $scope.file.name.split(".")[$scope.file.name.split(".").length - 1];

        var validFormats = ['png', 'jpeg', 'jpg'];
        if (validFormats.indexOf(extension.toLowerCase()) === -1) {
            $scope.file = {};
            toastr.warning("Only png, jpeg, jpg format file acceptable", "Information");
            angular.element("input[type='file']").val(null);
        }

        if (!angular.isUndefined($scope.file)) {
            var formData = new FormData();
            formData.append("file", $scope.file);
            formData.append("extension", $scope.file.name.split(".")[$scope.file.name.split(".").length - 1]);
            formData.append("type", "VenueImage");

            commonServices.uploadDocument(formData).then(function (res) {
                $scope.venue.ImageUrl = res.Data;
                // saveVenueDetail();
            });
        }
    }
    $scope.onSelectMapFile = function (model) {

        $scope.mapFile = model.files[0];
        console.log($scope.mapFile);
        var extension = $scope.mapFile.name.split(".")[$scope.mapFile.name.split(".").length - 1];

        var validFormats = ['png', 'jpeg', 'jpg'];
        if (validFormats.indexOf(extension.toLowerCase()) === -1) {
            $scope.mapFile = {};
            toastr.warning("Only png, jpeg, jpg format file acceptable", "Information");
            angular.element("input[type='file']").val(null);
        }
        if (!angular.isUndefined($scope.mapFile)) {
            var formData = new FormData();
            formData.append("file", $scope.mapFile);
            formData.append("extension", $scope.mapFile.name.split(".")[$scope.mapFile.name.split(".").length - 1]);
            formData.append("type", "VenueImage");

            commonServices.uploadDocument(formData).then(function (res) {
                $scope.venue.VenueMapImage = res.Data;
                console.log($scope.venue.VenueMapImage);
                //saveVenueDetail();
            });
        }
    }
    $scope.getCountryList = function () {
        venueServices.getCountryList().then(function (res) {
            $scope.countries = res.Data;
        });
    }


    $scope.deleteVenueImage = function (id, type) {
        if (confirm("Are you sure you want to delete this image?")) {
            venueServices.DeleteVenueImage(id, type).then(function (res) {
                alert("Image deleted successfully.");
                $state.go('user.venues');
            }).catch(function (error) {
                console.error("Error deleting image:", error);
                alert("An error occurred while deleting the image.");
            });
        }
    };

    $scope.getConstructionTypesList = function () {
        venueServices.getConstructionTypesList().then(function (res) {
            $scope.constructionTypes = res.Data;
        });
    }

    function codeLatLng(lat, lng) {
        var city = {};
        var country = {};
        var geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(lat, lng);
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                console.log(results)
                if (results[1]) {
                    //formatted address

                    //find country name
                    for (var i = 0; i < results[0].address_components.length; i++) {
                        for (var b = 0; b < results[0].address_components[i].types.length; b++) {

                            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                            if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
                                //this is the object you are looking for
                                city = results[0].address_components[i];
                                break;
                            }
                            if (results[0].address_components[i].types[b] == "country") {
                                country = results[0].address_components[i];
                                break;
                            }
                        }
                    }
                    //city data
                    if (!isfirsttimeLoad) {
                        $scope.venue.CompleteAddress = results[0].formatted_address;
                        console.log(city.short_name + " " + city.long_name)
                        $scope.venue.City = city.short_name;
                    }
                    isfirsttimeLoad = false;
                    setCountryID(country.long_name);
                    $scope.$apply();
                } else {
                    console.log("No results found");
                }
            } else {
                console.log("Geocoder failed due to: " + status);
            }
        });
    }
    codeLatLng($scope.venue.Latitude, $scope.venue.Longitude);

    function setCountryID(countryName) {
        angular.forEach($scope.countries, function (value) {
            if (value.Name.trim().toLowerCase() == countryName.trim().toLowerCase()) {
                $scope.venue.CountryID = value.Id + "";
            }
        });
    }

    $scope.getpos = function (event) {
        $scope.latlng = [event.latLng.lat(), event.latLng.lng()];
        $scope.venue.Latitude = event.latLng.lat() + "";
        $scope.venue.Longitude = event.latLng.lng() + "";
        codeLatLng($scope.venue.Latitude, $scope.venue.Longitude);
    };

    $scope.setMarker = function () {
        $scope.center = [$scope.venue.Latitude, $scope.venue.Longitude];
        $scope.latlng = [$scope.venue.Latitude, $scope.venue.Longitude];
        codeLatLng($scope.venue.Latitude, $scope.venue.Longitude);
    }

    $scope.update = function (form) {
        if ($window.confirm("Do you want to update this venue. Admin will be approve this venue again!")) {
            $scope.handleSubmit(form);
        }
    }

    $scope.handleSubmit = function (form) {
        if (form) {
            $scope.venue.TypeofConstruction = $scope.venue.TypeofConstruction + "";
            $scope.venue.CountryID = $scope.venue.CountryID + "";
            if (!angular.isUndefined($scope.file)) {
                var formData = new FormData();
                formData.append("file", $scope.file);
                formData.append("extension", $scope.file.name.split(".")[$scope.file.name.split(".").length - 1]);
                formData.append("type", "VenueImage");
                saveVenueDetail();

                //Commented this code due to this function Called 2 times which is make a diffrent file name is Azure

                //commonServices.uploadDocument(formData).then(function (res) {
                //    $scope.venue.ImageUrl = res.Data;
                //    saveVenueDetail();
                //});
            } else {
                saveVenueDetail();
            }
        }
    }

    function saveVenueDetail() {
        venueServices.manageVenueDetail($scope.venue).then(function (res) {
            toastr.success("Venue detail saved Successfully", "Success");
            $state.go('user.venues');
        });
    }
    $scope.checkLength = function ($event) {
        // $event.target.blur();
        console.log($event.target.value);
        console.log("$event.target.value");
        //$event.target.blur();
        // console.log($event);

        if ($event.target.value && $event.target.value.length >= 50) {
            $event.target.value = "";
            alert("Length must be less then 50 characters.")
            return false;
        }
    }
    $scope.editVenue = function () {
        if ($stateParams.index) {
            venueServices.getVenueDetailById($stateParams.index).then(function (res) {
                $scope.venue = res.Data;
                $scope.venue.TypeofConstruction = res.Data.TypeofConstruction + "";
                $scope.venue.CountryID = res.Data.CountryID + "";
                $scope.venue.Hemisphere = res.Data.Hemisphere.trim();
                $scope.latlng = [res.Data.Latitude, res.Data.Longitude];
                $scope.center = [res.Data.Latitude, res.Data.Longitude];
                codeLatLng(res.Data.Latitude, res.Data.Longitude);

            });
        }
    }

    function loadMapAutoComplete() {
        var input = document.getElementById('searchTextField');
        var autocomplete = new google.maps.places.Autocomplete(input);

        google.maps.event.addListener(autocomplete, 'place_changed', function () {

            var place = autocomplete.getPlace();
            $scope.venue.Latitude = place.geometry.location.lat();
            $scope.venue.Longitude = place.geometry.location.lng();
            $scope.setMarker();
            console.log(lat + ", " + long);
        });
    }

    loadMapAutoComplete();
    $scope.getCountryList();
    $scope.getConstructionTypesList();
    $scope.editVenue();
});
app.controller("groundManListController", function ($scope, groundManagerServices, venueServices, $state, $window) {
    $scope.venues = [];
    $scope.headings = [
        { headingName: "GroundManagerId", name: "Id", orderBy: 0 },
        { headingName: "AspNetUser.FirstName", name: "Name", orderBy: 1 },
        { headingName: "AspNetUser.Email", name: "Email", orderBy: 0 },
        { headingName: "AspNetUser.PhoneNumber", name: "Phone Number", orderBy: 0 },
        //{ headingName: "tblVenue.VenueName", name: "Venue Name", orderBy: 0 },
        { headingName: "Action", name: "Action", orderBy: 3 }
    ];

    function init() {
        $scope.groundManagers = [];
        $scope.filter = {
            page: 0,
            PageSize: "10",
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };
        $scope.pageCount = 1;

        $scope.search = {
            tblVenueId: "",
            FirstName: "",
            Email: "",
            PhoneNumber: "",
            IsApproved: ""
        };
        $scope.getGroundManagers();
        $scope.getVenues();

    }

    $scope.getGroundManagers = function () {
        groundManagerServices.getGroundManagers($scope.filter).then(function (res) {
            $scope.groundManagers = res.Data.Data;
            $scope.pageCount = res.Data.NumberOfPages * $scope.filter.PageSize;
            $scope.filter.page = res.Data.CurrentPage;

        });
    }

    $scope.clearFilters = function () {
        init();
    }

    $scope.searchGroundManager = function () {
        var postdata = {
            "AspNetUser.FirstName": angular.isUndefined($scope.search.FirstName) ? "" : $scope.search.FirstName,
            "AspNetUser.Email": angular.isUndefined($scope.search.Email) ? "" : $scope.search.Email,
            "AspNetUser.PhoneNumber": angular.isUndefined($scope.search.PhoneNumber) ? "" : $scope.search.PhoneNumber,
            "tblVenueId": angular.isUndefined($scope.search.tblVenueId) ? "" : $scope.search.tblVenueId,
            //"IsApproved": angular.isUndefined($scope.search.IsApproved) ? "" : $scope.search.IsApproved
        };
        $scope.filter.Search = JSON.stringify(postdata);
        $scope.getGroundManagers();
    }

    $scope.deleteGroundManager = function (id) {
        if (!$window.confirm("Are you want to delete this record?")) {
            return false;
        }
        groundManagerServices.deleteGroundManager(id).then(function (res) {
            $scope.getGroundManagers();
        });
    }

    $scope.getVenues = function () {
        var filter = {
            page: 0,
            PageSize: '1000',
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };
        venueServices.getVenuesList(filter).then(function (res) {
            $scope.venues = res.Data.Venues;
        });
    }

    $scope.sortDetails = function (index) {
        if ($scope.headings[index].orderBy < 3) {
            angular.forEach($scope.headings, function (value, key) {
                if (key === index) {
                    value.orderBy = value.orderBy === 0 || value.orderBy === 2 ? 1 : 2;
                } else if (value.orderBy !== 3) {
                    value.orderBy = 0;
                }
            });

            $scope.filter.orderByAsc = $scope.headings[index].orderBy;
            $scope.filter.orderBy = $scope.headings[index].headingName;
            $scope.filter.page = 1;
            $scope.searchGroundManager();
        }
    }
    $scope.pageChanged = function () {
        $scope.getGroundManagers();
    }
    init();
    //Created on 24-mar-22, show edit when Gm vanues are same as login user vanues
    $scope.IsShowVenue = function (groundMan) {
        var isReturn = false;
        var subclientVanues = $scope.venues;
        console.log("subclientVanues");
        console.log(subclientVanues);
        var gmVanues = groundMan.GroundManagerVenues;
        console.log("gmVanues");
        console.log(gmVanues);
        var subClientMatchid = [];

        angular.forEach(gmVanues, function (gvalue, key) {
            angular.forEach(subclientVanues, function (svalue, key1) {
                if (gvalue.VenueId == svalue.Id) {
                    subClientMatchid.push(svalue.Id);
                }
            });
        });
        if (subClientMatchid.length == gmVanues.length) {
            isReturn = true;
            return isReturn;
        }
        console.log("subClientMatchid");
        console.log(subClientMatchid);
        return isReturn;

    }
    //
});
app.controller("groundManCreateController", function ($scope, groundManagerServices, venueServices, $state, $stateParams) {

    $scope.groundManager = {};
    $scope.file = {};
    $scope.venues = [];

    $scope.onSelectFile = function (model) {
        $scope.file = model.files[0];
        var extension = $scope.file.name.split(".")[$scope.file.name.split(".").length - 1];
        var validFormats = ['png', 'jpeg', 'jpg'];

        if (validFormats.indexOf(extension.toLowerCase()) == -1) {
            $scope.file = {};
            angular.element("input[type='file']").val(null);
            toastr.warning("Only png, jpeg, jpg format file acceptable", "Information");
            return false;
        } 

    }

    $scope.handleSubmit = function (form) {
        if (form) {
            console.log("button click");
            var formData = new FormData();
            formData.append("object", JSON.stringify($scope.groundManager));
            formData.append("file", $scope.file);

            groundManagerServices.createGroundMan(formData).then(function (res, err) {
                $state.go('user.groundManager');
            });
        }
    }
    $scope.checkLength = function ($event) {
        // $event.target.blur();
        console.log($event.target.value);
        console.log("$event.target.value");
        //$event.target.blur();
        // console.log($event);

        if ($event.target.value && $event.target.value.length >= 20) {
            $event.target.value = "";
            alert("Length must be less then 20 characters.")
            return false;
        }
    }
    $scope.GetGroundManagerById = function () {
        if ($stateParams.index) {
            groundManagerServices.getGroundManagerById($stateParams.index).then(function (res) {
                $scope.groundManager = res.Data;
                console.log("$scope.groundManager");
                console.log($scope.groundManager);
                $scope.groundManager.TempEmail = res.Data.Email;
                $scope.groundManager.VenueId = res.Data.VenueId + "";
            });
        }
    }

    $scope.getVenues = function () {
        var filter = {
            page: 0,
            PageSize: '99999',
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };
        venueServices.getVenuesList(filter).then(function (res) {
            console.log("res");
            console.log(res.Data);
            $scope.venues = res.Data.Venues;
            $scope.GetGroundManagerById();
        });
    }

    $scope.getVenues();
});
app.controller("ManageSubClientController", function ($scope, subClientServices, $state, $stateParams, venueServices) {

    $scope.client = {};
    $scope.file = {};
    $scope.venues = [];
    $scope.userType = [];


    $scope.example14model = [];
    $scope.example14settings = {
        scrollableHeight: '200px',
        scrollable: true,
        enableSearch: true
    };    
    //$scope.example14data = [{
    //    "label": "Alabama",
    //    "id": "AL"
    //}, {
    //    "label": "Alaska",
    //    "id": "AK"
    //}, {
    //    "label": "American Samoa",
    //    "id": "AS"
    //}, {
    //    "label": "Arizona",
    //    "id": "AZ"
    //}, {
    //    "label": "Arkansas",
    //    "id": "AR"
    //}, {
    //    "label": "California",
    //    "id": "CA"
    //}, {
    //    "label": "Colorado",
    //    "id": "CO"
    //}, {
    //    "label": "Connecticut",
    //    "id": "CT"
    //}, {
    //    "label": "Delaware",
    //    "id": "DE"
    //}, {
    //    "label": "District Of Columbia",
    //    "id": "DC"
    //}, {
    //    "label": "Federated States Of Micronesia",
    //    "id": "FM"
    //}, {
    //    "label": "Florida",
    //    "id": "FL"
    //}, {
    //    "label": "Georgia",
    //    "id": "GA"
    //}, {
    //    "label": "Guam",
    //    "id": "GU"
    //}, {
    //    "label": "Hawaii",
    //    "id": "HI"
    //}, {
    //    "label": "Idaho",
    //    "id": "ID"
    //}, {
    //    "label": "Illinois",
    //    "id": "IL"
    //}, {
    //    "label": "Indiana",
    //    "id": "IN"
    //}, {
    //    "label": "Iowa",
    //    "id": "IA"
    //}, {
    //    "label": "Kansas",
    //    "id": "KS"
    //}, {
    //    "label": "Kentucky",
    //    "id": "KY"
    //}, {
    //    "label": "Louisiana",
    //    "id": "LA"
    //}, {
    //    "label": "Maine",
    //    "id": "ME"
    //}, {
    //    "label": "Marshall Islands",
    //    "id": "MH"
    //}, {
    //    "label": "Maryland",
    //    "id": "MD"
    //}, {
    //    "label": "Massachusetts",
    //    "id": "MA"
    //}, {
    //    "label": "Michigan",
    //    "id": "MI"
    //}, {
    //    "label": "Minnesota",
    //    "id": "MN"
    //}, {
    //    "label": "Mississippi",
    //    "id": "MS"
    //}, {
    //    "label": "Missouri",
    //    "id": "MO"
    //}, {
    //    "label": "Montana",
    //    "id": "MT"
    //}, {
    //    "label": "Nebraska",
    //    "id": "NE"
    //}, {
    //    "label": "Nevada",
    //    "id": "NV"
    //}, {
    //    "label": "New Hampshire",
    //    "id": "NH"
    //}, {
    //    "label": "New Jersey",
    //    "id": "NJ"
    //}, {
    //    "label": "New Mexico",
    //    "id": "NM"
    //}, {
    //    "label": "New York",
    //    "id": "NY"
    //}, {
    //    "label": "North Carolina",
    //    "id": "NC"
    //}, {
    //    "label": "North Dakota",
    //    "id": "ND"
    //}, {
    //    "label": "Northern Mariana Islands",
    //    "id": "MP"
    //}, {
    //    "label": "Ohio",
    //    "id": "OH"
    //}, {
    //    "label": "Oklahoma",
    //    "id": "OK"
    //}, {
    //    "label": "Oregon",
    //    "id": "OR"
    //}, {
    //    "label": "Palau",
    //    "id": "PW"
    //}, {
    //    "label": "Pennsylvania",
    //    "id": "PA"
    //}, {
    //    "label": "Puerto Rico",
    //    "id": "PR"
    //}, {
    //    "label": "Rhode Island",
    //    "id": "RI"
    //}, {
    //    "label": "South Carolina",
    //    "id": "SC"
    //}, {
    //    "label": "South Dakota",
    //    "id": "SD"
    //}, {
    //    "label": "Tennessee",
    //    "id": "TN"
    //}, {
    //    "label": "Texas",
    //    "id": "TX"
    //}, {
    //    "label": "Utah",
    //    "id": "UT"
    //}, {
    //    "label": "Vermont",
    //    "id": "VT"
    //}, {
    //    "label": "Virgin Islands",
    //    "id": "VI"
    //}, {
    //    "label": "Virginia",
    //    "id": "VA"
    //}, {
    //    "label": "Washington",
    //    "id": "WA"
    //}, {
    //    "label": "West Virginia",
    //    "id": "WV"
    //}, {
    //    "label": "Wisconsin",
    //    "id": "WI"
    //}, {
    //    "label": "Wyoming",
    //    "id": "WY"
    //}];
    $scope.example2settings = {
        displayProp: 'id'
    };

    $scope.onSelectFile = function (model) {
        $scope.file = model.files[0];
        var extension = $scope.file.name.split(".")[$scope.file.name.split(".").length - 1]
        var validFormats = ['png', 'jpeg', 'jpg'];
        if (validFormats.indexOf(extension.toLowerCase()) == -1) {
            $scope.file = {};
            angular.element("input[type='file']").val(null);
            toastr.warning("Only png, jpeg, jpg format file acceptable", "Information");
        }
    }

    $scope.handleSubmit = function (form) {
        if (form) {
            console.log("button click");
            var formData = new FormData();
            formData.append("object", JSON.stringify($scope.client));
            formData.append("file", $scope.file);

            subClientServices.createSubClient(formData).then(function (res, err) {
                toastr.success("User detail saved Successfully", "Success");
                $state.go('user.subClient');
            });
        }
    }

    $scope.GetSubClientById = function () {
        if ($stateParams.index) {
            subClientServices.getSubClientById($stateParams.index).then(function (res) {
                $scope.client = res.Data;
                console.log($scope.client);
                $scope.client.UserTypeValue = res.Data.UserTypeValue + "";
            });
        }
    }
    $scope.getAllUserType = function () {
        subClientServices.getUserType().then(function (res) {
            console.log("res.Data");
            console.log(res.Data);
            $scope.userType = res.Data;
           

        });
    }
    //$scope.getVenues = function () {
    //    var filter = {
    //        page: 0,
    //        PageSize: '10',
    //        Search: null,
    //        orderBy: null,
    //        orderByAsc: 1,
    //        IsPostBack: false
    //    };
    //    venueServices.getVenuesList(filter).then(function (res) {
    //        //$scope.venues = res.Data.Venues;
    //        var newArr = jQuery.map(res.Data.Venues, function (val, index) {
    //            console.log(val);
    //            return {
    //                "label": val.VenueName,
    //                "id": ""+val.Id
                    
    //            };
    //        })
    //        //$scope.example14model = JSON.stringify(newArr);
    //        $scope.example14data=newArr;
    //        console.log($scope.example14model);
                       
    //    });
    //}

    $scope.getVenues = function () {
        var filter = {
            page: 0,
            PageSize: '99999',
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };
        venueServices.getVenuesList(filter).then(function (res) {
            $scope.venues = res.Data.Venues;
            $scope.GetSubClientById();
        });
    }
    $scope.getVenues();
    $scope.GetSubClientById();
    $scope.getAllUserType();
});
app.controller("SubClientListController", function ($scope, subClientServices, $state, $window, userServices) {
    function init() {
        $scope.subClients = [];
        $scope.user = userServices.getCurentUser();

        $scope.search = {
            Id: "",
            FirstName: "",
            Email: "",
            PhoneNumber: "",
            IsApproved: ""
        };

        $scope.filter = {
            page: 1,
            PageSize: "10",
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };

        $scope.pageCount = 0;

        $scope.getSubClients();
    }

    $scope.getSubClients = function () {
        subClientServices.getSubClients($scope.filter).then(function (res) {
            console.log("res=>", res);
            $scope.subClients = res.Data.Clients;
            $scope.pageCount = res.Data.PageCount;
        });
    }

    $scope.clearFilters = function () {
        init();
    }

    $scope.searchSubClients = function () {
        var postdata = {
            "AspNetUser.FirstName": $scope.search.FirstName,
            "AspNetUser.Email": $scope.search.Email,
            "AspNetUser.PhoneNumber": $scope.search.PhoneNumber,
            "Id": $scope.search.Id,
            "IsApproved": $scope.search.IsApproved,
        };

        $scope.filter.Search = JSON.stringify(postdata);
        $scope.getSubClients();
    }

    $scope.deleteSubClient = function (id) {
        subClientServices.deleteSubClient(id).then(function (res) {
            $scope.getSubClients();
        });
    }

    $scope.disableSubClient = function (subClient) {
        var text = subClient.IsActive ? "deactivate" : "activate"

        if ($window.confirm("Do you want to " + text + " this User")) {
            subClientServices.disableSubClient(subClient.UserId).then(function (res) {
                $scope.getSubClients();
            });
        }
    }

    $scope.pageChanged = function () {
        $scope.getSubClients();
    }

    init();
});
app.controller("ManageProfileController", function ($scope, userServices, subClientServices, $state, $uibModal, folderPath) {
    $scope.user = userServices.getCurentUser();
    $scope.user.UserTypeValue = $scope.user.UserTypeValue + "";
    $scope.file = {};

    $scope.onSelectFile = function (model) {
        $scope.file = model.files[0];
        var extension = $scope.file.name.split(".")[$scope.file.name.split(".").length - 1];

        var validFormats = ['png', 'jpeg', 'jpg'];
        if (validFormats.indexOf(extension.toLowerCase()) === -1) {
            $scope.file = {};
            toastr.warning("Only png, jpeg, jpg format file acceptable", "Information");
            angular.element("input[type='file']").val(null);
        } 
    }

    $scope.handleSubmit = function (form) {
        if (form) {
            console.log("button click");
            var formData = new FormData();
            formData.append("object", JSON.stringify($scope.user));
            formData.append("file", $scope.file);

            subClientServices.createSubClient(formData).then(function (res, err) {
                $scope.GetUserDetail($scope.user.Email);

            });
        }
    }
    $scope.GetUserDetail = function (email) {
        userServices.getUserDetail(email).then(function (res, err) {
            userServices.saveUserDetail(res.Data);
            $state.go('user.manageProfile', {}, { reload: true });
        });
    }
    $scope.open = function () {
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/ChangePassword.html",
            controller: "ChangePasswordCtrl",
            size: '',
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });

    }
});

app.controller('ChangePasswordCtrl', function ($scope, $uibModalInstance, userServices) {

    $scope.isSubmit = false;
    $scope.user = {};

    $scope.update = function (form) {
        $scope.isSubmit = form;
        if (form) {
            $scope.user.Email = userServices.getCurentUser().Email;
            if ($scope.user.NewPassword === $scope.user.ConfirmPassword) {
                userServices.changePassword($scope.user).then(function (res, err) {
                    toastr.success(res.Message, "Success");
                    $scope.cancel();
                });
            }
        }
    }

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }

});
app.controller("mainController", function ($scope, $rootScope, userServices, notificationServices, $state, commonServices, baseUrl, $location) {
    $scope.user = userServices.getCurentUser();
    $scope.toggleNavigation = localStorage.getItem('ExpandLeftmenu') || 0;

    $scope.onClickToggleNavigation = function () {

        if (localStorage.getItem('ExpandLeftmenu') == 1) {
            localStorage.setItem('ExpandLeftmenu', 0);
            $scope.toggleNavigation = 0;
        }
        else {
            localStorage.setItem('ExpandLeftmenu', 1);
            $scope.toggleNavigation = 1;

        }
        location.reload();
    }

    $scope.logout = function () {
        $state.go('home.login');
        $timeout(function () {
            location.reload();
        }, 3000);

    }
    //

    $scope.showComingSoon = function () {
        toastr.info("Coming Soon!", "Information");
    };

    $scope.HasMembership = true;

    function init() {
        $rootScope.notifications = [];
        $rootScope.getNotifications();

        $scope.handleDashboardClick = function () {
            return userServices.AllowViewReportsToSubclientIfClientHasMembershipData()
                .then(function (res, err) {
                    const data = res.Data;

                    if (!data.IsClientOfSubclientHasMembership) {
                        toastr.info("This is a paid feature. Please upgrade your membership.", "Information");
                        $scope.HasMembership = false;
                        return;
                    }
                    else
                    {
                        $scope.HasMembership = true;
                    }

                });
        };

        $scope.handleMenuClick = function (path) {
            $scope.handleDashboardClick().then(function () {
                if ($scope.HasMembership) {
                    console.log("Navigating to path:", path);
                    console.log("HasMembership is:", $scope.HasMembership);
                    window.location.hash = path;
                }
            });
        };

    }




    $rootScope.getNotifications = function () {
        notificationServices.getNotifications().then(function (res) {
            ///----Added by Deepak on date(23Aug2019)
            angular.forEach(res.Data, function (value) {
                if (value.RedirectUrl != null) {
                    let url = angular.lowercase(value.RedirectUrl);
                    if (url.indexOf("message") > -1)
                        //value.RedirectUrl = '#/messages';
                        value.RedirectUrl = '#/message';
                    else if (url.indexOf("pitchmatter") > -1 || url.indexOf("pitchmatter") > -1)
                        value.RedirectUrl = '#/pitchmatter';
                    else if (url.indexOf("support") > -1)
                        value.RedirectUrl = '#/support';
                    else if (url.indexOf("venuedocument") > -1)
                        value.RedirectUrl = "#/venueDocument";
                    else if (url.indexOf("assessment/") > -1 || url.indexOf("assessmentreport") > -1) {
                        if (value.VenueId != null && value.VenueId != '' && value.VenueId != undefined) {
                            value.RedirectUrl = '#/venuedetail/' + value.VenueId;
                        } else {
                            value.RedirectUrl = '#/venues';
                        }
                    }
                    else
                        value.RedirectUrl = '';
                } else
                    value.RedirectUrl = '';

            });
            ///----
            console.log(res);
            $rootScope.notifications = res.Data;
        });
    }

    $rootScope.updateNotificationStatus = function (id) {
        notificationServices.updateNotificationStatus(id).then(function (res) {
            console.log(res);
            $rootScope.getNotifications();
        });
    }

    //function init() {
    //    $scope.notifications = [];
    //    $scope.getNotifications();
    //}

    //$scope.getNotifications = function () {
    //    notificationServices.getNotifications().then(function (res) {
    //        $scope.notifications = res.Data;
    //    });
    //}

    //$scope.updateNotificationStatus = function (id) {
    //    notificationServices.updateNotificationStatus(id).then(function (res) {
    //        console.log(res);
    //        $scope.getNotifications();
    //    });
    //}


    function firestoreNotification() {
        console.log("firebase.messaging.isSupported() for client");
        console.log(firebase.messaging.isSupported());
        if (firebase.messaging.isSupported()) {
            const messaging = firebase.messaging();
            //navigator.serviceWorker.register(baseUrl+'/firebase-messaging-sw.js');
            navigator.serviceWorker.register(baseUrl + '/firebase-messaging-sw.js').then((registration) => {
                messaging.useServiceWorker(registration);
                messaging
                    .requestPermission()
                    .then(function () {
                        // MsgElem.innerHTML = "Notification permission granted."
                        console.log("Notification permission granted.");

                        // get the token in the form of promise
                        return messaging.getToken()
                    })
                    .then(function (token) {
                        //TokenElem.innerHTML = "token is : " + token

                        saveWebToken(token);
                    })
                    .catch(function (err) {
                        //ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
                        console.log("Unable to get permission to notify.", err);
                    });

                messaging.onMessage(function (payload) {
                    console.log("Message received. ", payload);

                    //pushNotifications(payload);
                    // var payloadData = JSON.parse(payload.data);

                    pushNotifications(payload);
                    showNotification(payload);
                    // NotisElem.innerHTML = NotisElem.innerHTML + JSON.stringify(payload)
                });
            });
        }
        else {
            //alert("your browser might not supported. Please retry again.");
        }
    }
    function pushNotifications(payload) {
        $rootScope.getNotifications();

        //var countNotification = angular.element(document.querySelector('.label-success'));
        //var client = angular.element(document.querySelector('#groud-ul'));

        //var count = (parseInt(countNotification.text())) + 1;
        //countNotification.text(count);


        //var countLi = angular.element(document.querySelector('#countli'));
        //countLi.text("You have " + (count) + " notifications");
        //var objTitle = payload.data.title;
        //var objBody = payload.data.hasOwnProperty('body') ? payload.data.body : payload.data.message;
        //var dt = GetFormattedDate(new Date());

        //if (payload.data.redirectUrl != null) {
        //    let url = angular.lowercase(payload.data.redirectUrl);
        //    if (url.indexOf("message") > -1)
        //        payload.data.redirectUrl = '#/messages';
        //    else if (url.indexOf("pitchmatter") > -1 || url.indexOf("pitchmatter") > -1)
        //        payload.data.redirectUrl = '#/notes';
        //    else if (url.indexOf("support") > -1)
        //        payload.data.redirectUrl = '#/support';
        //    else if (url.indexOf("assessment/") > -1)
        //        payload.data.redirectUrl = '#/report';
        //    else
        //        payload.data.redirectUrl = '';
        //} else
        //    payload.data.redirectUrl = '';

        //client.prepend('<li class="ng-scope" ng-repeat="query in $root.notifications"><a href="' + payload.data.redirectUrl + '" ng-click="$root.updateNotificationStatus(query.Id);"><h4 class="ng-binding">' + objTitle + '<small><i class="fa fa-clock-o"></i> ' + dt + '</small></h4><p class="ng-binding">' + objBody + '</p></a></li >');
    }
    function showNotification(payload) {
        console.log("Show notification function");
        console.log(payload);
        Notification.requestPermission(function (result) {
            if (result === 'granted') {
                //pushNotifications(payload);
                navigator.serviceWorker.ready.then(function (registration) {
                    registration.showNotification(payload.data.title, {
                        //body: payload.data.body,
                        body: payload.data.hasOwnProperty('body') ? payload.data.body : payload.data.message,
                        icon: payload.data.icon,
                        vibrate: [200, 100, 200, 100, 200, 100, 200],
                        tag: 'vibration-sample'
                    });

                });

            }
        });
    }
    function GetFormattedDate(dt) {
        var date = dt;
        monthlist = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
        var hours = date.getHours() % 12;
        var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        return date.getDate() + "-" + monthlist[date.getMonth()] + "-" + date.getFullYear() + " " + (hours < 10 ? "0" + hours : hours) + ":" + minute;
    }
    function saveWebToken(token) {
        var postdata = {
            "DeviceToken": token,
            "DeviceType": 3,

        };

        commonServices.saveBrowserToken(postdata).then(function (res, err) {
            console.log("Saved token");
            console.log(res);
        }, function errorCallback(response) {
            if (response.data != null) {
                toastr.error(response.data.error_description, "Error");
            } else {
                toastr.error("Server did not response", "Error");
            }

        });

        // $scope.filter.Search = JSON.stringify(postdata);
    }
    firestoreNotification();
    init();
});
app.controller("assessmentController", function ($scope, $rootScope, assessmentServices, venueServices, $state, $locale, $uibModal, folderPath, $window) {
    function init() {
        $scope.assessment = [];
        $scope.filter = {
            page: 0,
            PageSize: '10',
            Search: null,
            orderBy: null,
            orderByAsc: 2,
            IsPostBack: false
        };
        $scope.pageCount = 0;
        $rootScope.getAssessments();
        $rootScope.assessmentRequest = {};
        $scope.headings = [
            { headingName: "tblVenue.VenueName", name: "Venue", orderBy: 0 },
            { headingName: "RequestDate", name: "Request Date", orderBy: 1 },
            { headingName: "RequestAssessmentStatus", name: "Status", orderBy: 0 },
            { headingName: "AssessmentDate", name: "Assessment Date", orderBy: 0 },
            { headingName: "Action", name: "Action", orderBy: 3 }
        ];
    }

    $rootScope.getAssessments = function () {
        assessmentServices.getAssessmentList($scope.filter).then(function (res) {
            $scope.assessment = res.Data.Data;
            $scope.pageCount = res.Data.NumberOfPages * $scope.filter.PageSize;
            $scope.filter.page = res.Data.CurrentPage;
        });
    }


    $scope.editAssessmentRequest = function (assessmentRequest) {
        $rootScope.assessmentRequest = assessmentRequest;

        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/AssessmentPopup.html",
            controller: "EditAssessmentCtrl",
            size: '',
        });

        modalInstance.result.then(function (response) {
            $rootScope.getAssessments();
        });
    }

    $scope.deleteAssessmentRequest = function (id) {
        if ($window.confirm("Are you sure you want to delete this Assessment?")) {
            assessmentServices.deleteAssessmentRequest(id).then(function (res) {
                $rootScope.getAssessments();
            });
        }
    }


    $scope.popup = function () {
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/AssessmentPopup.html",
            controller: "RequestAssessmentCtrl",
            size: '',
        });

        modalInstance.result.then(function (response) {
            $rootScope.getAssessments();
        });
    }

    $scope.searchData = function () {
        var postdata = {
            "tblVenue.VenueName": angular.isUndefined($scope.search.VenueName) ? "" : $scope.search.VenueName,
            "RequestDate": angular.isUndefined($scope.search.RequestDate) ? "" : $scope.search.RequestDate,
            "RequestAssessmentStatus": angular.isUndefined($scope.search.RequestAssessmentStatus) ? "" : $scope.search.RequestAssessmentStatus,
            "AssessmentDate": angular.isUndefined($scope.search.AssessmentDate) || !$scope.search.AssessmentDate ? "" : $scope.search.AssessmentDate,
        };
        $scope.filter.Search = JSON.stringify(postdata);
        $rootScope.getAssessments();
    }
    init();


    $scope.sortDetails = function (index) {
        if ($scope.headings[index].orderBy < 3) {
            angular.forEach($scope.headings, function (value, key) {
                if (key === index) {
                    value.orderBy = value.orderBy === 0 || value.orderBy === 2 ? 1 : 2;
                } else if (value.orderBy !== 3) {
                    value.orderBy = 0;
                }
            });

            $scope.filter.orderByAsc = $scope.headings[index].orderBy;
            $scope.filter.orderBy = $scope.headings[index].headingName;
            $scope.filter.page = 1;
            $rootScope.getAssessments();
        }
    }

    $scope.pageChanged = function () {
        $rootScope.getAssessments();
    }
});

app.controller('RequestAssessmentCtrl', function ($scope, $rootScope, $uibModalInstance, venueServices, assessmentServices) {

    $scope.getVenuesList = [];
    $scope.isSubmit = false;

    $scope.request = {
        AssessmentDate: new Date()
    };
    $scope.getVenues = function () {
        var filter = {
            page: 0,
            PageSize: '99999',
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };
        venueServices.getVenuesList(filter).then(function (res) {
            $scope.venues = res.Data;
            $scope.getVenuesList = res.Data.Venues;
        });
    }

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }


    $scope.createAssessmentRequest = function (form) {
        $scope.isSubmit = form;
        if (form) {
            assessmentServices.createAssessmentRequest($scope.request).then(function (res, err) {
                toastr.success("Assessment request generated Successfully", "Success");
                $scope.cancel();
                $rootScope.getAssessments();
            });
        }
    }

    $scope.getVenues();
});


app.controller('EditAssessmentCtrl', function ($scope, $rootScope, $uibModalInstance, venueServices, assessmentServices) {

    $scope.getVenuesList = [];
    $scope.getVenues = function () {
        var filter = {
            page: 0,
            PageSize: '99999',
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };
        venueServices.getVenuesList(filter).then(function (res) {
            $scope.venues = res.Data;
            $scope.getVenuesList = res.Data.Venues;
            $scope.request = {
                Id: $rootScope.assessmentRequest.Id,
                VenueId: $rootScope.assessmentRequest.VenueId + "",
                AssessmentDate: new Date($rootScope.assessmentRequest.AssessmentDate)
            };
        });
    }

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }

    $scope.createAssessmentRequest = function (form) {
        if (form) {
            assessmentServices.editAssessmentRequest($scope.request).then(function (res, err) {
                toastr.success("Assessment request generated Successfully", "Success");
                $scope.cancel();
                $rootScope.getAssessments();
            });
        }
    }


    $scope.getVenues();
});
app.controller("VenueDetailController", function ($scope, $rootScope, userServices, venueServices, venueDocumentService, groundManagerServices, pitchMatterService, reportServices, messageServices, $uibModal, assessmentServices, $state, $stateParams, folderPath, $window, Containerbaseurl) {
    $scope.container = Containerbaseurl;
    $scope.venueDetail = {};
    $scope.reports = [];
    $scope.users = [];
    $scope.venueDocument = [];
    $scope.groundManagerSearch = { "tblVenueId": $stateParams.index };
    $scope.pitchMatterSearch = { "VenueId": $stateParams.index };
    $scope.pitchMatterSearchUser = undefined;
    $scope.currentUser = userServices.getCurentUser();
    $scope.isReportHide = false;
    if (!$scope.currentUser.HasMembership) {
        if ($scope.currentUser.PaidFeatures.indexOf('Reports') > -1) {
            $scope.isReportHide = true;
        }
    }
    $scope.filter = {
        page: 0,
        PageSize: '100',
        Search: "",
        orderBy: null,
        orderByAsc: 0,
        IsPostBack: false
    };

    $scope.pitchmatterFilter = {
        page: 0,
        PageSize: '100',
        Search: "",
        orderBy: null,
        orderByAsc: 0,
        IsPostBack: false
    };

    $scope.pitchMattersHeadings = [
        { headingName: "PitchMatterId", name: "Id", orderBy: 1 },
        { headingName: "VenueId", name: "Venue", orderBy: 3 },
        { headingName: "Title", name: "Title", orderBy: 0 },
        { headingName: "Priority", name: "Priority", orderBy: 0 },
        { headingName: "Status", name: "Status", orderBy: 0 },
        { headingName: "Solution", name: "Solution", orderBy: 0 },
        { headingName: "AspNetUser.FirstName", name: "Submitted By", orderBy: 0 },
        { headingName: "CreateDate", name: "Submission Date", orderBy: 0 },
        { headingName: "Action", name: "Action", orderBy: 3 }
    ];

    $scope.groundManagers = [];
    $scope.assessment = [];
    $scope.pitchMatterRecords = [];

    function init() {
        if ($stateParams.index) {
            venueServices.getVenueDetailById($stateParams.index).then(function (res) {
                $scope.venueDetail = res.Data;
            });

            reportServices.getReportsByVenueId($stateParams.index).then(function (res, err) {
                $scope.reports = res.Data;
            });
            $scope.getAssessments();
            $scope.getGroundManagers();
            //start
            $scope.getPitchMatter($stateParams.index);

            messageServices.GetMessageUsers().then(function (res) {
                angular.forEach(res.Data, function (value, key) {
                    if (value.Role === "Consultant") {
                        $scope.users.push(value);
                    }
                });
            });
        }
        $rootScope.getDocumentByVenueId();
    }

    $scope.getGroundManagers = function () {

        var postdata = {
            "AspNetUser.FirstName": angular.isUndefined($scope.groundManagerSearch.FirstName) ? "" : $scope.groundManagerSearch.FirstName,
            "AspNetUser.Email": angular.isUndefined($scope.groundManagerSearch.Email) ? "" : $scope.search.Email,
            "AspNetUser.PhoneNumber": angular.isUndefined($scope.groundManagerSearch.PhoneNumber) ? "" : $scope.groundManagerSearch.PhoneNumber,
            "IsApproved": angular.isUndefined($scope.groundManagerSearch.IsApproved) ? "" : $scope.groundManagerSearch.IsApproved,
            "tblVenueId": $scope.groundManagerSearch.tblVenueId
        };

        $scope.filter.Search = JSON.stringify(postdata);
        groundManagerServices.getGroundManagers($scope.filter).then(function (res) {
            $scope.groundManagers = res.Data.Data;
            angular.forEach(res.Data.Data, function (value, key) {
                $scope.users.push({
                    Email: value.Email,
                    Name: value.FirstName,
                    Role: "Grounds Manager",
                    UserId: value.UserId
                });
            });
        });
    }

    $scope.getAssessments = function () {
        $scope.filter.Search = JSON.stringify({ "tblVenueId": $stateParams.index });

        assessmentServices.getAssessmentList($scope.filter).then(function (res) {
            //$scope.assessment = res.Data.AssessmentRequests;
            //$scope.pageCount = res.Data.PageCount;
            ///Change by Deepak ondate(31Jul2019)
            $scope.assessment = res.Data.Data;
            $scope.pageCount = res.Data.NumberOfPages;
        });
    }

    $scope.clearFilters = function () {
        $scope.groundManagerSearch = { "tblVenueId": $stateParams.index };
        $scope.getGroundManagers();
    }

    $scope.getReportDetailById = function (id) {
        var result = { reportId: id };
        $state.go('user.reportSummary', result);
    }

    //$rootScope.sendReportToMail = function (form) {
    //    if (form) {
    //        var object = {
    //            Email: $rootScope.mailId,
    //            AssessmentReportId: $scope.reportId,
    //        };

    //        reportServices.sendReportToMail(object).then(function (res, err) {
    //            console.log(res);
    //            toastr.success(res.Message, "Success");
    //            $scope.modalInstance.close();

    //        });
    //    }
    //}

    $scope.askForMail = function (id) {

        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/ForwordReport.html",
            controller: "forwordReportCtrl",
            size: 'sm',
            resolve: {
                reportId: function () {
                    return id;
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });

        //$scope.reportId = id;
        //var html = '<label>Email</label><input type="email" class="form-control" ng-model="$root.mailId" placeholder="Email" required />';

        //var modalHtml = '<form name="sendEmailForm" novalidate><div class="modal-body">' + html + '</div>';
        //modalHtml += '<div class="modal-footer"><button class="btn btn-primary" type="submit" ng-click="$root.sendReportToMail(sendEmailForm.$valid)">Send</button><button class="btn btn-warning" ng-click="$root.cancel()">Cancel</button></div></form>';

        //$scope.modalInstance = $uibModal.open({
        //    template: modalHtml,
        //    size: 'sm',
        //});

        //$scope.modalInstance.result.then(function (res) {
        //});
    };

    //$rootScope.cancel = function () {
    //    $scope.modalInstance.close();
    //}

    $scope.downloadReport = function (id) {
        reportServices.downloadReport(id).then(function (res, err) {
            var link = document.createElement("a");
            link.setAttribute("href", res.Data);
            link.setAttribute("download", "AssessmentReport.pdf");

            // Simulate clicking the download link
            var event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
            link.dispatchEvent(event);
        });
    }

    $rootScope.getPitchMatter = function () {
        $scope.pitchmatterFilter.Search = JSON.stringify($scope.pitchMatterSearch);
        pitchMatterService.getPitchMatterByVenueId($scope.pitchmatterFilter).then(function (res) {
            console.log(res);
            $scope.pitchMatterRecords = res.Data.Data;
        });
    };

    $scope.updateStatusPopup = function (pitch) {
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/updatePitchMatterStatus.html",
            controller: "updatePitchMatterStatusCtrl",
            size: '',
            resolve: {
                pitch: function () {
                    return pitch;
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });
    }

    $scope.viewPitchMatterDetail = function (pitch) {
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/viewPitchMatterDetailPopup.html",
            controller: "viewPitchMatterDetailCtrl",
            size: '',
            resolve: {
                pitch: function () {
                    return pitch
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });
    }

    $scope.ViewComments = function (reportId) {
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/reportComments.html",
            controller: "reportCommentCtrl",
            size: '',
            resolve: {
                reportId: function () {
                    return reportId
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });
    }

    $scope.selectVenueInfo = function () {
        $scope.filter = {
            page: 0,
            PageSize: '100',
            Search: "",
            orderBy: null,
            orderByAsc: 0,
            IsPostBack: false
        };
    }

    $scope.sortPitchMatterDetails = function (index) {
        if ($scope.pitchMattersHeadings[index].orderBy < 3) {
            angular.forEach($scope.pitchMattersHeadings, function (value, key) {
                if (key === index) {
                    value.orderBy = value.orderBy === 0 || value.orderBy === 2 ? 1 : 2;
                } else if (value.orderBy !== 3) {
                    value.orderBy = 0;
                }
            });

            $scope.pitchmatterFilter.orderByAsc = $scope.pitchMattersHeadings[index].orderBy;
            $scope.pitchmatterFilter.orderBy = $scope.pitchMattersHeadings[index].headingName;
            $scope.pitchmatterFilter.page = 1;
            $scope.getPitchMatter();
        }
    }

    $scope.editReport = function (id) {
        assessmentServices.getAssessmentInfoById(id).then(function (res) {
            if (res.Data != null) {
                var recentAssessmentInfo = res.Data;
                recentAssessmentInfo.AssessmentRequestId = recentAssessmentInfo.Condition.AssessmentRequestId;
                recentAssessmentInfo.isNewAssessment = false;
                $rootScope.requestAssessment = recentAssessmentInfo;
                assessmentServices.setAssessmentType(recentAssessmentInfo.Condition.AssessmentTypeId)
                updateFirstore(id);
            }
        });
    }

    function updateFirstore(assessmentRequestId) {
        var firestore = firebase.firestore();
        var docref = firestore.collection($scope.user.FirestoreCollectionPath).doc(assessmentRequestId + "");
        $rootScope.isLoading = true;

        docref.onSnapshot(function (res) {
            if (res.exists) {
                var assessmentData = res.data();
                assessmentData.isSubmitted = 0;
                docref.set(assessmentData).then(function (res) {
                    $state.go('user.venueInfo');
                    docref = null;
                    $rootScope.isLoading = false;
                }).catch(function (error) { console.log(error) });
            }
        });
    }


    $scope.labels = [];
    $scope.series = [];
    $scope.data = [];
    $scope.improvementData = [];
    $scope.scoredData = [];
    $scope.datasetOverride = [];
    function getTrendGraph() {
        venueServices.getTrendGraph($stateParams.index).then(function (res) {
            $scope.trendGraph = res.Data;
            var reportID = [];
            var questionObject = [];
            angular.forEach($scope.trendGraph, function (value) {
                if (reportID.indexOf(value.ReportId) == -1) {
                    reportID.push(value.ReportId);
                    $scope.labels.push(moment(value.ReportDate).format("DD-MMM-YYYY hh:mm"));
                }

                var object = {
                    id: "",
                    questionsName: "",
                    maxRating: 0,
                    ratingObject: []
                };

                var _ratingObject = {
                    rating: 0,
                    label: ""
                };

                if ($scope.series.indexOf(value.QuestionsName) == -1) {
                    $scope.series.push(value.QuestionsName);
                    object.id = value.QuestionId;
                    object.questionsName = value.QuestionsName;
                    object.maxRating = value.MaxRating;

                    _ratingObject.rating = value.Rating;
                    _ratingObject.label = moment(value.ReportDate).format("DD-MMM-YYYY hh:mm");

                    object.ratingObject.push(_ratingObject);
                    questionObject.push(object);
                } else {

                    angular.forEach(questionObject, function (ques) {
                        if (ques.id === value.QuestionId) {
                            _ratingObject.rating = value.Rating;
                            _ratingObject.label = moment(value.ReportDate).format("DD-MMM-YYYY hh:mm");
                            ques.ratingObject.push(_ratingObject);
                        }
                    });
                }
            });
            var labelObject = { fill: false, spanGaps: true };

            for (var index = 0; index < $scope.series.length; index++) {
                $scope.datasetOverride.push(labelObject);
            }


            angular.forEach(questionObject, function (ques) {
                var arrObject = [];
                angular.forEach($scope.labels, function (label) {
                    var rating = ques.ratingObject.filter(function (item) { return item.label === label });
                    if (rating.length > 0) {
                        arrObject.push(rating[0].rating);
                    } else {
                        arrObject.push(null);
                    }
                });

                $scope.data.push(arrObject);
                var _improvementdataObject = {
                    questionName: ques.questionsName,
                    newReading: 0,
                    previousReading: 0,
                    improvedBy: ''
                };

                if (ques.ratingObject.length > 1) {
                    var index = ques.ratingObject.length - 1;
                    var previousIndex = ques.ratingObject.length - 2;
                    _improvementdataObject.newReading = (ques.ratingObject[index].rating / ques.maxRating) * 100;
                    _improvementdataObject.previousReading = (ques.ratingObject[previousIndex].rating / ques.maxRating) * 100;
                    var improvedBy = _improvementdataObject.newReading - _improvementdataObject.previousReading;
                    if (improvedBy > 1) {
                        _improvementdataObject.improvedBy = improvedBy + " %";
                    }
                }
                else if (ques.ratingObject.length === 1) {
                    var index = ques.ratingObject.length - 1;
                    _improvementdataObject.newReading = (ques.ratingObject[index].rating / ques.maxRating) * 100;
                }

                $scope.improvementData.push(_improvementdataObject);
            });
        });
    }


    $scope.lightingLabels = [];
    $scope.lightingData = [];

    $scope.lightingOptions = {

        scales: {
            yAxes: [
                {
                    id: 'y-axis-1',
                    type: 'linear',
                    display: true,
                    position: 'left',
                    ticks: {
                        min: 0,
                        maxTicksLimit: 5,
                    }
                },
                {
                    id: 'y-axis-2',
                    type: 'linear',
                    display: true,
                    position: 'right',
                    ticks: {
                        max: 5,
                        min: 0,
                        stepSize: 1
                    }
                }
            ],
            xAxes: [{
                barPercentage: 0.5,
                barThickness: 25,
                maxBarThickness: 8,
                minBarLength: 2,
                gridLines: {
                    offsetGridLines: true
                }
            }]
        }
    };

    $scope.lightingdatasetOverride = [
        {
            label: "Rating",
            borderWidth: 3,
            hoverBackgroundColor: "#CA4A2C",
            hoverBorderColor: "#CA4A2C",
            type: 'line',
            fill: false,
            pointBackgroundColor: "#CA4A2C",
            pointRadius: 5,
            pointBorderWidth: 2,
            pointBorderColor: "#CA4A2C",
            "borderColor": "#CA4A2C",
            "pointColor": "#CA4A2C",
            yAxisID: 'y-axis-2'
        },
        {
            backgroundColor: "#84b343",
            label: "Hours",
            borderWidth: 0,
            type: 'bar',
            fill: false,
            yAxisID: 'y-axis-1'
        }
    ];

    function getLightingBarGraph() {
        venueServices.getLightingHourGraph($stateParams.index).then(function (res) {
            $scope.lightingHourGraph = res.Data;
            var object = [];
            var totalUsageHourobject = [];
            //angular.forEach($scope.lightingHourGraph, function (value, key) {
            //    $scope.lightingLabels.push(moment(value.ReportDate).format("DD-MMM-YYYY hh:mm"));
            //    //object.push(value.LightingHours);
            //    object.push(value.Rating);
            //    $scope.lightingData.push(value.LightingHours);

            //});
            ////$scope.lightingData.push(object);

            angular.forEach($scope.lightingHourGraph, function (value) {
                $scope.lightingLabels.push(moment(value.ReportDate).format("DD-MMM-YYYY hh:mm"));
                object.push(value.Rating);
                totalUsageHourobject.push(value.LightingHours);
            });
            $scope.lightingData.push(object);
            $scope.lightingData.push(totalUsageHourobject);

        });
    }

    function getScoring() {
        venueServices.getScoring($stateParams.index).then(function (res) {
            $scope.scoredData = res.Data;
            console.log(res.Data);
        });
    }   

    $scope.getNumber = function (num) {
        return new Array(num);
    }

    $rootScope.getDocumentByVenueId = function () {
        venueDocumentService.GetVenueDocumentByVenueId($stateParams.index).then(function (res) {
            $scope.venueDocument = res.Data;
            // console.log(res.Data);
        });
    }
    $scope.addVenueDocumentData = function () {

        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/addVenueDocumentData.html",
            controller: "addVenueDocumentDataCtrl",
            size: '',
            //resolve: {
            //    taskDate: function () {
            //        return selectedDate;
            //    },
            //    TaskUserId: function () {
            //        return userId;
            //    },
            //    taskVenueId: function () {
            //        return venueId;
            //    }
            //}
            resolve: {
                Id: function () {
                    return 0
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });

    }
    $scope.viewDetail = function (doc) {

        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/viewVenueDocument.html",
            controller: "viewVenueDocumentCtrl",
            size: '',
            resolve: {
                venueDocument: function () {
                    return doc;
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });

    }

    $scope.deleteVenueDocument = function (doc) {
        if (!$window.confirm("Are you want to delete this event?")) {
            return false;
        }

        if (doc) {
            venueDocumentService.DeleteDocument(doc.Id).then(function (res) {
                $rootScope.getDocumentByVenueId();
            });
        }
        else {
            toastr.warning("Something going wrong.", "Information");
        }
    }
    $scope.downloadVenueDocument = function (id) {
        venueDocumentService.DownloadDocument(id).then(function (res, err) {
            console.log(res.Data);
            var link = document.createElement("a");
            link.setAttribute("href", res.Data.UploadDocumentPath);
            link.setAttribute("download", res.Data.FileName);

            // Simulate clicking the download link
            var event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
            link.dispatchEvent(event);
        });
    }

    getTrendGraph();
    getLightingBarGraph();
    getScoring();
   
    init();


    //$scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
    //$scope.series = ['Series A', 'Series B'];
    //$scope.data = [
    //    [65, 59, 80, 81, 56, 55, 40],
    //    [28, 48, 40, 19, 86, 27, 90]
    //];

    $scope.onClick = function (points, evt) {
        console.log(points, evt);
    };

    $scope.options = {
        scales: {
            yAxes: [
                {
                    id: 'y-axis-1',
                    type: 'linear',
                    display: true,
                    position: 'left'
                },
                {
                    id: 'y-axis-2',
                    type: 'linear',
                    display: false,
                    position: 'right'
                }
            ]
        }
    };
});
app.controller('updatePitchMatterStatusCtrl', function ($scope, $rootScope, $uibModalInstance, pitch, pitchMatterService, Containerbaseurl) {
    $scope.container = Containerbaseurl;
    function init() {
        $scope.query = {
            Id: pitch.Id,
            Priority: pitch.Priority,
            Status: pitch.Status,
            Solution: pitch.Solution,
            // VenueId: pitch.VenueId
        }
    }

    // $scope.note = pitch;

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }


    $scope.updatePitchMatter = function (form) {
        if (form) {
            if ($scope.query.Id > 0) {
                $scope.query.Priority = $scope.query.Priority;
                $scope.query.Status = $scope.query.Status;
                $scope.query.Solution = $scope.query.Solution;

                pitchMatterService.updatePitchMatter($scope.query).then(function (res) {
                    $uibModalInstance.dismiss();
                    $rootScope.getPitchMatter(res.Data.VenueId);

                });


            }

        }
    }
    init();
});
app.controller('viewPitchMatterDetailCtrl', function ($scope, $rootScope, $uibModalInstance, pitch, venueServices, Containerbaseurl ) {
    $scope.container = Containerbaseurl;
    $scope.pitchMatterViewDetail = pitch;

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }



});
app.controller('forwordReportCtrl', function ($scope, $uibModalInstance, reportId, reportServices, messageServices, Containerbaseurl) {
    $scope.container = Containerbaseurl;
    function init() {
        $scope.ReportId = reportId;
        $scope.users = [];
        messageServices.GetMessageUsers().then(function (res) {
            $scope.users = res.Data;
        });

        $scope.forwordReport = { Email: undefined, UserEmail: undefined };
    }

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }

    function sendReport(email) {
        var object = {
            Email: email,
            AssessmentReportId: $scope.ReportId
        };

        reportServices.sendReportToMail(object).then(function (res, err) {
            console.log(res);
            toastr.success(res.Message, "Success");
            $scope.modalInstance.close();

        });
    }

    $scope.sendReportToMail = function () {
        if (!angular.isUndefined($scope.forwordReport.Email)) {
            sendReport($scope.forwordReport.Email);
        }

        if (!angular.isUndefined($scope.forwordReport.UserEmail)) {
            sendReport($scope.forwordReport.UserEmail);
        }
    }


    init();
});
app.controller('reportCommentCtrl', function ($scope, $uibModalInstance, reportId, reportServices, Containerbaseurl) {
    $scope.comments = [];
    $scope.container = Containerbaseurl;
    function init() {
        $scope.reportComment = {
            ReportId: reportId,
            Comment: ""
        }
        reportServices.getCommentsByReportId(reportId).then(function (res) {
            $scope.comments = res.Data;
        });
    }

    $scope.AddComments = function (form) {
        if (form) {
            reportServices.AddCommentOnReports($scope.reportComment).then(function (res) {
                init();
            });
        }
    }

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }

    init();
});

app.controller('addVenueDocumentDataCtrl', function ($scope, $rootScope, $window, $state, userServices, $uibModalInstance, venueServices, $stateParams, venueDocumentService, Containerbaseurl, Id) {
    $scope.venues = [];
    $scope.user = userServices.getCurentUser();
    $scope.container = Containerbaseurl;
    //$scope.venueDocument = {
    //    Id:0,        
    //    UserId: "",

    //};
    //$scope.venueDocument = [];
  
    function init() {
        
        $scope.getVenueByUserId();
    }
    $scope.getVenueByUserId = function () {
        if ($scope.user.UserId) {
            var filter = {
                page: 0,
                PageSize: '99999',
                Search: null,
                orderBy: null,
                orderByAsc: 1,
                IsPostBack: false
            };
            venueServices.getVenuesList(filter).then(function (res) {
                // $scope.venues = res.Data;
                //$scope.getVenuesList = res.Data.Venues;
                $scope.venues = res.Data.Venues;
            });

        }
    }
    $scope.onSelectFile = function (model) {
        $scope.file = model.files[0];
        var extension = $scope.file.name.split(".")[$scope.file.name.split(".").length - 1]
        var validFormats = ['png', 'jpeg', 'jpg', 'doc', 'docx', 'rtf', 'pdf'];
        if (validFormats.indexOf(extension.toLowerCase()) == -1) {
            $scope.file = {};
            angular.element("input[type='file']").val(null);
            toastr.warning("Only png, jpeg, jpg, doc, docx, rtf, pdf format file acceptable", "Information");

        }
    }

    $scope.handleSubmitData = function (form) {
        if (form) {            
            if (!$scope.file) {
                alert("Venue document is required.");
                return false;
            }
            else {
                //$scope.file = model.files[0];
                var extension = $scope.file.name.split(".")[$scope.file.name.split(".").length - 1]
                var validFormats = ['png', 'jpeg', 'jpg', 'doc', 'docx', 'rtf', 'pdf'];
                if (validFormats.indexOf(extension.toLowerCase()) == -1) {
                    alert("Only png, jpeg, jpg, doc, docx, rtf, pdf format file acceptable.");
                    return false;
                }
            }



            console.log("button click");
            var formData = new FormData();
            formData.append("object", JSON.stringify($scope.venueDocument));
            formData.append("file", $scope.file);

            venueDocumentService.CreateVenueDocument(formData).then(function (res, err) {
              
                $uibModalInstance.dismiss();
                $rootScope.getDocumentByVenueId();
                toastr.success("Record saved Successfully", "Success");   
               
            });
        }
    }

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
        // location.reload();  
        //$rootScope.getMessages();
    }

    //$scope.getPopDocumentByVenueId = function () {
    //    venueDocumentService.GetVenueDocumentByVenueId($stateParams.index).then(function (res) {
    //        $scope.venueDocument = res.Data;
    //        // console.log(res.Data);
    //    });
    //}
    init();
});
app.controller("supportController", function ($scope, $rootScope, supportServices, $uibModal, $stateParams, $state, folderPath, Containerbaseurl) {
    function init() {
        $scope.container = Containerbaseurl;
        $scope.queries = [];
        $scope.filter = {
            page: 1,
            PageSize: '10',
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false,
        };
        $scope.pageCount = 0;

        $scope.search = {};
        $scope.headings = [
            { headingName: "CreatedDate", name: "Date", orderBy: 0 },
            { headingName: "Subject", name: "Subject", orderBy: 1 },
            { headingName: "Message", name: "Message", orderBy: 0 },
            { headingName: "Priority", name: "Priority", orderBy: 0 },
            //{ headingName: "tblVenue.VenueName", name: "Venue Name", orderBy: 0 },
            { headingName: "Action", name: "Action", orderBy: 3 }
        ];
        $rootScope.getQueries();
    }

    $scope.searchData = function () {
        var postdata = {
            "Subject": angular.isUndefined($scope.search.Subject) ? "" : $scope.search.Subject,
            "Message": angular.isUndefined($scope.search.Message) ? "" : $scope.search.Message,
            "Priority": angular.isUndefined($scope.search.Priority) ? "" : $scope.search.Priority,
            "CreatedDate": angular.isUndefined($scope.search.CreatedDate) || !$scope.search.CreatedDate ? "" : $scope.search.CreatedDate,
        };
        $scope.filter.Search = JSON.stringify(postdata);
        $rootScope.getQueries();
    }
    $rootScope.getQueries = function () {
        supportServices.getQueries($scope.filter).then(function (res) {
            console.log(res);
            $scope.queries = res.Data.Data;
            $scope.pageCount = res.Data.NumberOfPages * $scope.filter.PageSize;
            $scope.filter.page = res.Data.CurrentPage;
        });
    }

    $scope.doReply = function (id) {
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/doReply.html",
            controller: "askQueryCtrl",
            size: '',
            resolve: {
                supportId: function () {
                    return id
                }
            }
        });

        modalInstance.result.then(function (response) {
            $rootScope.getQueries();
        });
    }

    $scope.askQuery = function () {
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/askQuery.html",
            controller: "askQueryCtrl",
            size: '',
            resolve: {
                supportId: function () {
                    return 0
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });
    }

    init();


    $scope.sortDetails = function (index) {
        if ($scope.headings[index].orderBy < 3) {
            angular.forEach($scope.headings, function (value, key) {
                if (key === index) {
                    value.orderBy = value.orderBy === 0 || value.orderBy === 2 ? 1 : 2;
                } else if (value.orderBy !== 3) {
                    value.orderBy = 0;
                }
            });

            $scope.filter.orderByAsc = $scope.headings[index].orderBy;
            $scope.filter.orderBy = $scope.headings[index].headingName;
            $scope.filter.page = 1;
            $rootScope.getQueries();
        }
    }

    $scope.pageChanged = function () {
        $rootScope.getQueries();
    }
});

app.controller('askQueryCtrl', function ($scope, $uibModalInstance, supportServices, commonServices, supportId, $rootScope, Containerbaseurl) {

    function init() {
        $scope.query = {
            Priority: "Low",
            Message: ""
        }
        $scope.file = undefined;
        $scope.container = Containerbaseurl;
        if (parseInt(supportId) > 0) {
            $scope.messageThread = [];
            supportServices.threadList(supportId).then(function (res) {
                $('#chat-box').slimScroll({
                    height: '250px'
                });
                $scope.messageThread = res.Data;
                if (res.Data.length > 0) {
                    $scope.userId = res.Data[0].SenderId;
                    // added on 06-Sept-19 to send support subject on reply
                   // $scope.query.Subject = res.Data[0].Subject;
                    //
                }
            });
            $scope.query.ParentId = supportId;
        }
    }

    $scope.onSelectFile = function (model) {
        if (model.files[0].type.indexOf('video') > -1) {
            toastr.warning("Video file doesn't spport", "Information");
            angular.element("input[type='file']").val(null);
            return false;
        }
        $scope.file = model.files[0];
        if (model.files.length > 0) {
            $scope.query.AttachedDocName = $scope.file.name;
        }
    }

    $scope.send = function (form) {
        if (form) {
            if (!angular.isUndefined($scope.file)) {
                var formData = new FormData();
                formData.append("file", $scope.file);
                formData.append("extension", $scope.file.name.split(".")[$scope.file.name.split(".").length - 1]);
                formData.append("type", "MessageNoteSupport");

                commonServices.uploadDocument(formData).then(function (res) {
                    $scope.query.AttachedDocPath = res.Data;
                    $scope.sendSupport();
                });
            }
            else {
                $scope.sendSupport();
            }
        }
    }

    $scope.sendSupport = function () {
        supportServices.saveSupportQuery($scope.query).then(function (res) {
            $uibModalInstance.dismiss();
            $rootScope.getQueries();
        });
    }
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
        $rootScope.getQueries();
    }

    init();
});


app.controller("reportViewController", function ($scope, reportServices, venueServices, userServices, $uibModal, $stateParams, $state, Containerbaseurl) {
	$scope.assessmentReportData = {};
	$scope.user = userServices.getCurentUser();

	$scope.container = Containerbaseurl;
	userServices.AllowViewReportsToSubclientIfClientHasMembershipData().then(function (res, err) {
		if (res.Data.Data.IsThisSubClient) {// If subclient login and its client don't have membership membership then show messageIsThisSubClient
			if (!res.Data.Data.IsClientOfSubclientHasMembership) {
				if ($scope.user.PaidFeatures.indexOf('Trend Graph') > -1) {
					toastr.info("This is a paid feature. For further information, contact the client.", "Information");
					$state.go("user.dashboard");
					//$state.go("user.membership");
				}
			}
		}
		else {

			var expiryDatetime = Date.parse($scope.user.MembershipExpiry);
			var currentDatetime = Date.now();
			if (!$scope.user.HasMembership || !(currentDatetime < expiryDatetime)) {
				if ($scope.user.PaidFeatures.indexOf('Trend Graph') > -1) {
					toastr.info("This is paid feature", "Information");
					$state.go("user.membership");
				} else {
					var result = { reportId: $stateParams.reportId };
					$state.go('user.reportSummary', result);
				}
			}
		}
	});


	$scope.summaryTotalData = {
		maxTotal: 0,
		scoreTotal: 0,
		perTotal: 0
	}

	$scope.assessmentSummaryData = []
	$scope.assessmentRatingData = [];
	$scope.assessmentName = "";
	$scope.venueInfo = {};
	$scope.venue = {};
	$scope.awardedRating = 0;
	$scope.summaryGraph = {
		Labels: [],
		Data: []
	};

	$scope.totalUsageHoursGraph = {
		Labels: [],
		Data: []
	};

	$scope.assessmentData = {};
	$scope.data = [];
	function init() {

		reportServices.getAssessemntReportSummuryById($stateParams.reportId).then(function (res, err) {
			$scope.assessmentSummaryData = res.Data.Summary;
			reportServices.getReportDetailById($stateParams.reportId).then(function (res, err) {
				console.log(res);
				$scope.assessmentName = res.Data.AssessmentTypeName;
				$scope.assessmentReportData = [];// res.Data;
				$scope.venueInfo = res.Data.VenueInfo;
				$scope.submitBy = res.Data.SubmitBy;
				var ReportDetail = res.Data;

				angular.forEach($scope.assessmentSummaryData, function (assessmentSummaryData) {
					$scope.summaryTotalData.maxTotal += assessmentSummaryData.Max;
					$scope.summaryTotalData.scoreTotal += assessmentSummaryData.Score;

					var object = {
						CategoryName: assessmentSummaryData.CategoryName,
						Max: assessmentSummaryData.Max,
						Score: assessmentSummaryData.Score,
						Percentage: assessmentSummaryData.Percentage,
						AssessmentReportOutputViewModel: []
					};

					angular.forEach(ReportDetail.AssessmentReportOutputViewModel, function (data) {
						if (assessmentSummaryData.CategoryName.trim().toLowerCase() == data.QuestionCategory.trim().toLowerCase()) {
							object.CategoryName = data.QuestionCategory;

							var graphObject = {
								Label: [], AVGValues: []
							}
							var graphData = [];
							var graphLightingHoursData = [];

							angular.forEach(data.LocationGraph, function (LocationGraph) {
								graphData.push(LocationGraph.AVGValues);
								graphLightingHoursData.push(LocationGraph.LightingHours);
								graphObject.Label.push(moment(LocationGraph.AssessmentDate).format('DD-MMM-YYYY'));
							});

							graphObject.AVGValues.push(graphData);
							graphObject.AVGValues.push(graphLightingHoursData);
							data.graph = graphObject;
							data.options = setOption(data.Ranges[0].Type);
							data.questionType = data.Ranges[0].Type;
							object.AssessmentReportOutputViewModel.push(data);
						}
					});
					$scope.assessmentReportData.push(object);
				});
				$scope.summaryTotalData.perTotal = Math.round(($scope.summaryTotalData.scoreTotal / $scope.summaryTotalData.maxTotal) * 100);

				venueServices.getVenueDetailById(res.Data.VenueInfo.VenueId).then(function (res) {
					$scope.venue = res.Data;
				});

				$scope.getDataFromFireStore(res.Data.VenueInfo.Condition.AssessmentRequestId);
				getAssessmentImage(res.Data.VenueInfo.Condition.AssessmentRequestId);

			});

		});
	}

	$scope.getReportDetailById = function () {
		var result = { reportId: $stateParams.reportId };
		$state.go('user.reportSummary', result);
	}

	$scope.files = [];
	function getAssessmentImage(AssessmentRequestId) {
		//reportServices.getImages(AssessmentRequestId).then(function (res, err) {
		//    $scope.files = res.Data;
		//    imageIndex = $scope.files.length;
		//});
	}

	$scope.getDataFromFireStore = function (AssessmentRequestId) {
		var firestore = firebase.firestore();
		$scope.docref = firestore.collection($scope.user.FirestoreCollectionPath).doc(AssessmentRequestId + "");
		$scope.docref.onSnapshot(function (res) {
			if (res.exists) {
				$scope.assessmentData = res.data();
				$scope.$apply();
			}
		});
	}

	$scope.getNumber = function (number) {
		return new Array(number);
	}

	$scope.getReportDetailById = function () {
		var result = { reportId: $stateParams.reportId };
		$state.go('user.reportSummary', result);
	}

	init();


	$scope.colours = [{ // default
		"fillColor": "rgba(0, 0, 0, 0)",
		"strokeColor": "#CA4A2C",
		"pointColor": "#CA4A2C",
	}];

	$scope.barColours = [{ // default
		"fillColor": "#4F6228",
		"strokeColor": "#4F6228",
		"pointColor": "rgba(151,185,205,1)",
	},
	{ // default
		"fillColor": "#76923B",
		"strokeColor": "#76923B",
		"pointColor": "rgba(151,185,205,1)",
	},
	{ // default
		"fillColor": "#C2D59A",
		"strokeColor": "#C2D59A",
		"pointColor": "rgba(151,185,205,1)",
	},
	{ // default
		"fillColor": "#00B050",
		"strokeColor": "#00B050",
		"pointColor": "rgba(151,185,205,1)",
	},
	{ // default
		"fillColor": "#00B050",
		"strokeColor": "#00B050",
		"pointColor": "rgba(151,185,205,1)",
	},
	{ // default
		"fillColor": "#00B050",
		"strokeColor": "#00B050",
		"pointColor": "rgba(151,185,205,1)",
	}];


	$scope.colors = ['#45b7cd', '#ff6384', '#ff8e72'];

	$scope.FilterQuestionGraph = function (days, questionId) {
		var postdata = {
			ReportId: $stateParams.reportId,
			VenueId: $scope.venueInfo.VenueId,
			QuestionId: questionId,
			Days: days
		};
		reportServices.filterQuestionRatingGraph(postdata).then(function (res) {
			angular.forEach($scope.assessmentReportData, function (assessmentReportData) {
				angular.forEach(assessmentReportData.AssessmentReportOutputViewModel, function (assessmentReportOutputViewModel) {
					if (assessmentReportOutputViewModel.QuestionId == res.Data[0].QuestionId) {
						var graphObject = {
							Label: [], AVGValues: []
						}
						var graphData = [];
						var graphLightingHoursData = [];

						angular.forEach(res.Data, function (LocationGraph) {
							graphData.push(LocationGraph.AVGValues);
							graphLightingHoursData.push(LocationGraph.LightingHours);
							graphObject.Label.push(moment(LocationGraph.AssessmentDate).format('DD-MMM-YYYY'));
						});

						graphObject.AVGValues.push(graphData);
						graphObject.AVGValues.push(graphLightingHoursData);
						assessmentReportOutputViewModel.graph = graphObject;
					}

					console.log();
				});
			});
		});
	};

	function setOption(name) {
		return options = {
			scales: {
				yAxes: [
					{
						id: 'y-axis-1',
						type: 'linear',
						display: true,
						position: 'left',
						ticks: {
							min: 0,
							maxTicksLimit: 5,
						},
						scaleLabel: {
							display: true,
							labelString: 'Hours'
						}
					},
					{
						id: 'y-axis-2',
						type: 'linear',
						display: true,
						position: 'right',
						ticks: {
							min: 0,
							maxTicksLimit: 5,
						},
						scaleLabel: {
							display: true,
							labelString: '(' + name + ')'
						}
					}
				],
				xAxes: [{
					barPercentage: 0.5,
					barThickness: 25,
					maxBarThickness: 8,
					minBarLength: 2,
					gridLines: {
						offsetGridLines: true
					}
				}]
			}
		};
	}

	$scope.datasetOverride = [
		{
			label: "Result",
			borderWidth: 3,
			hoverBackgroundColor: "#CA4A2C",
			hoverBorderColor: "#CA4A2C",
			type: 'line',
			fill: false,
			pointBackgroundColor: "#CA4A2C",
			pointRadius: 5,
			pointBorderWidth: 2,
			pointBorderColor: "#CA4A2C",
			"borderColor": "#CA4A2C",
			"pointColor": "#CA4A2C",
			yAxisID: 'y-axis-2'
		},
		{
			backgroundColor: "#84b343",
			label: "Hours",
			borderWidth: 0,
			type: 'bar',
			fill: false,
			yAxisID: 'y-axis-1'
		}
	];

	$scope.hourQuestionGraph = function (questionId, type, questionName) {
		var modalInstance = $uibModal.open({
			templateUrl: "content/CommonHtml/HourQuestionGraph.html",
			controller: "hourQuestionGraphCtrl",
			size: 'lg',
			resolve: {
				venueId: function () {
					return $scope.venueInfo.VenueId;
				},
				questionId: function () {
					return questionId;
				},
				reportId: function () {
					return $stateParams.reportId;
				},
				graphLabelName: function () {
					return type;
				},
				questionName: function () {
					return questionName;
				}
			}
		});

		modalInstance.result.then(function (response) {
			$scope.result = `${response} button hitted`;
		});
	}
});

app.controller("hourQuestionGraphCtrl", function ($scope, questionId, venueId, reportId, graphLabelName, questionName, reportServices, $uibModalInstance) {
	$scope.filterStartDate = moment().add(-1, "year").format('YYYY-MM-DD');
	$scope.filterFinishDate = moment().format('YYYY-MM-DD');

	$scope.scores = [];
	$scope.questionName = questionName;

	$scope.summaryGraph = {
		Labels: [],
		Data: []
	};

	$scope.graphObject = {
		Label: [], AVGValues: []
	};

	$scope.venue = {};

	$scope.onchangeStartDate = function () {
		$scope.filterToStartDate = moment($scope.fromDate).format('YYYY-MM-DD');
	}

	$scope.ok = function () {
		$uibModalInstance.dismiss();
	}

	$scope.cancel = function () {
		$uibModalInstance.dismiss();
	}

	$scope.handleSubmit = function () {
		$scope.graphObject = {
			Label: [], AVGValues: []
		};
		var postdata = {
			ReportId: reportId,
			VenueId: venueId,
			QuestionId: questionId,
			FromDate: $scope.fromDate ? moment($scope.fromDate).add(1, "days") : null,
			ToDate: $scope.toDate ? moment($scope.toDate).add(1, "days") : null
		};

		reportServices.filterQuestionRatingGraph(postdata).then(function (res) {

			var graphData = [];
			var graphLightingHoursData = [];

			angular.forEach(res.Data, function (LocationGraph) {
				graphData.push(LocationGraph.AVGValues);
				graphLightingHoursData.push(LocationGraph.LightingHours);
				$scope.graphObject.Label.push(moment(LocationGraph.AssessmentDate).format('DD-MMM-YYYY'));
			});

			$scope.graphObject.AVGValues.push(graphData);
			$scope.graphObject.AVGValues.push(graphLightingHoursData);
		});
	};

	function setGraphData(graphData) {
		var object = [];
		var totalUsageHourobject = [];
		$scope.summaryGraph = {
			Labels: [],
			Data: []
		};
		angular.forEach(graphData, function (graph) {
			$scope.summaryGraph.Labels.push(moment(graph.Date).format('DD-MMM-YYYY'));
			object.push(graph.Rating);
			totalUsageHourobject.push(graph.LightingHours);
		});
		$scope.summaryGraph.Data.push(object);
		$scope.summaryGraph.Data.push(totalUsageHourobject);
	}
	$scope.colors = ['#45b7cd', '#ff6384', '#ff8e72'];

	$scope.options = {
		scales: {
			yAxes: [
				{
					id: 'y-axis-1',
					type: 'linear',
					display: true,
					position: 'left',
					ticks: {
						min: 0,
						maxTicksLimit: 5,
					},
					scaleLabel: {
						display: true,
						labelString: 'Hours'
					}
				},
				{
					id: 'y-axis-2',
					type: 'linear',
					display: true,
					position: 'right',
					ticks: {
						min: 0,
						maxTicksLimit: 5,
					},
					scaleLabel: {
						display: true,
						labelString: '(' + graphLabelName + ')'
					}
				}
			],
			xAxes: [{
				barPercentage: 0.5,
				barThickness: 25,
				maxBarThickness: 8,
				minBarLength: 2,
				gridLines: {
					offsetGridLines: true
				}
			}]
		}
	};

	$scope.datasetOverride = [
		{
			label: "Result",
			borderWidth: 3,
			hoverBackgroundColor: "#CA4A2C",
			hoverBorderColor: "#CA4A2C",
			type: 'line',
			fill: false,
			pointBackgroundColor: "#CA4A2C",
			pointRadius: 5,
			pointBorderWidth: 2,
			pointBorderColor: "#CA4A2C",
			"borderColor": "#CA4A2C",
			"pointColor": "#CA4A2C",
			yAxisID: 'y-axis-2'
		}
		,
		{
			backgroundColor: "#84b343",
			label: "Hours",
			borderWidth: 0,
			type: 'bar',
			fill: false,
			yAxisID: 'y-axis-1'
		}
	];
	$scope.handleSubmit();
});
app.controller("DetailController", function ($scope, groundManagerServices, venueServices, $state, $stateParams) {
    $scope.groundManager = {};
    $scope.venues = [];
    $scope.GetGroundManagerById = function () {
        if ($stateParams.index) {
            groundManagerServices.getGroundManagerById($stateParams.index).then(function (res) {
                $scope.groundManager = res.Data;
                console.log(res.Data);
                $scope.groundManager.VenueId = res.Data.VenueId + "";
            });
        }
    }

    $scope.GetGroundManagerById();

    //Created on 24-mar-22, show edit when Gm vanues are same as login user vanues

    $scope.getVenues = function () {
        var filter = {
            page: 0,
            PageSize: '1000',
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };
        venueServices.getVenuesList(filter).then(function (res) {
            $scope.venues = res.Data.Venues;
        });
    }
    $scope.IsShowVenue = function (groundMan) {
        var isReturn = false;
        var subclientVanues = $scope.venues;
        console.log("subclientVanues");
        console.log(subclientVanues);
        var gmVanues = groundMan.GroundManagerVenues;
        console.log("gmVanues");
        console.log(gmVanues);
        var subClientMatchid = [];

        angular.forEach(gmVanues, function (gvalue, key) {
            angular.forEach(subclientVanues, function (svalue, key1) {
                if (gvalue.VenueId == svalue.Id) {
                    subClientMatchid.push(svalue.Id);
                }
            });
        });
        if (subClientMatchid.length == gmVanues.length) {
            isReturn = true;
            return isReturn;
        }
        console.log("subClientMatchid");
        console.log(subClientMatchid);
        return isReturn;

    }
    //end
});
app.controller("MessageController", function ($scope, $rootScope, messageServices, $uibModal, userServices, $state, folderPath) {
    function init() {
        $scope.messages = [];
        $scope.filter = {
            page: 1,
            PageSize: '10',
            Search: null,
            orderBy: null,
            orderByAsc: 1,
            IsPostBack: false
        };
        $scope.pageCount = 0;
        $rootScope.getMessages();
        $scope.search = {};
        $scope.headings = [
            { headingName: "Subject", name: "Subject", orderBy: 0 },
            { headingName: "Message", name: "Message", orderBy: 1 },
            { headingName: "Priority", name: "Priority", orderBy: 0 },
            { headingName: "ReceiverId", name: "ReceiverId", orderBy: 0 },
            { headingName: "AspNetUser1.FirstName", name: "ReceiverName", orderBy: 0 },
            //{ headingName: "AspNetUser1.Email", name: "ReceiverEmail", orderBy: 0 },// commented on 08-Jan-21 for ground manager according to tester feedback
            { headingName: "CreatedDate", name: "CreatedDate", orderBy: 0 },
            { headingName: "Action", name: "Action", orderBy: 3 }
        ];
    }

    $scope.user = userServices.getCurentUser();

    userServices.AllowViewReportsToSubclientIfClientHasMembershipData().then(function (res, err) {

        if (res.Data.Data.IsThisSubClient) {// If subclient login and its client don't have membership membership then show message
            if (!res.Data.Data.IsClientOfSubclientHasMembership) {
                if ($scope.user.PaidFeatures.indexOf('Messaging') > -1) {
                    toastr.info("This is a paid feature. For further information, contact the client.", "Information");
                    $state.go("user.dashboard");
                    //$state.go("user.membership");
                }
            }
        }
        else {
            var expiryDatetime = Date.parse($scope.user.MembershipExpiry);
            var currentDatetime = Date.now();
            if (!$scope.user.HasMembership || !(currentDatetime < expiryDatetime)) {
                if ($scope.user.PaidFeatures.indexOf('Messaging') > -1) {
                    toastr.info("This is paid feature", "Information");
                    //$state.go("user.dashboard");
                    $state.go("user.membership");
                }
            }
        }
    });

    $rootScope.getMessages = function () {
        messageServices.getQueries($scope.filter).then(function (res) {
            console.log(res);
            $scope.messages = res.Data.Data;
            $scope.pageCount = res.Data.NumberOfPages * $scope.filter.PageSize;
            $scope.filter.page = res.Data.CurrentPage;
        });
    }

    $scope.doMessageReply = function (id) {
        debugger;
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/doMessageReply.html",
            controller: "createMessageCtrl",
            size: '',
            resolve: {
                messageId: function () {
                    return id;
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });
    }

    $scope.sendMessage = function () {
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/createMessage.html",
            controller: "createMessageCtrl",
            size: '',
            resolve: {
                messageId: function () {
                    return 0
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });
    }
    $scope.searchData = function () {
        var postdata = {
            "Subject": angular.isUndefined($scope.search.Subject) ? "" : $scope.search.Subject,
            "Message": angular.isUndefined($scope.search.Message) ? "" : $scope.search.Message,
            "Priority": angular.isUndefined($scope.search.Priority) ? "" : $scope.search.Priority,
            "CreatedDate": angular.isUndefined($scope.search.CreatedDate) || !$scope.search.CreatedDate ? "" : $scope.search.CreatedDate,
            "AspNetUser1.FirstName": angular.isUndefined($scope.search.FirstName) || !$scope.search.FirstName ? "" : $scope.search.FirstName,
            "AspNetUser1.Email": angular.isUndefined($scope.search.Email) || !$scope.search.Email ? "" : $scope.search.Email,
        };
        $scope.filter.Search = JSON.stringify(postdata);
        $rootScope.getMessages();
    }
    init();

    $scope.sortDetails = function (index) {
        if ($scope.headings[index].orderBy < 3) {
            angular.forEach($scope.headings, function (value, key) {
                if (key === index) {
                    value.orderBy = value.orderBy === 0 || value.orderBy === 2 ? 1 : 2;
                } else if (value.orderBy !== 3) {
                    value.orderBy = 0;
                }
            });

            $scope.filter.orderByAsc = $scope.headings[index].orderBy;
            $scope.filter.orderBy = $scope.headings[index].headingName;
            $scope.filter.page = 1;
            $rootScope.getMessages();

        }
    }

    $scope.pageChanged = function () {
        $rootScope.getMessages();
    }
});

app.controller('createMessageCtrl', function ($scope, $uibModalInstance, messageServices, groundManagerServices, commonServices, messageId, $rootScope) {
    $scope.clientGroundManager = [];
    $scope.users = [];

    //$scope.request = {};
    function init() {
        
        $scope.request = {
            Priority: "Low",
            Message: "",
            selectedUser: undefined,
            ReceiverId: undefined,
            IsReply: false,
        };

        $scope.file = undefined;

        messageServices.GetMessageUsers().then(function (res) {
            $scope.users = res.Data;
            $scope.getGroundMans();
        });

        if (parseInt(messageId) > 0) {
            $scope.messageThread = [];
            messageServices.threadList(messageId).then(function (res) {
                $('#chat-box').slimScroll({
                    height: '250px'
                });
                $scope.messageThread = res.Data;

                if (res.Data.length > 0) {
                    $scope.request.ReceiverId = res.Data[0].ReceiverId;
                }
            });
            $scope.request.ParentId = messageId;

        }
    }

    $scope.onSelectFile = function (model) {
        if (model.files[0].type.indexOf('video') > -1) {
            toastr.warning("Video file doesn't spport", "Information");
            angular.element("input[type='file']").val(null);
            return false;
        }
        $scope.file = model.files[0];
        if (model.files.length > 0) {
            $scope.request.AttachedDocName = $scope.file.name;
        }
    }

    $scope.send = function (form) {
        if ($scope.request.selectedUser) {
            $scope.request.ReceiverId = $scope.request.selectedUser.UserId
        }

        if (!$scope.request.ReceiverId) {
            toastr.error("Please select anyone groundmanager or other user.", "Error");
            return false;
        }

        //if ($scope.request.IsReply) {
        if (form) {
            if (!angular.isUndefined($scope.file)) {
                var formData = new FormData();
                formData.append("file", $scope.file);
                formData.append("extension", $scope.file.name.split(".")[$scope.file.name.split(".").length - 1]);
                formData.append("type", "MessageNoteSupport");
                commonServices.uploadDocument(formData).then(function (res) {
                    $scope.request.AttachedDocPath = res.Data;
                    $scope.sendMessage();
                });
            }
            else {
                $scope.sendMessage();
            }
        }
    }


    $scope.sendMessage = function () {

        if (angular.isUndefined($scope.request.ReceiverId)) {
            $scope.request.ReceiverName = $scope.request.selectedUser.Name;
            $scope.request.ReceiverId = $scope.request.selectedUser.UserId;
        }
        $scope.request.ReceiverId = $scope.request.ReceiverId === "" ? null : $scope.request.ReceiverId;
        messageServices.saveMessageQuery($scope.request).then(function (res) {
            $uibModalInstance.dismiss();
            $rootScope.getMessages();
        });
    }
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
        $rootScope.getMessages();
    }


    $scope.getGroundMans = function () {
        var filter = {
            page: 0,
            PageSize: '1000',
            Search: null,
            orderBy: null,
            orderByAsc: 2,
            IsPostBack: false
        };
        groundManagerServices.getGroundManagers(filter).then(function (res) {
            $scope.clientGroundManager = res.Data.Data;
        });

    }
    $scope.clearGroundMan = function () {
        $scope.request.ReceiverId = undefined;
    }

    init();

});
app.controller("ListController", function ($scope, faqServices, $state, $stateParams) {
    $scope.active = true;
    $scope.FaqList = [];
    $scope.getFaqList = function () {

        faqServices.getFaqList().then(function (res) {
            $scope.FaqList = res.Data;
            
        });
    }
    $scope.getFaqList();
    
});
app.controller("NotificationController", function ($scope, $rootScope, notificationServices, $uibModal, $stateParams, $state, folderPath) {
    function init() {
        $scope.notifications = [];
        $scope.selected.NotificationIds = [];
        //$rootScope.getNotifications();
    }

    $scope.portalIdEnabled = true;
    $scope.selectedNotificationId = [];
    $scope.selected = {
        NotificationIds: []
    };

    $scope.selectAll = false;

    $scope.toggleNoti = function (index) {
        $rootScope.notifications[index].checked = !$rootScope.notifications[index].checked;
        if (!$rootScope.notifications[index].checked) {
            $scope.selectAll = false;
            $scope.selected.NotificationIds = $scope.selected.NotificationIds.filter(function (value) {
                return value != $rootScope.notifications[index].Id;
            });
        } else {
            $scope.selected.NotificationIds.push($rootScope.notifications[index].Id);
        }
        if ($scope.selected.NotificationIds.length == $rootScope.notifications.length) {
            $scope.selectAll = true;
        }
    };

    $scope.toggleAll = function () {
        var checked = $scope.selectAll;
        $scope.selected.NotificationIds = [];
        for (var i = 0; i < $rootScope.notifications.length; i++) {
            $scope.selectedNotificationId[i] = checked;
            $rootScope.notifications[i].checked = checked;
            $scope.selected.NotificationIds.push($rootScope.notifications[i].Id);
        }
        if (!checked) {
            $scope.selected.NotificationIds = [];
        }
    };

    $scope.Delete = function () {
        var ids = $scope.selected.NotificationIds.join(",");
        notificationServices.deleteNotifications(ids).then(function (res) {
            console.log(res);
            $scope.selectAll = false;
            $scope.selected.NotificationIds = [];
            $scope.selectedNotificationId = [];
            $rootScope.getNotifications();
            switch (res.StatusCode) {
                case 201:
                case 200:
                    toastr.success(res.Message, "Success");
                    break;
                case 401:
                    toastr.error(res.Message, "Error");
                    break;
                case 404:
                    toastr.warning(res.Message, "Information");
                    break;
                default:
                    toastr.error(res.Message, "Error");
                    break;
            }
        });
    }

    //$rootScope.getNotifications = function () {
    //    notificationServices.getNotifications().then(function (res) {
    //        console.log(res);
    //        $scope.notifications = res.Data;
    //    });
    //}

    //$rootScope.updateNotificationStatus = function (id) {
    //    notificationServices.updateNotificationStatus(id).then(function (res) {
    //        console.log(res);
    //        $rootScope.getNotifications();
    //    });
    //}

    $scope.viewNotification = function (notification) {
        var modalInstance = $uibModal.open({
            templateUrl: folderPath + "Dailog/viewNotifications.html",
            controller: "notificationDetailCtrl",
            size: '',
            resolve: {
                notification: function () {
                    return notification
                }
            }
        });

        modalInstance.result.then(function (response) {
            $scope.result = `${response} button hitted`;
        });
    }

    init();
});

app.controller("notificationDetailCtrl", function ($scope, $uibModalInstance, notification, $rootScope) {

    $scope.notificationDetail = notification;
    $rootScope.updateNotificationStatus(notification.Id);

    $scope.cancel = function () {
        $uibModalInstance.dismiss("close");
    }
});


app.controller("membershipController", function ($scope, membershipServices, userServices, $uibModal, folderPath) {
    $scope.details = "";
    $scope.plans = [];
    $scope.plan = "";
    $scope.selectedPlan = {};
    $scope.isRecurring = false;
    $scope.IsTermAndConditionAccepted = false;
    $scope.isExpired = false;
    var paymentInstance = {};

    function init() {
        //window.location.reload();
        membershipServices.getPlans().then(function (res) {
            console.log("getPlans", res);
            $scope.plans = res.Data;
            if (res.Data.length > 0) {
                $scope.plan = JSON.stringify($scope.plans[0]);
                $scope.selectPlan();
            }
        });

        membershipServices.detail().then(function (res) {
            console.log("detail", res);
            $scope.detail = res.Data;

            if ($scope.detail.ExpiryDate != null) {
                var expiryDatetime = Date.parse($scope.detail.ExpiryDate);
                var currentDatetime = Date.now();

                if (currentDatetime < expiryDatetime) {
                    $scope.isNotExpired = false;
                    //getClientToken();
                }
                else
                {
                    $scope.isNotExpired = true;
                    getClientToken();
                }
            }
            else {
                $scope.isNotExpired = true;
                getClientToken();
            }
        });
         
    }

    $scope.buyPackage = function () {
        var plan = JSON.parse($scope.plan);
        var object = {
            "MembershipPlanId": plan.Id,
            "PaymentStatus": "success",
            "PaymentMode": "online",
            "Description": "payment successfully",
            "IsRecurring": $scope.isRecurring,
            "Currency": plan.Currency
        };

        membershipServices.buy(object).then(function (res) {
            init();
        });
    }

    $scope.openAddonMembership = function () {
        //$rootScope.reportId = id;
        $scope.modalInstance = $uibModal.open({
            templateUrl: folderPath + '/dailog/MembershipAddOn.html',
            controller: "addonMembershipController",
            size: 'sm',
        });

        $scope.modalInstance.result.then(function (res) {
        });
    };

    $scope.selectPlan = function () {
        console.log("$scope.plan", $scope.plan);
        if ($scope.plan) {
            $scope.selectedPlan = JSON.parse($scope.plan);
            $scope.selectedPlan.Tax = parseFloat($scope.selectedPlan.Amount) * (parseFloat($scope.selectedPlan.Tax) / 100);
            $scope.selectedPlan.TotalAmount = parseFloat($scope.selectedPlan.Amount) + parseFloat($scope.selectedPlan.Tax);
        } else {
            $scope.selectedPlan = {};
        }
    }

    $scope.askForReason = function () {
        $uibModal.open({
            templateUrl: folderPath + "Dailog/unsubscribe.html",
            controller: "unsubscribeController"
        });
    };


    $scope.isPopupVisible = false;
    $scope.popupMessage = "";

    $scope.OpenpopUp = function () {
        if ($scope.plan != null) {
            $scope.isPopupVisible = true;
        }
        else {
            toastr.error("Please Select plan", "Warning");
        }

    };

    $scope.ClosepopMsg = function () {
        $scope.isPopupVisible = false;
    }

    $scope.sendPopupMessage = function () {
        console.log($scope.popupMessage);
        var plan = JSON.parse($scope.plan);
        var msg = document.querySelector('input[name="popupMessage"]').value;
        var object = {
            "MembersipPlanId": plan.Id,
            "Message": msg,
            "Amount": $scope.selectedPlan.TotalAmount,
            "Currency": plan.Currency,
            "DeviceType": "Web",
            "Type": "New Membership", 
        };

        membershipServices.SendMail(object).then(function (res) {
            if (!res.IsSuccess) {
                toastr.error(res.Message, "Failed");
                init();
            } else {
                toastr.success("Mail Sent To Admin", "Success");
                $scope.isPopupVisible = false;
            }
        });
       
    };

    function getClientToken() {

        membershipServices.getClientToken().then(function (res) {
            var client_token = res.Data;
            braintree.dropin.create({
                authorization: client_token,
                container: '#bt-dropin',
                paypal: {
                    flow: 'vault'
                }
            }, function (createErr, instance) {

                paymentInstance = instance;
            });
        });
    }

    $scope.doPayment = function () {


        //added on 16-Sept-21
        //if ($scope.detail.IsSubscribed) {
        //    alert("You have already active plan, please unsubscribe current plan to subscribe new plan.");
        //    return false;
        //}
        //
        if (!$scope.IsTermAndConditionAccepted) {
            toastr.error("Please accept Term and Condition", "Warning");
            return false;
        }
        if (confirm("If You have already active plan, then existing plan will be override.")) {
            paymentInstance.requestPaymentMethod(function (err, payload) {
                if (err) {
                    toastr.error(err.message + ". please try again", "Error");
                    console.log('Error', err);
                    return;
                }
                //console.log(payload);
                var plan = JSON.parse($scope.plan);
                var object = {
                    "MembershipPlanId": plan.Id,
                    "PaymentStatus": payload.nonce,
                    "PaymentMode": "online",
                    "Description": "payment successfully",
                    "IsRecurring": $scope.isRecurring,
                    "Amount": $scope.selectedPlan.TotalAmount,
                    "Currency": plan.Currency,
                    "DeviceType": "Web",
                    "IsSubscribe": true
                };

                membershipServices.payment(object).then(function (res) {
                    if (res.Data.PaymentStatus === "Failed") {
                        toastr.error(res.Message, "Failed");
                        init();
                    } else {
                        toastr.success("Payment done Successfully", "Success");
                        $scope.user = userServices.getCurentUser();
                        var email = $scope.user.Email;
                        userServices.getUserDetail(email).then(function (res1, err) {
                            userServices.saveUserDetail(res1.Data);
                            alert(res.Message);
                            init();
                        });
                    }
                });

            });
        }

        //

    }

    init();
});


app.controller("addonMembershipController", function ($scope, membershipServices, userServices, $uibModal, folderPath, $uibModalInstance) {
    $scope.details = "";
    $scope.plans = [];
    $scope.plan = "";
    $scope.selectedPlan = {};
    $scope.isRecurring = false;
    $scope.IsTermAndConditionAccepted = false;
    var paymentInstance = {};

    function init() {

        membershipServices.getPlans().then(function (res) {
            console.log("getPlans", res);
            $scope.plans = res.Data;
            if (res.Data.length > 0) {
                $scope.plan = null; // Important: don't auto-select anything
                //$scope.plan = JSON.stringify($scope.plans[0]);
                $scope.selectPlan();
            }
        });

        membershipServices.detail().then(function (res) {
            console.log("detail", res);
            $scope.details = res.Data;
        });



        getClientToken();
    }


    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }
    function getClientToken() {

        membershipServices.getClientToken().then(function (res) {
            var client_token = res.Data;
            braintree.dropin.create({
                authorization: client_token,
                container: '#bt-dropin1',
                paypal: {
                    flow: 'vault'
                }
            }, function (createErr, instance) {

                paymentInstance = instance;
            });
        });
    }

    $scope.selectPlan = function () {
        console.log("$scope.plan", $scope.plan);
        if ($scope.plan) {
            $scope.selectedPlan = JSON.parse($scope.plan);
            const createdDate = new Date($scope.details.CreatedDate);
            const today = new Date();
            const previousVenues = $scope.details.NoOfVenues || 0;
            const newPlanAmount = parseFloat($scope.selectedPlan.Amount);
            const newPlanVenues = $scope.selectedPlan.NoOfVenues || 0;
            const taxRate = parseFloat($scope.selectedPlan.Tax) || 0;

            let finalAmount = 0;

            const sameMonth = createdDate.getFullYear() === today.getFullYear() &&
                createdDate.getMonth() === today.getMonth();

            if (sameMonth) {
                // Same month: Pay full amount
                finalAmount = newPlanAmount;
            }
            else {

                const yearDiff = today.getFullYear() - createdDate.getFullYear();
                const monthDiff = (yearDiff * 12) + (today.getMonth() - createdDate.getMonth());
                const monthlyAmount = newPlanAmount / 12;
                const remainingMonths = 12 - (monthDiff % 12);
                const remainingAmount = monthlyAmount * remainingMonths;
                finalAmount = remainingAmount;
            }

            //it will calculate newPlanAmount/diffrence of month then finalAmount will come
            const taxAmount = finalAmount * (taxRate / 100);
            const totalAmount = finalAmount + taxAmount;

            $scope.selectedPlan.BaseAmount = finalAmount.toFixed(2);
            $scope.selectedPlan.Tax = taxAmount.toFixed(2);
            $scope.selectedPlan.TotalAmount = totalAmount.toFixed(2);
        } else {
            $scope.selectedPlan = {};
        }
    };

    $scope.isPopupVisible = false;
    $scope.popupMessage = "";

    $scope.OpenpopUp = function () {
        if ($scope.plan != null) {
            $scope.isPopupVisible = true;
        }
        else {
            toastr.error("Please Select plan", "Warning");
        }
         
    };

    $scope.ClosepopMsg = function () {
        $scope.isPopupVisible = false;
    }

    $scope.sendPopupMessage = function () {
       
        var plan = JSON.parse($scope.plan);
        console.log($scope.popupMessage);
        var object = {
            "MembersipPlanId": plan.Id,
            "Message": $scope.popupMessage,
            "Amount": $scope.selectedPlan.TotalAmount,
            "Currency": plan.Currency,
            "DeviceType": "Web",
            "Type": "Addon Membership"
          
        };
        membershipServices.SendMail(object).then(function (res) {
            if (!res.IsSuccess) {
                toastr.error(res.Message, "Failed");
                init();
            } else {
                toastr.success("Mail Sent To Admin", "Success");
                $scope.isPopupVisible = false;
            }
        });
       
    };


    $scope.doPayment = function () {

        if (!$scope.IsTermAndConditionAccepted) {
            toastr.error("Please accept Term and Condition", "Warning");
            return false;
        }
        if (confirm("If You have already active plan, then existing plan will be override.")) {
            paymentInstance.requestPaymentMethod(function (err, payload) {
                if (err) {
                    toastr.error(err.message + ". please try again", "Error");
                    console.log('Error', err);
                    return;
                }
                console.log(payload);
                var plan = JSON.parse($scope.plan);
                var object = {
                    "MembershipPlanId": plan.Id,
                    "PaymentStatus": payload.nonce,
                    "PaymentMode": "online",
                    "Description": "payment successfully",
                    "IsRecurring": $scope.isRecurring,
                    "Amount": $scope.selectedPlan.TotalAmount,
                    "Currency": plan.Currency,
                    "DeviceType": "Web",
                    "IsSubscribe": true
                };

                membershipServices.AddonPayment(object).then(function (res) {
                    if (res.Data.PaymentStatus === "Failed") {
                        toastr.error(res.Message, "Failed");
                        init();
                    } else {
                        toastr.success("Payment done Successfully", "Success");
                        $uibModalInstance.dismiss();
                        //$scope.user = userServices.getCurentUser();
                        //var email = $scope.user.Email;
                        //userServices.getUserDetail(email).then(function (res1, err) {
                        //    userServices.saveUserDetail(res1.Data);
                        //    alert(res.Message);
                        //    init();
                        //});
                    }
                });

            });
        }

        //

    }





    init();
});

