'use strict';

/**
 * @ngdoc overview
 * @name trunkApp
 * @description
 * # app
 *
 * Main module of the application.
 */


angular.module('app.controllers', []);
angular.module('app.directives', []);
angular.module('app.services', []);
angular.module('app.filters', []);

angular
    .module('app', [
        'ngAnimate',
        'ngCookies',
        'ngResource',
        'ngSanitize',
        'ngTouch',
        'ngBootstrap',
        'restangular',
        'http-auth-interceptor',
        'LocalStorageModule',
        'ui.select2',
        'ui.router',
        'ui.jq',
        'ui.bootstrap',
        'app.controllers',
        'app.services',
        'app.filters',
        'app.directives',
        'ui.utils',
        'checklist-model',
        'angular-loading-bar',
        'daterangepicker',
        'textAngular',
        //'vcRecaptcha',
       '720kb.datepicker'
    ]).config([
        '$stateProvider', '$urlRouterProvider', '$provide',

function($stateProvider, $urlRouterProvider, $provide) {
    //$httpProvider.interceptors.push('authInterceptorService');

    //configure html5mode
    //            $locationProvider.html5Mode(true).hashPrefix('!');
    $provide.decorator('taOptions', [
        'taRegisterTool', 'appService', '$delegate',
        function(taRegisterTool, appService, taOptions) {

            //var $editor;

            var insertHtml = function(qtvar) {
                var template = '<span>%var%</span>';
                template = template.replace(/%var%/g, qtvar);

                this.$editor().wrapSelection('inserthtml', template);
            };

            taOptions.disableSanitizer = true;

            var dropMenuTemplate = '<div class="insert-var-container" tooltip="Insert Variable">';
            dropMenuTemplate += '<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" ng-mouseup="focusHack()">';
            dropMenuTemplate += 'Insert Variable<span class="caret"></span>';
            dropMenuTemplate += '</button>';
            dropMenuTemplate += '<ul class="dropdown-menu">';
            dropMenuTemplate += '<li ng-repeat="opt in items"><a ng-click="InsertSubject(opt)">{{opt}}</a></li>';
            dropMenuTemplate += '</ul>';
            dropMenuTemplate += '</div>';

            // register the tool with textAngular
            taRegisterTool('insertVariable', {
                display: dropMenuTemplate,
                disabled: function() {

                    // runs as an init function
                    var self = this;
                    self.focusHack = function() {
                        $('.ta-scroll-window [contenteditable]')[0].focus();
                    };
                    self.items = [];
                    appService.getEmailProperties().then(function(result) {
                        self.items = result.values;
                    });

                    self.InsertSubject = function(opt) {
                        insertHtml.call(this, '[[' + opt + ']]');
                    };
                    self.isDisabled = function() {
                        return false;
                    };

                },
                action: function() {}
            });

            return taOptions;

        }
    ]);

    $urlRouterProvider
        .otherwise('/a');
    $stateProvider
        .state('app', {
            abstract: true,
            url: '/app',
            templateUrl: '/public/views/app/main.html',
            resolve: {
                authenticatedApp: [
                    'globalService', 'userService', 'toastService', '$state', 'localStorageService',
                    function(globalService, userService, toastService, $state, localStorageService) {
                        userService.validateSession().then(function() {
                            var id = localStorageService.get('id');
                            userService.getBasicProfileStatus(id).then(function(response) {
                                localStorageService.set('phoneVerified', response.phoneVerified);
                                if (!response.emailVerified) {
                                    localStorageService.set('phoneVerified', "");
                                    localStorageService.set('token', "");
                                    localStorageService.set('refreshToken', "");
                                    localStorageService.set('id', "");
                                    localStorageService.set('role', ""); //if email not verified remove all data from local Storage
                                    userService.validateSession();
                                    $state.go('user.emailVerifyPrompt');
                                } else if (!response.hasBasicProfile) {
                                    $state.go('app.common.signupTwo');
                                }
                            });

                            //                                    var role = localStorageService.get('role');
                            //                                    if (role != 'panelist') {
                            //                                        return $state.go('app.admin.dashboard', { 'role': role });
                            //                                    }
                        }, function(err) {
                            toastService.showError(err);
                            if (!globalService.getIsAuthorised()) {
                                var redirectUrl = document.location.href;
                                return $state.go('user.login', ({ success: redirectUrl }));
                            }
                        });
                        return 'Authenticated';
                    }
                ]
            }
        })
        .state('app.panelist', {
            abstract: true,
            url: '/panelist',
            templateUrl: '/public/views/app/panelist/app.html',
            controller: 'panelistAppCtrl',
            resolve: {
                authenticated: [
                    '$state', 'localStorageService', 'authenticatedApp', function($state, localStorageService, authenticatedApp) {
                        var role = localStorageService.get('role');
                        if (role != 'panelist')
                            $state.go('app.admin.dashboard', { 'role': role });
                    }
                ]
            }

        })
        .state('app.panelist.dashboard', {
            url: '/dashboard',
            templateUrl: '/public/views/app/panelist/partials/dashboard.html',
            controller: 'panelistDashboardCtrl',
            pageTitle: 'Panelist'
        })
        .state('app.panelist.profileDashboard', {
            url: '/profileDashboard',
            templateUrl: '/public/views/app/panelist/partials/profileDashboard.html',
            pageTitle: 'Profiles'
        })
        .state('app.panelist.profile', {
            url: '/profile/:profileId',
            templateUrl: '/public/views/app/panelist/partials/profile.html',
            controller: 'panelistProfileCtrl',
            pageTitle: 'Profile'
        })
        .state('app.panelist.changePassword', {
            url: '/changePassword',
            templateUrl: '/public/views/app/panelist/partials/changePassword.html',
            controller: 'panelistChangePasswordCtrl',
            pageTitle: 'Change Password'
        })
        .state('app.panelist.rewardDashboard', {
            url: '/rewardDashboard',
            templateUrl: '/public/views/app/panelist/partials/rewardDashboard.html',
            controller: 'panelistRewardDashboardCtrl',
            pageTitle: 'Rewards'
        })
        .state('app.panelist.referralDashboard', {
            url: '/referralDashboard',
            templateUrl: '/public/views/app/panelist/partials/referralDashboard.html',
            controller: 'panelistReferralDashboardCtrl',
            pageTitle: 'Referrals'
        })
        .state('app.panelist.redemptionDashboard', {
            url: '/redemptionDashboard',
            templateUrl: '/public/views/app/panelist/partials/redemptionDashboard.html',
            controller: 'panelistRedemptionDashboardCtrl',
            pageTitle: 'Redemption Requests'
        })
        .state('app.panelist.account', {
            url: '/account',
            templateUrl: '/public/views/app/panelist/partials/account.html',
            controller: 'panelistAccountCtrl',
            pageTitle: 'Account'
        })
        .state('app.panelist.editAccount', {
            url: '/editAccount',
            templateUrl: '/public/views/app/panelist/partials/editAccount.html',
            controller: 'panelistEditAccountCtrl',
            pageTitle: 'Edit Account'
        })
        .state('app.panelist.message', {
            url: '/messages',
            templateUrl: '/public/views/app/panelist/partials/message.html',
            controller: 'panelistMessageCtrl',
            pageTitle: 'Messages'
        })
        .state('app.panelist.surveyDashboard', {
            url: '/surveyDashboard',
            templateUrl: '/public/views/app/panelist/partials/surveyDashboard.html',
            controller: 'panelistSurveyDashboardCtrl',
            pageTitle: 'Surveys'
        })
        .state('app.panelist.verifyMobile', {
            url: '/verifyMobile',
            templateUrl: '/public/views/app/panelist/partials/verifyMobile.html',
            controller: 'panelistVerifyMobileCtrl',
            pageTitle: 'Verify Mobile'
        })
        .state('app.panelist.verifyOTP', {
            url: '/verifyOTP',
            templateUrl: '/public/views/app/panelist/partials/verifyOTP.html',
            controller: 'panelistVerifyOTPCtrl',
            pageTitle: 'Verify One Time Password'
        })
        .state('app.common', {
            abstract: true,
            url: '',
            template: '<div ui-view class="fade-in-right-big smooth"></div>'
        })
        .state('app.common.signupTwo', {
            url: '/signup-two',
            templateUrl: '/public/views/app/common/signupTwo.html',
            controller: 'signupTwoCtrl',
            pageTitle: 'Signup Page'
        })
        .state('app.admin', {
            abstract: true,
            url: '/:role',
            templateUrl: '/public/views/app/admin/app.html',
            resolve: {
                authenticated: [
                    '$state', 'localStorageService', 'authenticatedApp',
                    function($state, localStorageService, authenticatedApp) {
                        var role = localStorageService.get('role');
                        if (role == 'panelist')
                            $state.go('app.panelist.dashboard');
                    }
                ]
            }
        })
        .state('app.admin.dashboard', {
            url: '/dashboard',
            templateUrl: '/public/views/app/admin/partials/dashboard.html',
            controller: 'adminDashboardCtrl',
            pageTitle: 'Dashboard'
        })
        .state('app.admin.changePassword', {
            url: '/changePassword',
            templateUrl: '/public/views/app/admin/partials/changePassword.html',
            controller: 'adminChangePasswordCtrl',
            pageTitle: 'Change Password'
        })
        .state('app.admin.rewardDashboard', {
            url: '/rewardDashboard',
            templateUrl: '/public/views/app/admin/partials/rewardDashboard.html',
            controller: 'adminRewardDashboardCtrl',
            pageTitle: 'Rewards'
        })
        .state('app.admin.rewardDetails', {
            url: '/:rewardId/rewardDetails',
            templateUrl: '/public/views/app/admin/partials/rewardDetails.html',
            controller: 'adminRewardDetailsCtrl',
            pageTitle: 'Reward Details'
        })

       .state('app.admin.referralDashboard', {
            url: '/referralDashboard',
            templateUrl: '/public/views/app/admin/partials/referralDashboard.html',
            controller: 'adminReferralDashboardCtrl',
            pageTitle: 'Referrals'
        })
        .state('app.admin.referralDetails', {
            url: '/:referralId/referralDetails',
            templateUrl: '/public/views/app/admin/partials/referralDetails.html',
            controller: 'adminReferralDetailsCtrl',
            pageTitle: 'Referral Details'
        })
        .state('app.admin.redemptionDashboard', {
            url: '/redemptionDashboard',
            templateUrl: '/public/views/app/admin/partials/redemptionDashboard.html',
            controller: 'adminRedemptionDashboardCtrl',
            pageTitle: 'Redemptions'
        })
        .state('app.admin.redemptionRequestDetails', {
            url: '/:redemptionRequestId/requestDetails',
            templateUrl: '/public/views/app/admin/partials/redemptionRequestDetails.html',
            controller: 'adminRedemptionRequestDetailsCtrl',
            pageTitle: 'Redemption Details'
        })
        .state('app.admin.surveyDashboard', {
            url: '/surveyDashboard',
            templateUrl: '/public/views/app/admin/partials/surveyDashboard.html',
            controller: 'adminSurveyDashboardCtrl',
            pageTitle: 'Surveys'
        })
        .state('app.admin.editSurvey', {
            url: '/:surveyId/editSurvey',
            templateUrl: '/public/views/app/admin/partials/editSurvey.html',
            controller: 'adminEditSurveyCtrl',
            pageTitle: 'Edit Surveys'
        })
        .state('app.admin.surveyDetails', {
            url: '/:surveyId/surveyDetails',
            templateUrl: '/public/views/app/admin/partials/surveyDetails.html',
            controller: 'adminSurveyDetailsCtrl',
            pageTitle: 'Survey Details'
        })
//                 .state('app.admin.surveyUniqueLinksDetails', {
//                     url: '/:surveyId/surveyUniqueLinksDetails',
//                     templateUrl: '/public/views/app/admin/partials/surveyUniqueLinksDetails.html',
//                     controller: 'adminSurveyUniqueLinksDetailsCtrl',
//                     pageTitle: 'Survey Unique Links Details'
//                 })
        .state('app.admin.createSurvey', {
            url: '/createSurvey',
            templateUrl: '/public/views/app/admin/partials/createSurvey.html',
            controller: 'adminCreateSurveyCtrl',
            pageTitle: 'Create Surveys'
        })
        .state('app.admin.panelistDashboard', {
            url: '/panelistDashboard',
            templateUrl: '/public/views/app/admin/partials/panelistDashboard.html',
            controller: 'adminPanelistDashboardCtrl',
            pageTitle: 'Panelists'
        })
        .state('app.admin.registeredPanelistOnlyDashboard', {
            url: '/registeredOnlyPanelists',
            templateUrl: '/public/views/app/admin/partials/registeredPanelistOnlyDashboard.html',
            controller: 'adminRegisteredPanelistOnlyDashboardCtrl',
            pageTitle: 'Registered Panelists'
        })
        .state('app.admin.basicProfilePanelistOnlyDashboard', {
            url: '/basicProfilePanelistsOnly',
            templateUrl: '/public/views/app/admin/partials/basicProfilePanelistOnlyDashboard.html',
            controller: 'adminBasicProfilePanelistOnlyDashboardCtrl',
            pageTitle: 'Basic Profile Panelists'
        })
        .state('app.admin.unsubscribedPanelistOnlyDashboard', {
            url: '/unsubscribedPanelists',
            templateUrl: '/public/views/app/admin/partials/unsubscribedPanelistOnlyDashboard.html',
            controller: 'adminUnsubscribedPanelistOnlyDashboardCtrl',
            pageTitle: 'Unsubscribed Panelists'
        })
        .state('app.admin.deletedPanelistOnlyDashboard', {
            url: '/deletedPanelists',
            templateUrl: '/public/views/app/admin/partials/deletedPanelistOnlyDashboard.html',
            controller: 'adminDeletedPanelistOnlyDashboardCtrl',
            pageTitle: 'Deleted Panelists'
        })
        .state('app.admin.legacyErrorPanelistOnlyDashboard', {
            url: '/legacyErrorPanelists',
            templateUrl: '/public/views/app/admin/partials/legacyErrorPanelistOnlyDashboard.html',
            controller: 'adminLegacyErrorPanelistOnlyDashboardCtrl',
            pageTitle: 'Legacy Error Panelists'
        })
        .state('app.admin.bouncedPanelistOnlyDashboard', {
            url: '/bouncedPanelists',
            templateUrl: '/public/views/app/admin/partials/bouncedPanelistOnlyDashboard.html',
            controller: 'adminBouncedPanelistsOnlyDashboardCtrl',
            pageTitle:'Bounced Panelists'
        })
        .state('app.admin.panelist', {
            abstract: true,
            url: '/:panelistId',
            templateUrl: '/public/views/app/admin/partials/panelist.html'
        })
        .state('app.admin.panelist.panelistDetails', {
            url: '/panelistDetails',
            templateUrl: '/public/views/app/admin/partials/panelistDetails.html',
            controller: 'adminPanelistDetailsCtrl',
            pageTitle: 'Panelist Details'
        })
        .state('app.admin.panelist.editPanelistAccount', {
            url: '/editPanelistAccount',
            templateUrl: '/public/views/app/admin/partials/editPanelistAccount.html',
            controller: 'adminEditPanelistAccountCtrl',
            pageTitle: 'Edit Panelist'
        })
        .state('app.admin.panelist.profile', {
            url: '/profile/:profileId',
            templateUrl: '/public/views/app/admin/partials/panelistProfile.html',
            controller: 'adminPanelistProfileCtrl',
            pageTitle: 'Panelist Profile'
        })
        .state('app.admin.labelDashboard', {
            url: '/labelDashboard',
            templateUrl: '/public/views/app/admin/partials/labelDashboard.html',
            controller: 'adminLabelDashboardCtrl',
            pageTitle: 'Labels'
        })
        .state('app.admin.sampleDashboard', {
            url: '/sampleDashboard',
            templateUrl: '/public/views/app/admin/partials/sampleDashboard.html',
            controller: 'adminSampleDashboardCtrl',
            pageTitle: 'Samples'
        })
        .state('app.admin.secDashboard', {
            url: '/secDashboard',
            templateUrl: '/public/views/app/admin/partials/secDashboard.html',
            controller: 'adminSecDashboardCtrl',
            pageTitle: 'SEC'
        })
        .state('app.admin.sampleQuestions', {
            url: '/:sampleId/questions',
            templateUrl: '/public/views/app/admin/partials/sampleQuestions.html',
            controller: 'adminSampleQuestionsCtrl',
            pageTitle: 'Sample Questions'
        })
        .state('app.admin.secQuestions', {
            url: '/:secId/secquestions',
            templateUrl: '/public/views/app/admin/partials/secQuestions.html',
            controller: 'adminSecQuestionsCtrl',
            pageTitle: 'Sec Questions'
        })
        .state('app.admin.redemptionModeDashboard', {
            url: '/redemptionModeDashboard',
            templateUrl: '/public/views/app/admin/partials/redemptionModeDashboard.html',
            controller: 'adminRedemptionModeDashboardCtrl',
            pageTitle: 'Redemption Modes'
        })
        .state('app.admin.surveyEmailReportDashboard', {
            url: '/surveyEmailReportDashboard',
            templateUrl: '/public/views/app/admin/partials/surveyEmailReportDashboard.html',
            controller: 'adminSurveyEmailReportDashboardCtrl',
            pageTitle: 'Survey Email Reports'
        })
        .state('app.admin.placeDashboard', {
            url: '/placeDashboard',
            templateUrl: '/public/views/app/admin/partials/placeDashboard.html',
            controller: 'adminPlaceDashboardCtrl',
            pageTitle: 'Places'
        })
        .state('app.admin.newsletterDashboard', {
            url: '/newsletterDashboard',
            templateUrl: '/public/views/app/admin/partials/newsletterDashboard.html',
            controller: 'adminNewsletterDashboardCtrl',
            pageTitle: 'Newsletters'
        })
        .state('app.admin.newsletterDetails', {
            url: '/:newsletterId/newsletterId',
            templateUrl: '/public/views/app/admin/partials/newsletterDetails.html',
            controller: 'adminNewsletterDetailsCtrl',
            pageTitle: 'Newsletter Details'
        })
        .state('app.admin.partnerDashboard', {
            url: '/partnerDashboard',
            templateUrl: '/public/views/app/admin/partials/partnerDashboard.html',
            controller: 'adminPartnerDashboardCtrl',
            pageTitle: 'Partners'
        })
        .state('app.admin.sweepstakeDashboard', {
            url: '/sweepstakeDashboard',
            templateUrl: '/public/views/app/admin/partials/sweepstakeDashboard.html',
            controller: 'adminSweepstakeDashboardCtrl',
            pageTitle: 'Sweepstakes'
        })
           .state('app.admin.sweepstakeDetails', {
               url: '/:sweepstakeId/sweepstakeDetails',
               templateUrl: '/public/views/app/admin/partials/sweepstakeDetails.html',
               controller: 'adminSweepstakeDetailsCtrl',
               pageTitle: 'Sweepstake Details'
           })
        .state('app.admin.emailsForSchedule', {
            url: '/emailsForSchedule?surveyId&emailScheduleId',
            templateUrl: '/public/views/app/admin/partials/emailsForSchedule.html',
            controller: 'adminEmailsForScheduleCtrl',
            pageTitle: 'Emails For Schedule'
        })
        .state('app.admin.linksForSurvey', {
            url: '/:surveyId/linksForSurvey',
            templateUrl: '/public/views/app/admin/partials/linksForSurvey.html',
            controller: 'adminLinksForSurveyCtrl',
            pageTitle: 'Links For Survey'
        })
        .state('app.admin.reportsForSurvey', {
            url: '/:surveyId/reportsForSurvey',
            templateUrl: '/public/views/app/admin/partials/reportsForSurvey.html',
            controller: 'adminReportsForSurveyCtrl',
            pageTitle: 'Reports For Survey'
        })
        .state('app.admin.messageDashboard', {
            url: '/messageDashboard',
            templateUrl: '/public/views/app/admin/partials/messageDashboard.html',
            controller: 'adminMessageDashboardCtrl',
            pageTitle: 'Messages'
        })
        .state('app.admin.helpDashboard', {
            url: '/helpDashboard',
            templateUrl: '/public/views/app/admin/partials/helpDashboard.html',
            controller: 'adminHelpDashboardCtrl',
            pageTitle: 'Help'
        })
        .state('app.admin.profileDashboard', {
            url: '/profileDashboard',
            templateUrl: '/public/views/app/admin/partials/profileDashboard.html',
            controller: 'adminProfileDashboardCtrl',
            pageTitle: 'Profiles'
        })
        .state('app.admin.profileQuestions', {
            url: '/profile/:profileId/questions',
            templateUrl: '/public/views/app/admin/partials/profileQuestions.html',
            controller: 'adminProfileQuestionsCtrl',
            pageTitle: 'Profile Questions'
        })
        .state('app.admin.editProfileQuestion', {
            url: '/profile/:profileId/questions/:questionId/edit',
            templateUrl: '/public/views/app/admin/partials/editProfileQuestion.html',
            controller: 'adminEditProfileQuestionCtrl',
            pageTitle: 'Edit Profile Question'
        })
        .state('app.admin.profileQuestionDetails', {
            url: '/profile/:profileId/questions/:questionId/details',
            templateUrl: '/public/views/app/admin/partials/profileQuestionDetails.html',
            controller: 'adminProfileQuestionDetailsCtrl',
            pageTitle: 'Profile Question Details'
        })
        .state('app.admin.createProfileQuestion', {
            url: '/profile/:profileId/createProfileQuestion',
            templateUrl: '/public/views/app/admin/partials/createProfileQuestion.html',
            controller: 'adminCreateProfileQuestionCtrl',
            pageTitle: 'Create Profile Question'
        })
        .state('app.admin.marketingLinkDashboard', {
            url: '/marketingLinkDashboard',
            templateUrl: '/public/views/app/admin/partials/marketingLinkDashboard.html',
            controller: 'adminMarketingLinkDashboardCtrl',
            pageTitle: 'Marketing Links'
        })
        .state('app.admin.marketingLinkUsers', {
            url: '/:marketingLinkId/marketingLinkUsers',
            templateUrl: '/public/views/app/admin/partials/marketingLinkUsers.html',
            controller: 'adminMarketingLinkUsersCtrl',
            pageTitle: 'Marketing Link Users'
        })
         .state('user', {
            abstract: true,
            url: '/user',
            template: '<div ui-view class="fade-in-right-big smooth"></div>',
            resolve: {
                authenticated: [
                    '$state', 'globalService', 'userService', 'localStorageService', '$stateParams',
                    function($state, globalService, userService, localStorageService, $stateParams) {
                        userService.validateSession().then(function() {
                            if (globalService.getIsAuthorised()) {
                                var id = localStorageService.get('id');
                                var role = localStorageService.get('role');
                                userService.getBasicProfileStatus(id).then(function(response) {
                                    localStorageService.set('phoneVerified', response.phoneVerified);
                                    if (!response.emailVerified) {
                                        localStorageService.set('phoneVerified', "");
                                        localStorageService.set('token', "");
                                        localStorageService.set('refreshToken', "");
                                        localStorageService.set('id', "");
                                        localStorageService.set('role', ""); //if email not verified remove all data from local Storage
                                        userService.validateSession();
                                        $state.go('user.emailVerifyPrompt');
                                    } else if (!response.hasBasicProfile) {
                                        $state.go('app.common.signupTwo');
                                    } else {
                                        if ($stateParams.success) {
                                            window.location.href = $stateParams.success;
                                        } else if (role == 'panelist')
                                            $state.go('app.panelist.dashboard');
                                        else
                                            $state.go('app.admin.dashboard', { 'role': role });
                                    }
                                });
                                //
                                //                                        var role = localStorageService.get('role');
                                //                                        if (role == 'panelist')
                                //                                            return $state.go('app.panelist.dashboard');
                                //                                        else
                                //                                            return $state.go('app.admin.dashboard', { 'role': role });
                            }
                        }, function(err) {
                        });
                    }
                ]
            }
        })
        .state('user.signup', {
            url: '/signup',
            templateUrl: '/public/views/user/signup.html',
            controller: 'signUpCtrl',
            pageTitle: 'Signup'
        })
        .state('user.signupComplete', {
            url: '/signupComplete',
            templateUrl: '/public/views/user/signupComplete.html',
            pageTitle: 'Signup Complete'
        })
        .state('user.login', {
            url: '/login?success',
            templateUrl: '/public/views/user/login.html',
            controller: 'loginCtrl',
            pageTitle: 'Login'
        })

        .state('user.externalLogin', {
            url: '/externalLogin',
            templateUrl: '/public/views/user/externalLogin.html',
            controller: 'externalLoginCtrl',

        })
        .state('user.forgotPassword', {
            url: '/forgotPassword',
            templateUrl: '/public/views/user/forgotPassword.html',
            controller: 'forgotPasswordCtrl',
            pageTitle: 'Forgot Password'
        })
        .state('user.verifyEmail', {
            url: '/verifyEmail',
            templateUrl: '/public/views/user/verifyEmail.html',
            controller: 'verifyEmailCtrl',
            pageTitle: 'Verify Email'
        })
        .state('user.resetPassword', {
            url: '/resetPassword?email&token',
            templateUrl: '/public/views/user/resetPassword.html',
            controller: 'resetPasswordCtrl',
            pageTitle: 'Reset Password'
        })
        .state('user.emailVerified', {
            url: '/emailVerified',
            templateUrl: '/public/views/user/emailVerified.html',
            pageTitle: 'Email Verified'
        })
        .state('user.emailVerificationError', {
            url: '/emailVerificationError',
            templateUrl: '/public/views/user/emailVerificationError.html',
            pageTitle: 'Email Verification Error'
        })
        .state('user.emailVerifyPrompt', {
            url: '/emailVerifyPrompt',
            templateUrl: '/public/views/user/emailVerifyPrompt.html',
            pageTitle: 'Email Verification Prompt'
        })
        .state('common', {
            abstract: true,
            url: '',
            template: '<div ui-view class="fade-in-right-big smooth"></div>',
        })
        .state('common.surveyStartError', {
            url: '/surveyStartError?reason',
            templateUrl: '/public/views/common/surveyStartError.html',
            controller: function($scope, $stateParams) {
                $scope.reason = $stateParams.reason;
            },
            pageTitle: 'Survey Start Error'
        })
        .state('common.home', {
            url: '/home',
            templateUrl: '/public/views/common/home.html',
            pageTitle: 'Home'
        })
        .state('common.surveyFinished', {
            url: '/survey/finish?id&status',
            templateUrl: function($stateParams) {
                return '/public/views/app/panelist/partials/surveyFinished/' + $stateParams.status + '.html';
            },
            controller: 'panelistSurveyFinishedCtrl'
        })
        .state('common.surveyEndError', {
            url: '/surveyEndError?reason',
            templateUrl: '/public/views/common/surveyEndError.html',
            controller: function($scope, $stateParams) {
                $scope.reason = $stateParams.reason;
            },
            pageTitle: 'Survey Start Error'
        });

   }])
.run([
        'Restangular', 'globalService', 'userService', '$rootScope', '$state','$window','$location',
        function(restangular, globalService, userService, $rootScope, $state,$window,$location) {
            $window.ga('create', 'UA-XXXXXXXX-X', 'auto');
            $rootScope.$on("$stateChangeSuccess", function () {
                $window.ga('send', 'pageview', $location.path());

                $rootScope.pageTitle = $state.current.pageTitle || 'Default';

            });
            restangular.setBaseUrl(globalService.getBaseUrl());
            userService.validateSession();
        }
    ])
    .controller('MainController', [
        '$scope', 'globalService', function($scope, globalService) {
            $scope.count = 10;
            $scope.isLoggedIn = globalService.getIsAuthorised();
            //for date
            $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
            $scope.format = $scope.formats[1];
            //for links to not act as relative url
            $scope.getLink = function(url) {
                if (!/^https?:\/\//i.test(url)) {
                    url = 'http://' + url;
                }
                return url;
            };
        }
    ])

    .controller('DatepickerDemoCtrl', function ($scope) {
        // Disable weekend selection
        //        $scope.disabled = function (date, mode) {
        //            return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
        //        };

        $scope.toggleMin = function () {
            $scope.minDate = $scope.minDate ? null : new Date();
        };
        $scope.toggleMin();
        $scope.open = function ($event) {
            $event.preventDefault();
            $event.stopPropagation();

            $scope.opened = true;
        };
        $scope.dateOptions = {
            formatYear: 'yy',
            startingDay: 1
            
        };
        $scope.maxDate = new Date();
        $scope.maxDate.setFullYear($scope.minDate.getFullYear() - 15);
        $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
        $scope.format = $scope.formats[1];
    })
//    .controller('DatepickerCtrl', function($scope) {
//        $scope.myDate = new Date();
//        $scope.minDate = new Date(
//            $scope.myDate.getFullYear(),
//            $scope.myDate.getMonth() - 2,
//            $scope.myDate.getDate());
//        $scope.maxDate = new Date(
//            $scope.myDate.getFullYear(),
//            $scope.myDate.getMonth() + 2,
//            $scope.myDate.getDate());
//        $scope.onlyWeekendsPredicate = function(date) {
//            var day = date.getDay();
//            return day === 0 || day === 6;
//        }
//    })

    .controller('profilesProgressCtrl', [
        '$scope', 'appService', '$stateParams', function ($scope, appService, $stateParams) {
            $scope.vm = {};
            $scope.vm.profiles = [];
            $scope.vm.profilesCompleted = null;
            $scope.vm.progressStatus = '';
            var panelistId = $stateParams.panelistId || '';
            //get all profiles
            appService.getProfiles(panelistId).then(function (result) {
                $scope.vm.profiles = result.profiles;
                var sum = 0;
                angular.forEach($scope.vm.profiles, function (value) {
                    sum += value.percentageCompletion;
                });
                $scope.vm.profilesCompleted = Math.floor(sum / $scope.vm.profiles.length);
                if ($scope.vm.profilesCompleted < 25)
                    $scope.vm.progressStatus = 'danger';
                else if ($scope.vm.profilesCompleted <= 75)
                    $scope.vm.progressStatus = 'warning';
                else
                    $scope.vm.progressStatus = 'success';
            });
        }
    ])
 .filter('unsafe', function ($sce) {

     return function (val) {

         return $sce.trustAsHtml(val);

     };

 });;
'use strict';

/**
 * @ngdoc directive
 * @name trunkApp.directive:nav
 * @description
 * # nav
 */
angular.module('app.directives')
    .directive('uiNav', [
        '$timeout', function($timeout) {
            return {
                restrict: 'AC',
                link: function(scope, el, attr) {
                    var _window = $(window);
                    var _mb = 768;
                    // unfolded
                    $(el).on('click', 'a', function(e) {
                        var _this = $(this);
                        _this.parent().siblings(".active").toggleClass('active');
                        _this.parent().toggleClass('active');
                        _this.next().is('ul') && e.preventDefault();
                        _this.next().is('ul') || ((_window.width() < _mb) && $('.app-aside').toggleClass('show'));
                    });

                    // folded
                    var wrap = $('.app-aside'), next;
                    $(el).on('mouseenter', 'a', function(e) {
                        if (!$('.app-aside-fixed.app-aside-folded').length || (_window.width() < _mb)) return;
                        var _this = $(this);

                        next && next.trigger('mouseleave.nav');

                        if (_this.next().is('ul')) {
                            next = _this.next();
                        } else {
                            return;
                        }

                        next.appendTo(wrap).css('top', _this.offset().top - _this.height());
                        next.on('mouseleave.nav', function(e) {
                            next.appendTo(_this.parent());
                            next.off('mouseleave.nav');
                            _this.parent().removeClass('active');
                        });
                        _this.parent().addClass('active');

                    });

                    wrap.on('mouseleave', function(e) {
                        next && next.trigger('mouseleave.nav');
                    });
                }
            };
        }
    ]);;
'use strict';

/**
 * @ngdoc directive
 * @name trunkApp.directive:uiButterbar
 * @description
 * # uiButterbar
 */
angular.module('app')
    .directive('uiButterbar', [
        '$rootScope', '$location', '$anchorScroll', function($rootScope, $location, $anchorScroll) {
            return {
                restrict: 'AC',
                template: '<span class="bar"></span>',
                link: function(scope, el, attrs) {
                    el.addClass('butterbar hide');
                    scope.$on('$stateChangeStart', function(event) {
                        $location.hash('app');
                        $anchorScroll();
                        el.removeClass('hide').addClass('active');
                    });
                    scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState) {
                        event.targetScope.$watch('$viewContentLoaded', function() {
                            el.addClass('hide').removeClass('active');
                        })
                    });
                }
            };
        }
    ]);;
'use strict';

/**
 * @ngdoc service
 * @name uiApp.globalService
 * @description
 * # globalService
 * Factory in the uiApp.
 */
angular.module('app')
    .factory('globalService', [
        '$rootScope', 'Restangular', '$interval', '$location',
        function ($rootScope, restangular, $interval, $location) {
            var self = {};
            self.isAuthorised = false;
            self.messages = [];
            self.baseUrl = "http://localhost:1582/api/v1";
            //to remove the messages which have expired.
            $interval(
                function () {
                    angular.forEach(self.messages, function (val) {
                        var currentTime = new Date();
                        if (val.expireBy.getSeconds() <= currentTime.getSeconds())
                            self.removeMessage(val);
                    });
                }, 1000);

            self.setIsAuthorised = function (loginStatus) {
                self.isAuthorised = loginStatus;
            };
            self.getIsAuthorised = function () {
                return self.isAuthorised;
            };
            /*
         * type - info, error, success
         */
            self.setMessage = function (message, type) {
                var t = new Date();
                t.setSeconds(t.getSeconds() + 5);
                self.messages.push({ text: message, type: type, expireBy: t });
            };
            self.getMessages = function () {
                return self.messages;
            };
            self.removeMessage = function (message) {
                var idx = self.messages.indexOf(message);
                if (idx != -1)
                    self.messages.splice(idx, 1);
            };
            self.getOnlineStatus = function () {
                return restangular.all("ping").getList();
            };
            self.getBaseUrl = function () {
                if ($location.host() == 'localhost') {
                    self.baseUrl = "http://localhost:1582/api/v1";
                    //                    self.baseUrl = "http://localhost:81/api/v1";
//                    self.baseUrl = "http://137.116.155.221/api/v1";
                } else {
                    self.baseUrl = "https://" + $location.host() + "/api/v1";
                }
                return self.baseUrl;
            };
            self.getUrl = function (relativeUrl) {
                return self.baseUrl + relativeUrl;
            };
            self.setUrl = function (object) {
                return jQuery.param(object);
            };
            return self;
        }
    ]);;
'use strict';

/**
 * @ngdoc service
 * @name ui
 Notificationservice
 * @description
 * # Notificationservice
 * Service in the uiApp.
 */
angular.module('app')
    .factory('toastService', function() {

        var self = this;
        self.show = function(msg) {
            toastr.success(msg);
        };
        self.showError = function(msg) {
            toastr.error(msg);
        }
        //self.showMobileVerification = function (msg) {
        //    toastr.options = {
        //        timeOut: 0,
        //        extendedTimeOut: 0,
        //        tapToDismiss: false,
        //        onclick: function () {
        //            $state.go('user.verifyMobile');
        //        }
        //    };
        //    toast = toastr.error(msg);
        //};

        //self.close = function () {
        //    toast.remove();
        //};
        return self;


        // AngularJS will instantiate a singleton by calling "new" on this function
    });;
'use strict';

/**
 * @ngdoc service
 * @name ui
 userService
 * @description
 * # userService
 * Factory in the uiApp.
 */
angular.module('app')
    .factory('userService', [
        "Restangular", "$http", 'localStorageService', 'globalService', '$q',
        function (restangular, $http, localStorageService, globalService, $q) {
            var self = this;
            self.externalAuthData = {
                provider: "",
                userName: "",
                externalAccessToken: "",
                email: "",
                referralId: "",
                marketingId: ""
            };

            //   self.recaptchaPublicKey = '6LcNHgsTAAAAAPHFGPphSyIZ1CuLQrl9QYPj4Qgl';

            //login for the entire app
            self.login = function (email, password) {

                var data = {
                    username: email,
                    password: password,
                    client_id: 'ngApp',
                    grant_type: 'password'
                };
                var dataEncoded = $.param(data, true);
                return restangular.all('accounts').customPOST(dataEncoded, 'login', {},
                    {
                        'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8"
                    }
                );
            };
          

            self.signUp = function (email, mobile, password, confirmPassword, referralId, marketingId, response, widgetId) {
                var data = {
                    UserName: email,
                    Mobile: mobile,
                    Password: password,
                    ConfirmPassword: confirmPassword,
                    referralId: referralId,
                    marketingId: marketingId
                  //  response: response,
                   // challenge: widgetId
                }
                return restangular.all('').customPOST(data, 'users');
            };
            self.externalLogin = function (email, mobile, provider, externalToken, referralId, marketingId) {
                var data = {
                    UserName: email,
                    PhoneNumber: mobile,
                    Provider: provider,
                    ExternalAccessToken: externalToken,
                    referralId: referralId,
                    marketingId: marketingId
                };
                return restangular.all('accounts').customPOST(data, 'RegisterExternal');
            };
            self.obtainAccessToken = function (provider, externalToken) {
                var data = {
                    provider: provider,
                    externalAccessToken: externalToken
                };
                return restangular.all('accounts').customPOST(data, 'ObtainLocalAccessToken');
            };
            self.forgotPassword = function (email) {
                var data = { Email: email };
                return restangular.all('accounts').customPOST(data, 'forgotPassword');
            };
            self.resetPassword = function (password, email, token) {
                var data = { Email: email, Password: password, Token: token };
                return restangular.all('accounts').customPOST(data, 'resetPassword');
            };
            self.getReferralSources = function () {
                return restangular.all('referralSources').customGET();
            };
            self.getBasicProfileStatus = function (id) {
                return restangular.one('users', id).all('basicProfileStatus').customGET();
            };
            self.updateAccount = function (user) {
                var id = localStorageService.get('id');
                var data = {
                    firstName: user.firstName,
                    lastName: user.lastName,
                    Gender: user.gender,
                    Mobile: user.mobile,
                    DateOfBirth: new Date(user.dateOfBirth).toDateString(),
                    ReferralSource: user.referralSource,
                    AddressLine1: user.addressLine1,
                    Country: user.country,
                    State: user.state,
                    City: user.city,
                    Pincode: user.pincode,
                    AcceptTerms: "true"
                }
                if (user.addressLine2)
                    data.AddressLine2 = user.addressLine2;
                return restangular.one('users', id).customPUT(data);
            };

            self.editAccountByPanelist = function (user, dateFilled) {
                var id = localStorageService.get('id');
                var data = {
                    firstName: user.firstName,
                    lastName: user.lastName,
                    Gender: user.gender,
                    Mobile: user.mobile,
                    DateOfBirth: new Date(dateFilled).toDateString(),
                    ReferralSource: user.referralSource,
                    AddressLine1: user.addressLine1,
                    Country: user.country,
                    State: user.state,
                    City: user.city,
                    Pincode: user.pincode,
                    AcceptTerms: "true"
                }
                if (user.addressLine2)
                    data.AddressLine2 = user.addressLine2;
                return restangular.one('users', id).customPUT(data);
            };
            self.validateSession = function () {
             var deferred = $q.defer();
             var token = localStorageService.get('token');
             var expiryDate = localStorageService.get('expiry');
             var dateExpiry = new Date(expiryDate);
             var timeExpiry = dateExpiry.getTime();
                var d = new Date();
                var currentTime = d.getTime();
                if (timeExpiry > currentTime && token!==null && angular.isDefined(token)) {
                    $http.defaults.headers.common = { 'Authorization': token };
                    self.checkLoginStatus().then(function () {
                        globalService.setIsAuthorised(true);
                        deferred.resolve('Authorised');
                    }, function () {
                        localStorageService.set('token', "");
                        var refreshToken = localStorageService.get('refreshToken');
                        if (refreshToken != null && angular.isDefined(refreshToken)) {
                            globalService.setIsAuthorised(false); //todo:create a request with refresh token
                            deferred.reject('Not Authorised');
                        } else {
                            globalService.setIsAuthorised(false);
                            deferred.reject('Not Authorised');
                        }
                    });
                } else {
                    globalService.setIsAuthorised(false);
                    deferred.reject('Not Authorised');
                }
                return deferred.promise;
            };
            //get user information
            self.getUserInfo = function (panelistId) {
                var id = panelistId || localStorageService.get('id');
                return restangular.one('users', id).customGET();
            }
            self.verifyMobile = function (mobile) {
                var data = {
                    phoneNumber: mobile
                };
                return restangular.all('accounts').customPOST(data, 'verifyMobile');
            };
            self.verifyEmail = function (email) {
                var data = {
                    email: email
                };
                return restangular.all('accounts').customPOST(data, 'verifyemail');
            };
            self.verifyMobileCode = function (oneTimePassword) {
                var data = {
                    token: oneTimePassword
                };
                return restangular.all('accounts').customPOST(data, 'verifyMobileCode');
            };
            self.checkLoginStatus = function () {
                return restangular.all('accounts').all('loginStatus').customGET();
            };
            //for logout
            self.logout = function () {
                //return restangular.all('accounts').all('logOut').customPOST({ tokenId: "dafsfasfdsf" });
                $http.defaults.headers.common = { 'Authorization': '' };
                localStorageService.set('token', "");
                localStorageService.set('refreshToken', "");
                localStorageService.set('id', "");
                localStorageService.set('role', "");
                localStorageService.set('phoneVerified', "");
                localStorageService.cookie.clearAll();
                globalService.setIsAuthorised(false);
            };
            return self;
        }
    ]);;
angular.module('app')
    .factory('appService', [
        'localStorageService',
        "Restangular",
        function (localStorageService, restangular) {
            var id = localStorageService.get('id');
            var role = localStorageService.get('role');
            var self = this;
            //get all profiles for a panelist
            self.getProfiles = function (panelistId) {
                if (role == 'panelist') //get all profiles for a panelist
                    return restangular.one('users', id).customGET('profiles');
                else //get all profiles for a admin
                {
                    panelistId = panelistId || '';
                    if (panelistId == '')
                        return restangular.all('').customGET('profiles');
                    else
                        return restangular.one('users', panelistId).customGET('profiles');
                }
            };

            //create profile
            self.createProfile = function (name, description, displayOrder) {
                var data = {
                    name: name,
                    description: description,
                    displayOrder: displayOrder
                };
                return restangular.all('profiles').customPOST(data);
            };
            //update profile
            self.editProfile = function (profileId, name, description, displayOrder) {
                var data = {
                    name: name,
                    description: description,
                    displayOrder: displayOrder
                };
                return restangular.one('profiles', profileId).customPUT(data);
            };
            //delete profile
            self.deleteProfile = function (profileId) {
                return restangular.one('profiles', profileId).remove();
            }
            //get single profile for a panelist
            self.getProfile = function (profileId, panelistId) {
                panelistId = panelistId || id;
                return restangular.one('users', panelistId).one('profiles', profileId).customGET();
            };
            //get questions for profile
            self.getQuestionsForProfile = function (profileId) {
                return restangular.one('profiles', profileId).customGET('questions');
            }
            //get single profile question
            self.getProfileQuestion = function (profileId, questionId) {
                return restangular.one('profiles', profileId).one('questions', questionId).customGET();
            }
            //create profile question
            self.createProfileQuestion = function (profileId, question) {
                var data = {
                    text: question.text,
                    hint: question.hint,
                    displayOrder: question.displayOrder,
                    displayType: question.displayType,
                    isActive: question.isActive,
                    options: question.options
                }
                return restangular.one('profiles', profileId).all('questions').customPOST(data);
            };
            //edit profile question
            self.editProfileQuestion = function (profileId, questionId, question) {
                var data = {
                    text: question.text,
                    hint: question.hint,
                    displayOrder: question.displayOrder,
                    displayType: question.displayType,
                    isActive: question.isActive,
                    options: question.options
                }
                return restangular.one('profiles', profileId).one('questions', questionId).customPUT(data);
            };
            //delete profile question
            self.deleteProfileQuestion = function (profileId, questionId) {
                return restangular.one('profiles', profileId).one('questions', questionId).remove();
            }
            //update profile for a panelist
            self.updateProfileForSingleUser = function (profileId, userResponse, panelistId) {
                panelistId = panelistId || id;
                return restangular.one('users', panelistId).one('profiles', profileId).post('', userResponse);
            };
            //get display types
            self.getQuestionDisplayTypes = function () {
                return restangular.all('questionDisplayTypes').customGET();
            }
            //get user Pic 
            self.getUserPic = function (panelistId) {
                panelistId = panelistId || id;
                return restangular.one('users', panelistId).customGET('photo');
            };
            //get labels for admin
            self.getLabels = function (page, count, panelistId) {
                panelistId = panelistId || '';
                if (panelistId == '')
                    return restangular.all('').customGET('labels', { page: page, count: count });
                else
                    return restangular.one('users', panelistId).customGET('labels', { page: page, count: count });
            };
            //create label for admin
            self.createLabel = function (name, description) {
                var data = {
                    name: name,
                    description: description
                };
                return restangular.all('labels').customPOST(data);
            };
            //edit label for admin
            self.editLabel = function (labelId, name, description) {
                var data = {
                    name: name,
                    description: description
                };
                return restangular.one('labels', labelId).customPUT(data);
            };
            //assign labels to panelist
            self.assignLabels = function (labelIds, panelistId) {
                var data = {
                    labelIds: labelIds
                };
                return restangular.one('users', panelistId).customPOST(data, 'labels');
            };
            //delete label
            self.deleteLabel = function (labelId) {
                return restangular.one('labels', labelId).remove();
            };
            //download basic profile details for a single panelist
            self.downloadBasicProfileDetails = function (panelistId) {
                return restangular.one('users', panelistId).all('profilesExport').customGET('');
            };

            //download reward details for a single panelist
            self.downloadRewardDetails = function (panelistId) {
                return restangular.one('users', panelistId).all('rewards').customGET('export');
            };


            //download survey details for a single panelist


            self.downloadSurveyDetails = function (panelistId) {
                return restangular.one('users', panelistId).all('surveys').customGET('export');
            };

            //get samples for admin
            self.getSamples = function (page, count) {
                return restangular.all('').customGET('samples', { page: page, count: count });
            };
            //get secs for admin
            self.getSecs = function (page, count) {
                return restangular.all('').customGET('socioEconomicClassifications', { page: page, count: count });
            };
            //filter samples
            self.filterSamples = function (page, count, name) {
                return restangular.all('').customGET('samples', {
                    page: page,
                    count: count,
                    name: name
                });
            };
            //filter secs
            self.filterSecs = function (page, count, name) {
                return restangular.all('').customGET('socioeconomicclassifications', {
                    page: page,
                    count: count,
                    name: name
                });
            };
            //get samples attached to email schedules
            self.getEmailScheduleSamples = function (emailScheduleId) {
                return restangular.one('emailSchedules', emailScheduleId).customGET('samples');
            };
            //create sample for admin
            self.createSample = function (name, description, isActive, gender, fromAge, toAge, tierIds, cityIds, stateIds, registrationDate) {
                var fromRegistrationDate = '';
                var toRegistrationDate = '';
                if (registrationDate.startDate !== null)
                    fromRegistrationDate = registrationDate.startDate.toDateString();
                if (registrationDate.endDate !== null)
                    toRegistrationDate = registrationDate.endDate.toDateString();

                var data = {
                    name: name,
                    description: description,
                    isActive: isActive,
                    gender: gender,
                    fromAge: fromAge,
                    toAge: toAge,
                    tiers: tierIds,
                    cities: cityIds,
                    states: stateIds,
                    fromRegistrationDate: fromRegistrationDate,
                    toRegistrationDate: toRegistrationDate
                };
                if (gender == "null")
                    data.gender = null;
                return restangular.all('samples').customPOST(data);
            };
            self.createPanelistSample = function (name, description, isActive, filter, profileQuestions) {
                var data = {
                    name: name,
                    description: description,
                    isActive: isActive,
                    gender: filter.gender,
                    fromAge: filter.fromAge,
                    toAge: filter.toAge,
                    tiers: filter.tierIds,
                    cities: filter.cityIds,
                    states: filter.stateIds,
                    fromRegistrationDate: filter.minRegistrationDate,
                    toRegistrationDate: filter.maxRegistrationDate,
                    profileQuestions: []
                };
                angular.forEach(profileQuestions, function (value) {
                    if (value.questionId) {
                        data.profileQuestions.push({ questionId: value.questionId, options: value.optionId, operand: value.operand, value: '' });
                    }
                });
                return restangular.all('samples').customPOST(data, 'panelists');
            };
            //create Sec
            self.createSec = function (name, description, isActive) {
                var data = {
                    name: name,
                    description: description,
                    isActive: isActive,
                };
                return restangular.all('socioeconomicclassifications').customPOST(data);
            };
            //edit sample for admin
            self.editSample = function (sampleId, name, description, isActive, gender, fromAge, toAge, tierIds, cityIds, stateIds, registrationDate) {
                //                var fromRegistrationDate = '';
                //                var toRegistrationDate = '';
                var c = '';
                var f = '';
                if (registrationDate.startDate !== null) {
                    var a = moment(registrationDate.startDate);
                    var b = new Date(a);
                    c = b.toDateString();
                }
                if (registrationDate.endDate !== null) {
                    var d = moment(registrationDate.endDate);
                    var e = new Date(d);
                    f = e.toDateString();
                }
                var data = {
                    id: sampleId,
                    name: name,
                    description: description,
                    isActive: isActive,
                    gender: gender,
                    fromAge: fromAge,
                    toAge: toAge,
                    tiers: tierIds,
                    cities: cityIds,
                    states: stateIds,
                    fromRegistrationDate: c,
                    toRegistrationDate: f
                };
                if (gender == "null")
                    data.gender = null;
                return restangular.one('samples', sampleId).customPUT(data);
            };
            //edit sec for admin
            self.editSec = function (secId, name, description, isActive) {
                var data = {
                    id: secId,
                    name: name,
                    description: description,
                    isActive: isActive,
                };
                return restangular.one('socioeconomicclassifications', secId).customPUT(data);
            };
            //attach samples to email schedules
            self.attachSamplesToEmailSchedule = function (sampleIds, emailScheduleId) {
                var data = {
                    sampleIds: sampleIds,
                };
                return restangular.one('emailSchedules', emailScheduleId).customPOST(data, 'samples');
            };
            //get questions for a sample
            self.getSampleQuestions = function (sampleId) {
                return restangular.one('samples', sampleId).customGET('questions');
            }
            //get questions for a sec
            self.getSecQuestions = function (secId) {
                return restangular.one('socioeconomicclassifications', secId).customGET('questions');
            }
            //get stats for sample
            self.getSampleStats = function (sampleId) {
                return restangular.one('samples', sampleId).customGET('stats');
            };
            //delete sample question
            self.deleteSampleQuestion = function (sampleId, questionId) {
                return restangular.one('samples', sampleId).one('questions', questionId).remove();
            }
            //delete sec question
            self.deleteSecQuestion = function (secId, questionId) {
                return restangular.one('socioeconomicclassifications', secId).one('questions', questionId).remove();
            }
            //add sample questions
            self.addSampleQuestion = function (sampleId, questionId, optionIds, operandId) {
                //                var options = [];
                //                options[0] = optionIds.join(',');
                var data = {
                    questionId: questionId,
                    options: optionIds,
                    operand: operandId,
                    value: ''
                };
                return restangular.one('samples', sampleId).all('questions').customPOST(data);
            };
            //add sec questions
            self.addSecQuestion = function (secId, questionId, optionIds) {
                var data = {
                    questionId: questionId,
                    options: optionIds,
                    value: ''
                };
                return restangular.one('socioeconomicclassifications', secId).all('questions').customPOST(data);
            };
            //get profile count for sample
            self.getProfileCountForSample = function (sampleId) {
                return restangular.one('samples', sampleId).customGET('count');
            };
            //get profile count for sec
            self.getProfileCountForSec = function (secId) {
                return restangular.one('socioeconomicclassifications', secId).customGET('count');
            };
            //get operands
            self.getOperands = function () {
                return restangular.all('operands').customGET();
            }
            //get newsletters for admin
            self.getNewsletters = function (page, count) {
                return restangular.all('').customGET('newsletters', { page: page, count: count });
            };
            //get single newsletter
            self.getNewsletter = function (newsletterId) {
                return restangular.one('newsletters', newsletterId).customGET();
            }
            //create newsletter
            self.createNewsletter = function (name, sendDate, subject, body, emails) {
                var data = {
                    name: name,
                    sendDate: sendDate,
                    subject: subject,
                    body: body,
                    emails: emails
                };
                return restangular.all('newsletters').customPOST(data);
            };
            self.sendNewsletter = function (newsletterId) {
                return restangular.one('newsletters', newsletterId).customGET('start');
            };
            //edit newsletter
            self.editNewsletter = function (newsletterId, name, a, subject, body, emails) {
                var data = {
                    name: name,
                    sendDate: new Date(a).toDateString(),
                    subject: subject,
                    body: body,
                    emails: emails
                };
                return restangular.one('newsletters', newsletterId).customPUT(data);
            };
            //get samples attached to newsletter
            self.getNewsletterSamples = function (newsletterId) {
                return restangular.one('newsletters', newsletterId).customGET('samples');
            };
            //attach samples to newsletter
            self.attachSamplesToNewsletter = function (sampleIds, newsletterId) {
                var data = {
                    sampleIds: sampleIds
                };
                return restangular.one('newsletters', newsletterId).customPOST(data, 'samples');
            };
            //delete newsletter
            self.deleteNewsletter = function (newsletterId) {
                return restangular.one('newsletters', newsletterId).remove();
            };

            //get partners for admin
            self.getPartners = function (page, count) {
                return restangular.all('').customGET('partners', { page: page, count: count });
            };
            //create partners
            self.createPartner = function (name, description, successUrl, overquotaUrl, disqualifiedUrl) {
                var data = {
                    name: name,
                    description: description,
                    successUrl: successUrl,
                    overquotaUrl: overquotaUrl,
                    disqualifiedUrl: disqualifiedUrl
                };
                return restangular.all('partners').customPOST(data);
            };
            //edit partners
            self.editPartner = function (partnerId, name, description, successUrl, overquotaUrl, disqualifiedUrl) {
                var data = {
                    name: name,
                    description: description,
                    successUrl: successUrl,
                    overquotaUrl: overquotaUrl,
                    disqualifiedUrl: disqualifiedUrl
                };
                return restangular.one('partners', partnerId).customPUT(data);
            };
            //get partners attached to survey
            self.getSurveyPartners = function (surveyId) {
                return restangular.one('surveys', surveyId).customGET('partners');
            };
            //add partners to survey
            self.addPartnersToSurvey = function (partnerIds, surveyId) {
                var data = {
                    partnerIds: partnerIds
                };
                return restangular.one('surveys', surveyId).customPOST(data, 'partners');
            };
            //delete partner
            self.deletePartner = function (partnerId) {
                return restangular.one('partners', partnerId).remove();
            };

            //get marketingLinks for admin
            self.getMarketingLinks = function (page, count) {
                return restangular.all('').customGET('marketingLinks', { page: page, count: count });
            };
            //get marketingLink for admin
            self.getMarketingLink = function (linkId) {
                return restangular.all('').one('marketingLinks', linkId).customGET();
            };
            //create marketingLink
            self.createMarketingLink = function (name, description) {
                var data = {
                    name: name,
                    description: description
                };
                return restangular.all('marketingLinks').customPOST(data);
            };
            //edit marketingLink
            self.editMarketingLink = function (marketingLinkId, name, description) {
                var data = {
                    name: name,
                    description: description
                };
                return restangular.one('marketingLinks', marketingLinkId).customPUT(data);
            };
            //delete marketing link
            self.deleteMarketingLink = function (marketingLinkId) {
                return restangular.one('marketingLinks', marketingLinkId).remove();
            };
            self.getUsersForLink = function (marketingLinkId, page, count) {
                return restangular.one('marketingLinks', marketingLinkId).customGET('referrals', { page: page, count: count });
            }

            //export marketing links

            self.exportMarketingLinks = function (page, count) {
                return restangular.all('marketingLinks').customGET('export',
                {
                    page: page,
                    count: count
                });
            };

            //export single marketing link

            self.exportMarketingLinkUserDetails = function (marketingLinkId) {
                return restangular.one('marketingLinks', marketingLinkId).all('users').customGET('export');
            };

            //get sweepstakes
            self.getSweepstakes = function (page, count) {
                return restangular.all('').customGET('sweepstakes', { page: page, count: count });
            };
            //create sweepstakes
            self.createSweepstake = function (sweepstakeDate) {
                var data = {
                    sweepstakeDate: sweepstakeDate
                };
                return restangular.all('sweepstakes').customPOST(data);
            };
            //get single sweepstake for admin
            self.getSweepstake = function (sweepstakeId) {
                return restangular.all('sweepstakes').customGET(sweepstakeId);
            };
            //approve sweepstake for admin
            self.approveSweepstake = function (sweepstakeId) {
                return restangular.one('sweepstakes', sweepstakeId).customGET('approve');
            };

            //export sweepstakes
            self.exportSweepstakes = function (page, count) {
                return restangular.all('sweepstakes').customGET('export',
                {
                    page: page,
                    count: count
                });
            };

            //export single sweepstake

            self.exportSweepstakeDetails = function (sweepstakeId) {
                return restangular.one('sweepstakes', sweepstakeId).customGET('export');
            };

            //get emails
            self.getEmailsForSchedule = function (page, count, surveyId, emailScheduleId) {
                return restangular.one('surveys', surveyId).one('emailSchedules', emailScheduleId).customGET('emails', { page: page, count: count });
            };
            //get emails
            self.getEmailsForScheduleStatus = function (page, count, surveyId, emailScheduleId) {
                return restangular.one('surveys', surveyId).one('emailSchedules', emailScheduleId).all('emails').customGET('status', { page: page, count: count });
            };
            //update user pic
            self.updateUserPic = function (pic) {
                var formData = new FormData();
                if (angular.isDefined(pic))
                    formData.append("file", pic);
                return restangular.one('users', id)
                    .withHttpConfig({ transformRequest: angular.identity })
                    .customPOST(formData, "photo", undefined, { 'Content-Type': undefined });

            };
            //get user active status
            self.getUserActiveStatus = function () {
                return restangular.all('userActiveStatuses').customGET();
            }
            //get all users for a admin
            self.getPanelists = function (page, count) {
                return restangular.all('').customGET('users', { page: page, count: count });
            };
            //update panelist for a admin
            self.updatePanelistAccount = function (panelistId, user, dateFilled) {

                var data = {
                    basicProfile: {
                        firstName: user.firstName,
                        lastName: user.lastName,
                        Gender: user.gender,
                        Mobile: user.mobile,
                        DateOfBirth: new Date(dateFilled).toDateString(),
                        ReferralSource: user.referralSource,
                        AddressLine1: user.addressLine1,
                        //                        AddressLine2:user.addressLine2,
                        Country: user.country,
                        State: user.state,
                        City: user.city,
                        Pincode: user.pincode,
                        AcceptTerms: "true"
                    },
                    legacyError: user.legacyError

                }
                if (user.addressLine2)
                    data.basicProfile.AddressLine2 = user.addressLine2;
                return restangular.one('users', panelistId).all('updateAccount').customPUT(data);
            }
            //filter users
            self.filterPanelists = function (page, count, filter, profileQuestions, userIds) {
                var data = {
                    email: filter.email,
                    phoneNumber: filter.phoneNumber,
                    surveyIds: filter.surveyIds,
                    states: filter.stateIds,
                    cities: filter.cityIds,
                    tiers: filter.tierIds,
                    minAge: filter.fromAge,
                    maxAge: filter.toAge,
                    gender: filter.gender,
                    activeStatus: filter.userActiveStatus,
                    minRegistrationDate: filter.minRegistrationDate,
                    maxRegistrationDate: filter.maxRegistrationDate,
                    secIds: filter.secIds,
                    profileQuestions: [],
                    userIds: [],
                    includeUnsubscribed: filter.includeUnsubscribed
                };
                if (userIds != '') {
                    data.userIds = userIds.split(',');
                }
                angular.forEach(profileQuestions, function (value) {
                    if (value.questionId) {
                        data.profileQuestions.push({ questionId: value.questionId, optionids: value.optionId, operand: value.operand });
                    }
                });
                return restangular.all('users').customPOST(data, 'panelists',
                {
                    page: page,
                    count: count,
                });
                //                return restangular.all('').customGET('users', { page: page, count: count });
            };

            //fillter bounced only panelists
            self.filterBouncedOnlyPanelists = function (page, count, filter) {

                var fromDate = '';
                var a = '';
                var b = '';
                var toDate = '';
                if (filter.registrationDate) {
                    a = new Date(moment(filter.registrationDate.startDate));
                    fromDate = a.toDateString();
                    b = new Date(moment(filter.registrationDate.endDate));
                    toDate = b.toDateString();
                }

                var data = {
                    email: filter.email,
                    fromDate: fromDate,
                    toDate: toDate,
                    blacklistType: filter.blacklistType
                };
                return restangular.all('users').customPOST(data, 'bounces',
                {
                    page: page,
                    count: count,
                });
            };

            //export panelists
            self.exportPanelists = function (page, count, filter, profileQuestions, userIds) {
                var data = {
                    email: filter.email,
                    phoneNumber: filter.phoneNumber,
                    surveyIds: filter.surveyIds,
                    states: filter.stateIds,
                    cities: filter.cityIds,
                    tiers: filter.tierIds,
                    minAge: filter.fromAge,
                    maxAge: filter.toAge,
                    gender: filter.gender,
                    activeStatus: filter.userActiveStatus,
                    minRegistrationDate: filter.minRegistrationDate,
                    maxRegistrationDate: filter.maxRegistrationDate,
                    secIds: filter.secIds,
                    profileQuestions: [],
                    userIds: [],
                    includeUnsubscribed: filter.includeUnsubscribed
                };
                if (userIds !== '') {
                    data.userIds = userIds.split(',');
                }
                angular.forEach(profileQuestions, function (value) {
                    if (value.questionId) {
                        data.profileQuestions.push({ questionId: value.questionId, optionids: value.optionId, operand: value.operand });
                    }
                });
                return restangular.all('users').customPOST(data, 'panelists',
                {
                    page: page,
                    count: count,
                    export: true

                });
                //                return restangular.all('').customGET('users', { page: page, count: count });
            };

            //export bounced panelists

            self.exportBouncedOnlyPanelists = function (page, count, filter) {

                var fromDate = '';
                var a = '';
                var b = '';
                var toDate = '';
                if (filter.registrationDate) {
                    a = new Date(moment(filter.registrationDate.startDate));
                    fromDate = a.toDateString();
                    b = new Date(moment(filter.registrationDate.endDate));
                    toDate = b.toDateString();
                }
                var data = {
                    email: filter.email,
                    blacklistType: filter.blacklistType,
                    type: filter.type,
                    subType: filter.subType,
                    fromDate: fromDate,
                    toDate: toDate

                };
                return restangular.all('users').customPOST(data, 'bounces',
                {
                    page: page,
                    count: count,
                    export: true
                });
            };
            //get legacy error types
            self.getLegacyErrorTypes = function () {
                return restangular.all('').customGET('legacyErrorTypes');
            };
            //filter legacy error panelists
            self.filterLegacyErrorPanelists = function (page, count, name, email, phoneNumber, legacyErrorType) {
                return restangular.all('users').customGET('legacyErrors',
                {
                    page: page,
                    count: count,
                    name: name,
                    email: email,
                    phoneNumber: phoneNumber,
                    legacyErrorType: legacyErrorType
                });
            };
            //filter basic profile panelists 
            self.filterBasicProfilePanelistsOnly = function (page, count, name, email, phoneNumber) {
                return restangular.all('users').customGET('basicProfileOnly',
                {
                    page: page,
                    count: count,
                    name: name,
                    email: email,
                    phoneNumber: phoneNumber
                });
            };

            //filter registered only panelists
            self.filterRegisteredOnlyPanelists = function (page, count, name, email, phoneNumber) {
                return restangular.all('users').customGET('registeredOnly',
                {
                    page: page,
                    count: count,
                    name: name,
                    email: email,
                    phoneNumber: phoneNumber
                });
            };

            //filter deleted requests panelists
            self.filterDeletedRequestPanelists = function (page, count, name, email, phoneNumber, includeDeleted) {
                return restangular.all('users').customGET('deleteRequests',
                {
                    page: page,
                    count: count,
                    name: name,
                    email: email,
                    phoneNumber: phoneNumber,
                    includeDeleted: includeDeleted
                });
            };
            //filter unsubscribed requests panelists
            self.filterUnsubscribedRequestPanelists = function (page, count, name, email, phoneNumber, includeUnsubscribed) {
                return restangular.all('users').customGET('unsubscribeRequests',
                {
                    page: page,
                    count: count,
                    name: name,
                    email: email,
                    phoneNumber: phoneNumber,
                    includeUnsubscribed: includeUnsubscribed
                });
            };

            //            //export users
            //            self.exportPanelists = function (name, email, phoneNumber) {
            //                return restangular.all('users').customGET('export',
            //                    {
            //                        name: name, email: email, phoneNumber: phoneNumber
            //                    });
            //            };
            //export registered only users
            self.exportRegisteredOnlyPanelists = function (name, email, phoneNumber) {
                return restangular.all('users').all('registeredOnly').customGET('export',
                    {
                        name: name, email: email, phoneNumber: phoneNumber
                    });
            };

            //export legacy error only panelists

            self.exportLegacyErrorPanelists = function (name, email, phoneNumber) {
                return restangular.all('users').all('legacyErrors').customGET('export',
                {
                    name: name,
                    email: email,
                    phoneNumber: phoneNumber
                });
            };

            //export basic profile only panelists
            self.exportBasicProfileOnlyPanelists = function (name, email, phoneNumber) {
                return restangular.all('users').all('basicProfileOnly').customGET('export',
                    {
                        name: name, email: email, phoneNumber: phoneNumber
                    });
            };
            //export deleted requests panelists
            self.exportDeletedRequestPanelists = function (name, email, phoneNumber, includeDeleted) {
                return restangular.all('users').all('deleteRequests').customGET('export',
                    {
                        name: name, email: email, phoneNumber: phoneNumber, includeDeleted: includeDeleted
                    });
            };
            //export unsubscribed requests panelists
            self.exportUnsubscribedRequestPanelists = function (name, email, phoneNumber, includeUnsubscribed) {
                return restangular.all('users').all('unsubscribeRequests').customGET('export',
                    {
                        name: name, email: email, phoneNumber: phoneNumber, includeUnsubscribed: includeUnsubscribed
                    });
            };
            //get all redemptions
            self.getRedemptions = function (page, count, panelistId) {
                if (role == 'panelist') //get all redemptions for a panelist
                    return restangular.one('users', id).customGET('redemptionRequests', { page: page, count: count });
                else //get all redemptions for a admin
                {
                    panelistId = panelistId || '';
                    if (panelistId == '')
                        return restangular.all('').customGET('redemptionRequests', { page: page, count: count });
                    else
                        return restangular.one('users', panelistId).customGET('redemptionRequests', { page: page, count: count });
                }
            };
            //get redemption request statuses for admin
            self.getRedemptionRequestStatuses = function () {
                return restangular.all('').customGET('redemptionRequestStatuses');
            };
            //filter redemption requests
            self.filterRedemptions = function (page, count, requestDate, redemptionMode, status, email) {
                var a = '';
                var b = '';
                var c = [];
                var fromRequestDate = '';
                var toRequestDate = '';
                a = new Date(moment(requestDate.startDate));
                fromRequestDate = a.toDateString();
                b = new Date(moment(requestDate.endDate));
                toRequestDate = b.toDateString();
                angular.forEach(redemptionMode, function (value) {
                    c.push(JSON.parse(value).id);
                });
                return restangular.all('').customGET('redemptionRequests',
                     {
                         page: page,
                         count: count,
                         fromRequestDate: fromRequestDate,
                         toRequestDate: toRequestDate,
                         redemptionModeId: c,
                         redemptionRequestStatus: status,
                         email: email
                     });
            };
            //filter required redemption requests
            self.filterRequiredRedemptions = function (page, count, a, d, mode, status, email) {
                var fromRequestDate = '';
                var toRequestDate = '';
                fromRequestDate = a;
                toRequestDate = d;
                return restangular.all('').customGET('redemptionRequests',
                {
                    page: page,
                    count: count,
                    fromRequestDate: fromRequestDate,
                    toRequestDate: toRequestDate,
                    redemptionModeId: mode,
                    redemptionRequestStatus: status,
                    email: email
                });
            };
            //export redemption requests
            self.exportRedemptions = function (page, count, requestDate, redemptionMode, status, email) {
                var a = '';
                var b = '';
                var c = [];
                var fromRequestDate = '';
                var toRequestDate = '';
                a = new Date(moment(requestDate.startDate));
                fromRequestDate = a.toDateString();
                b = new Date(moment(requestDate.endDate));
                toRequestDate = b.toDateString();
                angular.forEach(redemptionMode, function (value) {
                    c.push(JSON.parse(value).id);
                });
                return restangular.all('redemptionRequests').customGET('export',
                    {
                        page: page,
                        count: count,
                        fromRequestDate: fromRequestDate,
                        toRequestDate: toRequestDate,
                        redemptionModeId: c,
                        redemptionRequestStatus: status,
                        email: email
                    });
            };
            //approve redemption request
            self.approveRedemptionRequest = function (redemptionRequestId, points, notes) {
                var data = [
                    {
                        redemptionRequestId: redemptionRequestId,
                        points: points,
                        notes: notes
                    }
                ];
                return restangular.all('redemptionRequests').customPOST(data, 'approve');
            };
            //cancel redemption request
            self.cancelRedemptionRequest = function (redemptionRequestId, notes) {
                var data = [
                    {
                        redemptionRequestId: redemptionRequestId,
                        notes: notes
                    }
                ];
                return restangular.all('redemptionRequests').customPOST(data, 'cancel');
            };
            //filter referrals
            self.filterReferrals = function (page, count, createDate, status, method, userEmail, referralEmail, phoneNumberConfirmed, signupIp) {
                var a = '';
                var b = '';
                var fromCreateDate = '';
                var toCreateDate = '';
                a = new Date(moment(createDate.startDate));
                b = new Date(moment(createDate.endDate));
                fromCreateDate = a.toDateString();
                toCreateDate = b.toDateString();
                return restangular.all('').customGET('referrals',
                {
                    page: page,
                    count: count,
                    fromCreateDate: fromCreateDate,
                    toCreateDate: toCreateDate,
                    referralStatus: status,
                    referralMethod: method,
                    userEmail: userEmail,
                    referralEmail: referralEmail,
                    phoneNumberConfirmed: phoneNumberConfirmed,
                    signupIp: signupIp
                });
            };
            //filter required referrals
            self.filterRequiredReferrals = function (page, count, a, d, status, method, userEmail, referralEmail, phoneNumberConfirmed, signupIp) {
                var fromCreateDate = '';
                var toCreateDate = '';
                fromCreateDate = a;
                toCreateDate = d;

                return restangular.all('').customGET('referrals',
                {
                    page: page,
                    count: count,
                    fromCreateDate: fromCreateDate,
                    toCreateDate: toCreateDate,
                    referralStatus: status,
                    referralMethod: method,
                    userEmail: userEmail,
                    referralEmail: referralEmail,
                    phoneNumberConfirmed: phoneNumberConfirmed,
                    signupIp: signupIp
                });
            };
            //export referrals
            self.exportReferrals = function (page, count, createDate, status, method, userEmail, referralEmail, phoneNumberConfirmed, signupIp) {
                var a = '';
                var b = '';
                var fromCreateDate = '';
                var toCreateDate = '';
                a = new Date(moment(createDate.startDate));
                b = new Date(moment(createDate.endDate));
                fromCreateDate = a.toDateString();
                toCreateDate = b.toDateString();
                return restangular.all('referrals').customGET('export',
                    {
                        page: page,
                        count: count,
                        fromCreateDate: fromCreateDate,
                        toCreateDate: toCreateDate,
                        referralStatus: status,
                        referralMethod: method,
                        userEmail: userEmail,
                        referralEmail: referralEmail,
                        phoneNumberConfirmed: phoneNumberConfirmed,
                        signupIp: signupIp
                    });
            };
            //approve referral
            self.approveReferral = function (referralId) {
                var data =
                {
                    Ids: [referralId]
                };
                return restangular.all('referrals').customPOST(data, 'approve');
            };
            //cancel referral
            self.cancelReferral = function (referralId) {
                var data =
                {
                    Ids: [referralId]
                };
                return restangular.all('referrals').customPOST(data, 'cancel');
            };
            //filter rewards
            self.filterRewards = function (page, count, rewardDate, type) {
                var a = '';
                var b = '';
                var fromRewardDate = '';
                var toRewardDate = '';
                a = new Date(moment(rewardDate.startDate));
                fromRewardDate = a.toDateString();
                b = new Date(moment(rewardDate.endDate));
                toRewardDate = b.toDateString();
                return restangular.all('').customGET('rewards',
                {
                    page: page,
                    count: count,
                    fromRewardDate: fromRewardDate,
                    toRewardDate: toRewardDate,
                    rewardType: type
                });
            };
            //filter required rewards
            self.filterRequiredRewards = function (page, count, a, d, type) {
                var fromRewardDate = '';
                var toRewardDate = '';
                fromRewardDate = a;
                toRewardDate = d;

                return restangular.all('').customGET('rewards',
                {
                    page: page,
                    count: count,
                    fromRewardDate: fromRewardDate,
                    toRewardDate: toRewardDate,
                    rewardType: type
                });
            };
            //export rewards
            self.exportRewards = function (page, count, rewardDate, type) {
                var a = '';
                var b = '';
                var fromRewardDate = '';
                var toRewardDate = '';
                a = new Date(moment(rewardDate.startDate));
                fromRewardDate = a.toDateString();
                b = new Date(moment(rewardDate.endDate));
                toRewardDate = b.toDateString();
                return restangular.all('rewards').customGET('export',
                    {
                        page: page,
                        count: count,
                        fromRewardDate: fromRewardDate,
                        toRewardDate: toRewardDate,
                        rewardType: type
                    });
            };
            //get total points for a panelist
            self.getTotalPoints = function (panelistId) {
                panelistId = panelistId || id;
                return restangular.one('users', panelistId).all('points').customGET();
            };
            //get redemption points status
            self.getRedemptionPointsStatus = function (panelistId) {
                panelistId = panelistId || id;
                return restangular.one('users', panelistId).all('redemptionRequests').all('pointstatus').customGET();
            };
            //get rewards points status
            self.getRewardsPointsStatus = function (panelistId) {
                panelistId = panelistId || id;
                return restangular.one('users', panelistId).all('rewards').all('pointstatus').customGET();
            };
            //get referrals status
            self.getReferralsStatus = function (panelistId) {
                panelistId = panelistId || id;
                return restangular.one('users', panelistId).all('referrals').all('status').customGET();
            };
            //get surveys status
            self.getSurveysStatus = function (panelistId) {
                panelistId = panelistId || id;
                return restangular.one('users', panelistId).all('surveys').all('status').customGET();
            };
            //get all referrals
            self.getReferrals = function (page, count, panelistId) {
                if (role == 'panelist') //get all referrals for a panelist
                    return restangular.one('users', id).customGET('referrals', { page: page, count: count });
                else //get all referrals for a admin
                {
                    panelistId = panelistId || '';
                    if (panelistId == '')
                        return restangular.all('').customGET('referrals', { page: page, count: count });
                    else
                        return restangular.one('users', panelistId).customGET('referrals', { page: page, count: count });
                }
            };
            //get all referral status
            self.getReferralStatuses = function () {
                return restangular.all('').customGET('referralStatuses');
            };
            //get all referral method
            self.getReferralMethods = function () {
                return restangular.all('').customGET('referralMethods');
            };

            //get single referral for admin
            self.getReferral = function (referralId) {
                return restangular.all('referrals').customGET(referralId);
            };
            //get surveys
            self.getSurveys = function (page, count, panelistId) {
                if (role == 'panelist') //get all surveys for a panelist
                    return restangular.one('users', id).customGET('surveys', { page: page, count: count });
                else //get all surveys for a admin
                {
                    panelistId = panelistId || '';
                    if (panelistId == '')
                        return restangular.all('').customGET('surveys', { page: page, count: count });
                    else
                        return restangular.one('users', panelistId).customGET('surveys', { page: page, count: count });
                }
            };
            //start survey
            self.startSurvey = function (startId) {
                return restangular.all('surveys').one('start', startId).customGET();
            };
            //get single survey for admin
            self.getSurvey = function (surveyId) {
                return restangular.all('surveys').customGET(surveyId);
            };
            //get all rewards 
            self.getRewards = function (page, count, panelistId) {
                if (role == 'panelist') //get all rewards for a panelist
                    return restangular.one('users', id).customGET('rewards', { page: page, count: count });
                else //get all rewards for a admin
                {
                    panelistId = panelistId || '';
                    if (panelistId == '')
                        return restangular.all('').customGET('rewards', { page: page, count: count });
                    else
                        return restangular.one('users', panelistId).customGET('rewards', { page: page, count: count });
                }
            };
            //get all secs
            self.getUserSecs = function (panelistId) {
                return restangular.one('users', panelistId).customGET('sec');

            };
            //get single reward for admin
            self.getReward = function (rewardId) {
                return restangular.all('rewards').customGET(rewardId);
            };
            //get reward types for admin
            self.getRewardTypes = function () {
                return restangular.all('').customGET('rewardTypes');
            };
            //get survey attempt statuses for admin
            self.getSurveyAttemptStatuses = function () {
                return restangular.all('').customGET('surveyAttemptStatuses');
            };
            //revoke reward
            self.revokeReward = function (panelistId, rewardId) {
                return restangular.one('users', panelistId).one('rewards', rewardId).customGET('revoke');
            };
            //grant reward
            self.grantReward = function (panelistId, rewardId) {
                return restangular.one('users', panelistId).one('rewards', rewardId).customGET('grant');
            };
            //get single redemption request for admin
            self.getRedemptionRequest = function (redemptionRequestId) {
                return restangular.all('redemptionRequests').customGET(redemptionRequestId);
            };
            //get survey names for admin
            self.getSurveyNames = function () {
                return restangular.all('surveys').customGET('names');
            };
            //get client names for admin
            self.getClientNames = function () {
                return restangular.all('surveys').customGET('clients');
            };
            //get survey types for admin
            self.getSurveyTypes = function () {
                return restangular.all('').customGET('surveyTypes');
            }
            //get redemption modes
            self.getRedemptionModes = function () {
                return restangular.all('').customGET('redemptionModes');
            };
            //get survey email reports
            self.getSurveyEmailReports = function () {
                return restangular.all('reports').customGET('emails');
                //                return restangular.oneUrl('routeName', 'http://137.116.155.221/reports/emails').get();


            }
            //create redemption mode
            self.createRedemptionMode = function (name, minimumPoints, description, useName, useAddress, usePhone) {
                var data = {
                    name: name,
                    minimumPoints: minimumPoints,
                    description: description,
                    useName: useName,
                    useAddress: useAddress,
                    usePhone: usePhone
                }
                return restangular.all('redemptionModes').customPOST(data);
            };
            //edit redemption mode
            self.editRedemptionMode = function (redemptionModeId, name, minimumPoints, description, useName, useAddress, usePhone) {
                var data = {
                    name: name,
                    minimumPoints: minimumPoints,
                    description: description,
                    useName: useName,
                    useAddress: useAddress,
                    usePhone: usePhone
                }
                return restangular.one('redemptionModes', redemptionModeId).customPUT(data);
            };
            //create redemption request
            self.createRedemptionRequest = function (mode, points, date, userInfo) {
                var data = {
                    RedemptionModeId: mode,
                    RequestDate: date,
                    PointsRequested: points,
                    //                   Notes: remarks,
                    RedemptionRequestDetail: {
                        PhoneNumber: userInfo.mobile,
                        Name: userInfo.firstName,
                        Address1: userInfo.addressLine1,
                        Address2: userInfo.addressLine2,
                        State: userInfo.state,
                        City: userInfo.city,
                        Country: userInfo.country,
                        Pincode: userInfo.pincode
                    }
                };
                return restangular.one('users', id).customPOST(data, 'redemptionRequests');
            };
            //filter survey
            self.filterSurveys = function (page, count, publishDate, expiryDate, surveyName, clientName, surveyType) {
                var fromPublishDate = '';
                var a = '';
                var b = '';
                var c = '';
                var d = '';
                var toPublishDate = '';
                var fromExpiryDate = '';
                var toExpiryDate = '';
                if (publishDate) {
                    a = new Date(moment(publishDate.startDate));
                    fromPublishDate = a.toDateString();
                    b = new Date(moment(publishDate.endDate));
                    toPublishDate = b.toDateString();
                }
                if (expiryDate) {
                    c = new Date(moment(expiryDate.startDate));
                    fromExpiryDate = c.toDateString();
                    d = new Date(moment(expiryDate.endDate));
                    toExpiryDate = d.toDateString();
                };
                return restangular.all('').customGET('surveys',
                {
                    page: page,
                    count: count,
                    fromPublishDate: fromPublishDate,
                    toPublishDate: toPublishDate,
                    fromExpiryDate: fromExpiryDate,
                    toExpiryDate: toExpiryDate,
                    name: surveyName,
                    client: clientName,
                    surveyType: surveyType
                });
            };

            //filter required surveys
            self.filterRequiredSurveys = function (page, count, a, d, e, h, surveyName, clientName, surveyType) {
                var fromPublishDate = '';
                var toPublishDate = '';
                var fromExpiryDate = '';
                var toExpiryDate = '';

                fromPublishDate = a;
                toPublishDate = d;


                fromExpiryDate = e;
                toExpiryDate = h;

                return restangular.all('').customGET('surveys',
                {
                    page: page,
                    count: count,
                    fromPublishDate: fromPublishDate,
                    toPublishDate: toPublishDate,
                    fromExpiryDate: fromExpiryDate,
                    toExpiryDate: toExpiryDate,
                    name: surveyName,
                    client: clientName,
                    surveyType: surveyType
                });
            };
            //export surveys
            self.exportSurveys = function (page, count, publishDate, expiryDate, surveyName, clientName, surveyType) {
                var fromPublishDate = '';
                var a = '';
                var b = '';
                var c = '';
                var d = '';
                var toPublishDate = '';
                var fromExpiryDate = '';
                var toExpiryDate = '';
                if (publishDate) {
                    a = new Date(moment(publishDate.startDate));
                    fromPublishDate = a.toDateString();
                    b = new Date(moment(publishDate.endDate));
                    toPublishDate = b.toDateString();
                }
                if (expiryDate) {
                    c = new Date(moment(expiryDate.startDate));
                    fromExpiryDate = c.toDateString();
                    d = new Date(moment(expiryDate.endDate));
                    toExpiryDate = d.toDateString();
                }
                return restangular.all('surveys').customGET('export',
                     {
                         page: page,
                         count: count,
                         fromPublishDate: fromPublishDate,
                         toPublishDate: toPublishDate,
                         fromExpiryDate: fromExpiryDate,
                         toExpiryDate: toExpiryDate,
                         name: surveyName,
                         client: clientName,
                         surveyType: surveyType
                     });
            };

            //export single survey

            self.exportSurvey = function (page, count, surveyId, f) {
                return restangular.one('surveys', surveyId).all('users').customGET('export', {
                    page: page,
                    count: count,
                    attemptStatus: f

                });
            };

            //export surveys info
            self.exportSurveysOnDashboard = function (page, count, publishDate) {
                var fromPublishDate = '';
                var toPublishDate = '';
                if (publishDate) {
                    fromPublishDate = publishDate.startDate._d.toDateString();
                    toPublishDate = publishDate.endDate._d.toDateString();
                };
                return restangular.all('surveysOnDashboard').customGET('export',
                {
                    page: page,
                    count: count,
                    fromPublishDate: fromPublishDate,
                    toPublishDate: toPublishDate
                });

            };
            //create survey
            self.createSurvey = function (survey, file) {
                //                var formData = new FormData();
                //                formData.append("Name", survey.name);
                //                formData.append("Company", survey.company);
                //                formData.append("Description", survey.description);
                //                formData.append("SurveyType", survey.surveyType);
                //                formData.append("PointAllocationType", survey.pointAllocationType);
                //                formData.append("UserLimitCommitted", survey.userLimitCommitted);
                //                formData.append("UserLimitCutoff", survey.userLimitCutoff);
                //                formData.append("Client", survey.client);
                //                formData.append("CeggPoints", survey.ceggPoints);
                //                formData.append("SurveyLength", survey.surveyLength);
                //                formData.append("PublishDate", survey.publishDate);
                //                formData.append("ExpiryDate", survey.expiryDate);
                //                formData.append("OutlierCutoffTime", survey.outlierCutoffTime);
                //                formData.append("CostPerInterview", survey.costPerInterview);
                //                formData.append("SurveyBlacklistIds", survey.surveyBlacklistIds);
                //                formData.append("CompanyLogo", survey.CompanyLogo);
                //                formData.append("IsActive", true);
                //                formData.append("UseUniqueLinks", survey.useUniqueLinks);
                //                if (!survey.useUniqueLinks) {
                //                    formData.append("Url", survey.url);
                //                }
                //                return restangular.all('')
                //                    .withHttpConfig({ transformRequest: angular.identity })
                //                    .customPOST(formData, "surveys", undefined, { 'Content-Type': undefined });
                var data = {
                    Name: survey.name,
                    Company: survey.company,
                    Description: survey.description,
                    Survey: survey.surveyType,
                    PointAllocationType: survey.pointAllocationType,
                    UserLimitCommitted: survey.userLimitCommitted,
                    UserLimitCutoff: survey.userLimitCutoff,
                    Client: survey.client,
                    CeggPoints: survey.ceggPoints,
                    SurveyLength: survey.surveyLength,
                    PublishDate: new Date(survey.publishDate).toDateString(),
                    ExpiryDate: new Date(survey.expiryDate).toDateString(),
                    OutlierCutoffTime: survey.outlierCutoffTime,
                    CostPerInterview: survey.costPerInterview,
                    SurveyBlacklistIds: survey.surveyBlacklistIds,
                    IsActive: true,
                    CompanyLogo: survey.companyLogo,
                    UseUniqueLinks: survey.useUniqueLinks,
                    IpUnique: survey.ipUnique,
                    SurveyUrlIdentifier: survey.surveyUrlIdentifier
                }
                if (!survey.useUniqueLinks)
                    data.Url = survey.url;
                return restangular.all('').customPOST(data, 'surveys');
            };
            //edit survey
            self.editSurvey = function (survey, surveyId, a, b) {
                //var formData = new FormData();
                //formData.append("Name", survey.surveyName);
                //formData.append("Company", survey.companyName);
                //formData.append("Description", survey.description);
                //formData.append("SurveyType", survey.surveyType);
                //formData.append("PointAllocationType", survey.pointAllocationType);
                //formData.append("UserLimitCommitted", survey.userLimitCommitted);
                //formData.append("UserLimitCutoff", survey.userLimitCutoff);
                //formData.append("Client", survey.clientName);
                //formData.append("CeggPoints", survey.ceggPoints);
                //formData.append("Url", survey.surveyUrl);
                //formData.append("SurveyLength", survey.surveyLength);
                //formData.append("PublishDate", survey.publishDate);
                //formData.append("ExpiryDate", survey.expiryDate);
                //formData.append("OutlierCutoffTime", survey.outlierTime);
                //formData.append("CostPerInterview", survey.cost);
                //formData.append("SurveyBlacklistIds", survey.blacklistIds);
                //formData.append("IsActive", true);
                //if (angular.isDefined(survey.companyLogo))
                //    formData.append("CompanyLogo", survey.companyLogo);
                //return restangular.all('')
                //    .withHttpConfig({ transformRequest: angular.identity })
                //    .customPOST(formData, "surveys", undefined, { 'Content-Type': undefined });
                var data = {
                    Name: survey.name,
                    Company: survey.company,
                    Description: survey.description,
                    SurveyType: survey.surveyType,
                    PointAllocationType: survey.pointAllocationType,
                    UserLimitCommitted: survey.userLimitCommitted,
                    UserLimitCutoff: survey.userLimitCutoff,
                    Client: survey.client,
                    CeggPoints: survey.ceggPoints,
                    SurveyLength: survey.surveyLength,
                    PublishDate: new Date(a).toDateString(),
                    ExpiryDate: new Date(b).toDateString(),
                    OutlierCutoffTime: survey.outlierCutoffTime,
                    CostPerInterview: survey.costPerInterview,
                    SurveyBlacklistIds: survey.surveyBlacklistIds,
                    IsActive: true,
                    CompanyLogo: survey.companyLogo,
                    UseUniqueLinks: survey.useUniqueLinks,
                    IpUnique: survey.ipUnique,
                    SurveyUrlIdentifier: survey.surveyUrlIdentifier,
                    IsPaused: survey.isPaused

                }
                if (!survey.useUniqueLinks)
                    data.Url = survey.url;
                return restangular.all('surveys').customPUT(data, surveyId);
            };
            //create referral
            self.createReferral = function (name, email, mobile) {
                var data = {
                    Name: name,
                    Email: email,
                    PhoneNumber: mobile,
                    ReferralMethod: "Manual"
                };
                return restangular.one('users', id).customPOST(data, 'referrals');
            };
            //reset Password
            self.changePassword = function (currentPassword, newPassword, confirmPassword, panelistId) {
                var data = {
                    OldPassword: currentPassword,
                    Password: newPassword,
                    ConfirmPassword: confirmPassword
                };
                if (role == 'panelist') //change password for a panelist
                    return restangular.one('accounts', id).customPOST(data, 'changePassword');
                else //change password for a admin
                {
                    panelistId = panelistId || '';
                    if (panelistId == '')
                        return restangular.all('').customPOST(data, 'changePassword');
                    else
                        return restangular.one('accounts', panelistId).customPOST(data, 'changePassword');
                }

            };
            //subscribe panelist
            self.subscribe = function (panelistId) {
                panelistId = panelistId || id;
                if (role == 'panelist') //subscribe for a panelist
                    return restangular.one('users', panelistId).customGET('requestSubscribe');
                else //subscribe for a admin
                    return restangular.one('users', panelistId).customGET('subscribe');
            };
            //unsubscribe panelist
            self.unsubscribe = function (panelistId) {
                panelistId = panelistId || id;
                if (role == 'panelist') //subscribe for a panelist
                    return restangular.one('users', panelistId).customGET('requestUnsubscribe');
                else //subscribe for a admin
                    return restangular.one('users', panelistId).customGET('unsubscribe');
            };
            //revert delete account
            self.revertDeleteAccount = function (panelistId) {
                return restangular.one('users', panelistId).customGET('revertDelete');
            }
            //delete account
            self.deleteAccount = function (panelistId) {
                panelistId = panelistId || id;
                return restangular.one('users', panelistId).remove();
            };
            //delete account permanently
            self.permanentDeleteAccount = function (panelistId) {
                return restangular.one('users', panelistId).customGET('permanentDelete');
            }
            //upload referral with file
            self.uploadReferralFile = function (file) {
                var formData = new FormData();
                if (angular.isDefined(file))
                    formData.append("file", file);
                return restangular.one('users', id)
                    .withHttpConfig({ transformRequest: angular.identity })
                    .customPOST(formData, "uploadReferrals", undefined, { 'Content-Type': undefined });
            };
            //upload survey approvals
            self.uploadSurveyApprovals = function (surveyId, file) {
                var formData = new FormData();
                if (angular.isDefined(file))
                    formData.append("file", file);
                return restangular.one('surveys', surveyId).all('users')
                    .withHttpConfig({ transformRequest: angular.identity })
                    .customPOST(formData, "uploadresults", undefined, { 'Content-Type': undefined });
            };
            //upload survey unique links
            self.uploadSurveyUniqueLinks = function (surveyId, file) {
                var formData = new FormData();
                if (angular.isDefined(file))
                    formData.append("file", file);
                return restangular.one('surveys', surveyId).all('users')
                    .withHttpConfig({ transformRequest: angular.identity })
                    .customPOST(formData, "uploadUniqueUrls", undefined, { 'Content-Type': undefined });
            };
            //upload referral approvals
            self.uploadReferralApprovals = function (file) {
                var formData = new FormData();
                if (angular.isDefined(file))
                    formData.append("file", file);
                return restangular.all('referrals')
                    .withHttpConfig({ transformRequest: angular.identity })
                    .customPOST(formData, "uploadApproved", undefined, { 'Content-Type': undefined });
            };
            //upload redemption approvals
            self.uploadRedemptionApprovals = function (file) {
                var formData = new FormData();
                if (angular.isDefined(file))
                    formData.append("file", file);
                return restangular.all('redemptionRequests')
                    .withHttpConfig({ transformRequest: angular.identity })
                    .customPOST(formData, "uploadApproved", undefined, { 'Content-Type': undefined });
            };
            //get all tiers
            self.getTiers = function () {
                return restangular.all('').customGET('tiers');
            };
            //get all cities for state
            self.getCities = function (countryId, stateId) {
                return restangular.one('countries', countryId).one('states', stateId).customGET('cities');
            };
            //get cities for tiers
            //self.getCitiesForTiers = function() {
            //    return restangular.one('countries', countryId).one('states', stateId).all('tiers').customGET('cities');
            //};
            //get all cities
            self.getAllCities = function () {
                return restangular.all('').customGET('cities');
            };
            //get all states
            self.getAllStates = function () {
                return restangular.all('').customGET('states');
            };
            //get all countries
            self.getCountries = function () {
                return restangular.all('').customGET('countries');
            };
            //get all states for a country
            self.getStates = function (countryId) {
                return restangular.one('countries', countryId).customGET('states');
            };
            //get email properties
            self.getEmailProperties = function () {
                return restangular.all('').customGET('surveyEmailProperties');
            }
            //close survey
            self.closeSurvey = function (surveyId) {
                return restangular.one('surveys', surveyId).customGET('close');
            };
            //open survey
            self.openSurvey = function (surveyId) {
                return restangular.one('surveys', surveyId).customGET('open');
            }
            //get attempts for the survey
            self.getAttempts = function (page, count, surveyId, f) {
                return restangular.one('surveys', surveyId).customGET('users',
                 {
                     page: page,
                     count: count,
                     attemptStatus: f
                 });
            };
            //delete survey allocation entry
            self.deleteSurveyAllocation = function (surveyAllocationId) {
                return restangular.one('surveyAllocations', surveyAllocationId).remove();
            }
            //get attempt status for the survey
            self.getAttemptStatus = function (surveyId) {
                return restangular.one('surveys', surveyId).all('users').customGET('attemptStatus');
            };
            //get templates for the survey
            self.getTemplates = function (surveyId) {
                return restangular.one('surveys', surveyId).customGET('templates');
            };
            //create template for the survey
            self.createTemplate = function (surveyId, name, isActive, body, subject) {
                var data = {
                    name: name,
                    isActive: isActive,
                    body: body,
                    subject: subject
                };
                return restangular.one('surveys', surveyId).all('templates').customPOST(data);
            };
            //add a new country
            self.addCountry = function (name) {
                var data = {
                    name: name,

                };
                return restangular.all('countries').customPOST(data);
            };
            //edit a country
            self.editCountry = function (countryId, name) {
                var data = {
                    name: name,
                };
                return restangular.one('countries', countryId).customPUT(data);
            };
            //add a new state
            self.addState = function (countryId, name) {
                var data = {
                    name: name,

                };
                return restangular.one('countries', countryId).all('states').customPOST(data);
            };
            //edit a state
            self.editState = function (countryId, stateId, name) {
                var data = {
                    name: name,
                };
                return restangular.one('countries', countryId).one('states', stateId).customPUT(data);
            };
            //add a new city
            self.addCity = function (countryId, stateId, name, tier) {
                var data = {
                    name: name,
                    tier: tier
                };
                return restangular.one('countries', countryId).one('states', stateId).all('cities').customPOST(data);
            };
            //edit a city
            self.editCity = function (countryId, stateId, cityId, name, tier) {
                var data = {
                    name: name,
                    tier: tier
                };
                return restangular.one('countries', countryId).one('states', stateId).one('cities', cityId).customPUT(data);
            };
            //edit template for the survey
            self.editTemplate = function (surveyId, templateId, name, isActive, body, subject) {
                var data = {
                    name: name,
                    isActive: isActive,
                    body: body,
                    subject: subject
                };
                return restangular.one('surveys', surveyId).one('templates', templateId).customPUT(data);
            };
            //get email schedules for the survey
            self.getEmailSchedules = function (surveyId) {
                return restangular.one('surveys', surveyId).customGET('emailSchedules');
            };
            //get unique links for the survey
            self.getUniqueLinks = function (page, count, surveyId) {
                return restangular.one('surveys', surveyId).customGET('uniqueLinks', {
                    page: page,
                    count: count
                });
            }

            //get reports for the survey
            self.getUniqueReports = function (surveyId) {
                return restangular.all('reports').all('survey').customGET(surveyId);
            }

            //create email schedule
            self.createEmailSchedule = function (surveyId, emailSchedule) {
                var data = {
                    scheduleDate: emailSchedule.scheduleDate,
                    count: emailSchedule.count,
                    name: emailSchedule.emailScheduleName,
                    isSendAll: emailSchedule.isSendAll,
                    surveyTemplateId: emailSchedule.surveyTemplateId,
                    scheduleType: emailSchedule.scheduleType || 0,
                    baseEmailScheduleId: emailSchedule.baseEmailScheduleId || null
                };
                return restangular.one('surveys', surveyId).all('emailSchedules').customPOST(data);
            };
            //update email schedule
            self.updateEmailSchedule = function (surveyId, emailSchedule, d) {
                var data = {
                    scheduleDate: d,
                    count: emailSchedule.count,
                    name: emailSchedule.emailScheduleName,
                    isSendAll: emailSchedule.isSendAll,
                    surveyTemplateId: emailSchedule.surveyTemplateId,
                    scheduleType: emailSchedule.scheduleType,

                    baseEmailScheduleId: emailSchedule.baseEmailScheduleId || null
                };
                return restangular.one('surveys', surveyId).one('emailSchedules', emailSchedule.id).customPUT(data);
            };
            //cancel email schedule
            self.cancelEmailSchedule = function (surveyId, emailScheduleId) {
                return restangular.one('surveys', surveyId).one('emailSchedules', emailScheduleId).customGET('cancel');
            };
            //send email schedule
            self.sendEmailSchedule = function (surveyId, emailScheduleId) {
                return restangular.one('surveys', surveyId).one('emailSchedules', emailScheduleId).customGET('start');
            };
            //send emails for testing


            //            self.sendEmail = function(surveyId,templateId) {
            //                return restangular.one('surveys', surveyId).one('templates', templateId).customGET('testing');
            //            }
            //test template
            self.createTestTemplate = function (surveyId, templateId, k) {
                var data = {
                    emails: k
                };
                return restangular.one('surveys', surveyId).one('templates', templateId).one('testing').customPOST(data);
            };

            //attach users to email schedule
            self.createUser = function (surveyId, emailScheduleId, user) {
                var data = {
                    userIds: user
                };
                return restangular.one('surveys', surveyId).one('emailSchedules', emailScheduleId).one('custom').customPOST(data);
            };

            //change attempt status
            self.changeAttemptStatus = function (surveyId, selectedItem, user) {
                var data = {
                    status: selectedItem,
                    allocationIds: user
                };
                return restangular.one('surveys', surveyId).one('allocations').one('update').customPOST(data);
            };
            //get query types
            self.getQueryTypes = function () {
                return restangular.all('queryTypes').customGET();
            };
            //get query status
            self.getQueryStatus = function () {
                return restangular.all('queryStatuses').customGET();
            };
            //get messages
            self.filterMessages = function (page, count, queryType, queryStatus, email) {
                return restangular.all('').customGET('messages',
                    {
                        page: page,
                        count: count,
                        queryType: queryType,
                        queryStatus: queryStatus,
                        email: email
                    });
            };
            //resolve message
            self.markMessageResolved = function (messageId) {
                return restangular.one('messages', messageId).customGET('resolve');
            };
            //submit message
            self.submitMessage = function (queryType, subject, body) {
                var data = {
                    userId: id,
                    queryType: queryType,
                    subject: subject,
                    body: body
                };
                return restangular.all('messages').customPOST(data);
            }
            return self;
        }
    ]);;
//angular.module('app')
//    .factory('reportService', [
//        "Restangular",
//        function (Restangular) {
//            return Restangular.withConfig(function (RestangularConfigurer) {
//                RestangularConfigurer.setBaseUrl('http://137.116.155.221/api/v1');
//            });
//   }
//    ]);;
'use strict';

/**
 * @ngdoc service
 * @name uiApp.Notificationservice
 * @description
 * # Notificationservice
 * Service in the uiApp.
 */
angular.module('app')
    .factory('modalService', [
        '$modal', function ($modal) {
            var self = this;
            var modalInstance = null;
            self.open = function (scope, path,size) {
                modalInstance = $modal.open({
                    templateUrl: path,
                    scope: scope,
                    size:size
                    });
            };
            self.askConfirmation = function (scope, text, func,desc) {
                scope.values = {};
                scope.values.text = text || null;
                scope.values.func = func || null;
                scope.values.desc = desc || null;
                scope.closeDialog = function () {
                    self.close();
                };
                modalInstance = $modal.open({
                    templateUrl: '/public/views/app/confirm.html',
                    scope: scope
                });
            };
            self.close = function () {
                modalInstance.dismiss('close');
            };
            return self;
            // AngularJS will instantiate a singleton by calling "new" on this function
        }
    ]);;
angular.module('app')
    .controller('loginCtrl', [
        '$scope', 'userService', 'localStorageService', '$state', 'authService', 'toastService', 'globalService', '$stateParams',
        function ($scope, userService, localStorageService, $state, authService, toastService, globalService, $stateParams) {
            $scope.vm = {};
            $scope.vm.email = '';
            $scope.vm.password = '';
            $scope.login = function () {
                userService.login($scope.vm.email, $scope.vm.password).then(function (result) {
                    localStorageService.add('token', "bearer " + result.access_token);
                    localStorageService.add('refreshToken', result.refresh_token);
                    localStorageService.add('id', result.userId);
                    localStorageService.add('role', result.roles);
                    localStorageService.add('expiry', result[".expires"]);
                    authService.loginConfirmed(result.access_token);
                    globalService.setIsAuthorised(true);
                    userService.validateSession().then(function () {
                        var role = localStorageService.get('role');
                        userService.getBasicProfileStatus(result.userId).then(function (response) {
                            localStorageService.add('phoneVerified', response.phoneVerified);
                            if (!response.emailVerified) {
                                localStorageService.set('phoneVerified', "");
                                localStorageService.set('token', "");
                                localStorageService.set('refreshToken', "");
                                localStorageService.set('id', "");
                                localStorageService.set('role', ""); //if email not verified remove all data from local Storage
                                userService.validateSession();
                                $state.go('user.emailVerifyPrompt');
                            } else
                                if (!response.hasBasicProfile) {
                                    $state.go('app.common.signupTwo');
                                    toastService.show('Successfully Logged In');
                                } else {
                                    if ($stateParams.success) {
                                        window.location.href = $stateParams.success;
                                    }
                                    else if (role == 'panelist')
                                        $state.go('app.panelist.dashboard');
                                    else
                                        $state.go('app.admin.dashboard', { 'role': role });
                                    toastService.show('Welcome to IndiaSpeaks Portal');
                                }
                        });
                    });

                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };

            $scope.authExternalProvider = function (provider) {
                var baseUrl = globalService.getBaseUrl();

                var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';

               var externalProviderUrl = baseUrl + "/Accounts/ExternalLogin?provider=" + provider
                    + "&response_type=token&client_id=ngApp&redirect_uri=" + redirectUri;
                window.$windowScope = $scope;
                window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
            };

           $scope.authCompletedCB = function (fragment) {
                $scope.$apply(function () {
                    if (fragment.haslocalaccount == 'False') {
                        userService.logout();
                        userService.externalAuthData = {
                            provider: fragment.provider,
                            userName: fragment.external_user_name,
                            externalAccessToken: fragment.external_access_token,
                            email: fragment.email
                        };
                        $state.go('user.externalLogin');
                    } else {
                        //Obtain access token and redirect to orders
                        userService.obtainAccessToken(fragment.provider, fragment.external_access_token).then(function (result) {
                            localStorageService.add('token', "bearer " + result.access_token);
                            //                            localStorageService.add('refreshToken', result.refresh_token);
                            localStorageService.add('id', result.userId);
                            localStorageService.add('role', result.roles);
                            localStorageService.add('expiry', result[".expires"]);
                            authService.loginConfirmed(result.access_token);
                            globalService.setIsAuthorised(true);
                            userService.validateSession().then(function () {
                                var role = localStorageService.get('role');
                                userService.getBasicProfileStatus(result.userId).then(function (response) {
                                    localStorageService.add('phoneVerified', response.phoneVerified);
                                    if (!response.hasBasicProfile) {
                                        $scope.eventCodeForFbOldUser();
                                        $state.go('app.common.signupTwo');
                                        toastService.show('Successfully Logged In');
                                    } else {
                                        if ($stateParams.success) {
                                            window.location.href = $stateParams.success;
                                        }
                                        if (role == 'panelist')
                                            $state.go('app.panelist.dashboard');
                                        else
                                            $state.go('app.admin.dashboard', { 'role': role });
                                        toastService.show('Successfully Logged In');
                                    }
                                });
                            });
                        }, function (err) {
                            toastService.showError(err.data.error_description);
                        });
                    }

                });
           };

           $scope.eventCodeForFbOldUser = function () {
               fbq('track', 'Lead');
           };
        }
    ]);;
angular.module('app')
    .controller('signUpCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'globalService', 'authService',
        function ($scope, userService, $state, toastService, localStorageService, globalService, authService) {
            $scope.vm = {};
            $scope.vm.email = '';
            $scope.vm.mobile = '';
            $scope.vm.password = '';
            $scope.vm.confirmPassword = '';
            $scope.vm.message = '';
            $scope.vm.isChecked = true;

            //   $scope.vm.publicKey = userService.recaptchaPublicKey;

            //get query string parameter
            var referralIdName = "referralId";
            referralIdName = referralIdName.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + referralIdName + "=([^&#]*)"),
                resultsReferral = regex.exec(location.href);
            var referralId = resultsReferral === null ? "" : decodeURIComponent(resultsReferral[1].replace(/\+/g, " "));
            var marketingIdName = "marketingId";
            marketingIdName = marketingIdName.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regexMarketing = new RegExp("[\\?&]" + marketingIdName + "=([^&#]*)"),
                results = regexMarketing.exec(location.href);
            var marketingId = results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
            $scope.signUp = function () {
             //   $scope.vm.response = vcRecaptchaService.getResponse();
                userService.signUp($scope.vm.email, $scope.vm.mobile, $scope.vm.password, $scope.vm.confirmPassword, referralId, marketingId).then(function () {
                    $scope.eventCode();
                    $state.go('user.signupComplete');
                    
                }, function (err) {
                    if (err.status == 400)
                        toastService.showError(err.data.modelState.error[0]);
//                    else
//                        if (err.status == 401) {
//                            toastService.showError("Invalid Recaptcha.Please try again");
//                            vcRecaptchaService.reload($scope.widgetId);
//                        }
                });
            };

            $scope.eventCode = function () {

//                !function (f, b, e, v, n, t, s) {
//                    if (f.fbq) return; n = f.fbq = function () {
//                        n.callMethod ?
//        n.callMethod.apply(n, arguments) : n.queue.push(arguments)}; if (!f._fbq) f._fbq = n;
//                    n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
//                    t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)}(window,document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
//
//                fbq('init', '142078796230546');
                //                fbq('track', "PageView");

                fbq('track', 'Lead');



            };

            $scope.authExternalProvider = function (provider) {
                var baseUrl = globalService.getBaseUrl();

                var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';

                var externalProviderUrl = baseUrl + "/Accounts/ExternalLogin?provider=" + provider
                    + "&response_type=token&client_id=ngApp&redirect_uri=" + redirectUri + "&referralId=" + referralId + "&marketingId=" + marketingId;
                window.$windowScope = $scope;

                window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
            };

            $scope.authCompletedCB = function (fragment) {
                $scope.$apply(function () {

                    if (fragment.haslocalaccount == 'False') {
                        userService.logout();
                        userService.externalAuthData = {
                            provider: fragment.provider,
                            userName: fragment.external_user_name,
                            externalAccessToken: fragment.external_access_token,
                            email: fragment.email,
                            referralId: referralId,
                            marketingId: marketingId
                        };
                        $state.go('user.externalLogin');
                    } else {
                        //Obtain access token and redirect to orders
                        userService.obtainAccessToken(fragment.provider, fragment.external_access_token).then(function (result) {
                            localStorageService.add('token', "bearer " + result.access_token);
                            //localStorageService.add('refreshToken', result.refresh_token);
                            localStorageService.add('id', result.userId);
                            localStorageService.add('role', result.roles);
                            authService.loginConfirmed(result.access_token);
                            globalService.setIsAuthorised(true);
                            var role = localStorageService.get('role');
                            userService.getBasicProfileStatus(result.userId).then(function (response) {
                                localStorageService.add('phoneVerified', response.phoneVerified);
                                if (!response.hasBasicProfile) {
                                    $scope.eventCodeForFbOldUserSignupPage();
                                    $state.go('app.common.signupTwo');
                                    toastService.show('Successfully Logged In');
                                } else {
                                    if (role == 'panelist')
                                        $state.go('app.panelist.dashboard');
                                    else
                                        $state.go('app.admin.dashboard', { 'role': role });
                                    toastService.show('Successfully Logged In');
                                }
                            });

                        }, function (err) {
                            if (err.status == 400)
                                toastService.showError(err.data.modelState.error[0]);
                        });
                    }

                });
            };

            $scope.eventCodeForFbOldUserSignupPage = function() {
                fbq('track', 'Lead');
            };

//            $scope.setResponse = function (response) {
//                $scope.vm.response = response;
//            };
//            $scope.setWidgetId = function (widgetId) {
//                $scope.vm.widgetId = widgetId;
//            };

        }
    ]);;
angular.module('app')
    .controller('forgotPasswordCtrl', [
        '$scope', 'userService', '$state', function ($scope, userService, $state) {
            $scope.vm = {};
            $scope.vm.email = '';
            $scope.vm.showSignIn = false;
            $scope.resetPassword = function () {
                userService.forgotPassword($scope.vm.email).then(function () {
                    $scope.vm.showSignIn = true;
                });
            };
        }
    ]);;
angular.module('app')
    .controller('externalLoginCtrl', [
        '$scope', 'userService', '$state', 'localStorageService', 'authService', 'globalService','toastService',
        function ($scope, userService, $state, localStorageService, authService, globalService,toastService) {
            $scope.vm = {};
            $scope.vm.email = '';
            $scope.vm.mobile = '';
            $scope.registerData = {
                userName: userService.externalAuthData.userName,
                provider: userService.externalAuthData.provider,
                externalAccessToken: userService.externalAuthData.externalAccessToken,
                email: userService.externalAuthData.email,
                referralId: userService.externalAuthData.referralId,
                marketingId: userService.externalAuthData.marketingId
            };
            $scope.externalLogin = function () {
                userService.externalLogin($scope.registerData.email, $scope.vm.mobile, $scope.registerData.provider, $scope.registerData.externalAccessToken, $scope.registerData.referralId, $scope.registerData.marketingId).then(function (result) {
                    localStorageService.add('token', "bearer " + result.access_token);
                    localStorageService.add('refreshToken', result.refresh_token);
                    localStorageService.add('id', result.userId);
                    localStorageService.add('role', result.roles);
                    authService.loginConfirmed(result.access_token);
                    globalService.setIsAuthorised(true);
                    $scope.eventCodeForFbNewUser();
                    $state.go('app.common.signupTwo');
                } , function(err) {
                    toastService.showError("A user already exists for this Phone Number");
                });
            };

            $scope.eventCodeForFbNewUser = function () {
                fbq('track', 'Lead');
            };
        }
    ]);;
angular.module('app')
    .controller('verifyEmailCtrl', [
        '$scope', 'userService', 'toastService', '$state',
        function($scope, userService, toastService, $state) {
            $scope.vm = {};
            $scope.vm.email = '';
            $scope.emailVerification = function() {
                userService.verifyEmail($scope.vm.email).then(function() {
                    $state.go('user.emailVerifyPrompt');
                }, function(err) {
                    toastService.showError(err.data.error_description);
                });
            };
        }
    ]);;
angular.module('app')
    .controller('resetPasswordCtrl', [
        '$scope', 'userService', 'toastService', '$state', '$stateParams',
        function ($scope, userService, toastService, $state, $stateParams) {
            $scope.vm = {};
            $scope.vm.password = '';
            $scope.vm.confirmPassword = '';
            $scope.vm.resetPasswordSuccess = false;
            var email = $stateParams.email;
            var token = $stateParams.token;
            $scope.resetPassword = function () {
                userService.resetPassword($scope.vm.password, email, token).then(function () {
                    $scope.vm.resetPasswordSuccess = true;
                    $scope.vm.password = '';
                    $scope.vm.confirmPassword = '';
                    $scope.changePasswordForm.$setPristine();
                }, function (err) {
                    toastService.showError(err.data.message);
                });
            };
        }
    ]);;
angular.module('app')
    .controller('panelistAppCtrl', [
        'localStorageService', '$scope','userService','$state','$interval','$rootScope',
        function (localStorageService, $scope, userService, $state, $interval, $rootScope) {

                        $scope.phoneVerified = localStorageService.get('phoneVerified');

            $rootScope.$on("CallParentMethod", function () {
                $scope.parentMethod();
            });

            $scope.parentMethod = function() {
                $scope.phoneVerified = localStorageService.get('phoneVerified');
            };


            $scope.vm = {};
            $scope.vm.mobile = '';
            userService.getUserInfo().then(function(response) {
                $scope.vm.mobile = response.basicProfile.mobile;
            });
            
            $scope.verifctnMobile = function() {
                userService.verifyMobile($scope.vm.mobile).then(function () {
                    $state.go('app.panelist.verifyOTP');
                }, function (err) {
                    $scope.vm.message = err.data.error_description;

                });
            };
        }
    ]);;
angular.module('app')
    .controller('panelistNavCtrl', [
        '$scope', 'userService', '$state', 'appService',
        function($scope, userService, $state, appService) {
            $scope.vm = {};
            $scope.vm.profiles = [];
            //$scope.showProfileDashboard = function () {
            //    appService.getProfiles().then(function (result) {
            //        $scope.vm.profiles = result.profiles;
            //        $state.go('app.profileDashboard');
            //    });
            //};
            $scope.logout = function() {
                userService.logout();
                //.then(function () {
                $state.go('user.login');
                //});
            };
        }
    ]);;
angular.module('app')
    .controller('panelistHeaderCtrl', [
        '$scope', 'userService', '$state','$window',
        function($scope, userService, $state, $window) {
            $scope.vm = {};
           $scope.vm.toTitleCase = function(str) {
                return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
            }
            userService.getUserInfo().then(function(result) {
                $scope.vm.userInfo = result.basicProfile;
                $scope.vm.a = $scope.vm.toTitleCase($scope.vm.userInfo.firstName);
                $scope.vm.b = $scope.vm.toTitleCase($scope.vm.userInfo.lastName);
                });

            $scope.logout = function() {
                userService.logout();
                //.then(function () {
                $state.go('user.login');
                $window.location.reload();
                //});
            };

            $scope.openPanelistNavbar = function () {
                var myE2 = angular.element(document.querySelector('#navigationbarMenu2'));
                myE2.removeClass('collapse');
                myE2.removeClass('in');
                myE2.addClass('collapse');
            };
            
        }
    ]);;
angular.module('app')
    .controller('panelistProfileCtrl', [
        '$scope', 'userService', 'localStorageService', '$state', 'authService', 'appService', '$stateParams', 'toastService',
        function($scope, userService, localStorageService, $state, authService, appService, $stateParams, toastService) {
            $scope.vm = {};
            $scope.vm.profile = [];
            $scope.vm.progressStatus = '';
            $scope.vm.profileCompleted = null;
            $scope.profileId = $stateParams.profileId;
            //get a single profile for a user 
            appService.getProfile($scope.profileId).then(function(result) {
                $scope.vm.profile = result;
                $scope.vm.profileCompleted = result.percentageCompletion;
                if ($scope.vm.profile.percentageCompletion < 25)
                    $scope.vm.progressStatus = 'danger';
                else if ($scope.vm.profile.percentageCompletion <= 75)
                    $scope.vm.progressStatus = 'warning';
                else
                    $scope.vm.progressStatus = 'success';
                angular.forEach($scope.vm.profile.questions, function(value) {
                    if (value.userResponse == null)
                        value.userResponse = { questionId: value.id, optionsIds: [] };
                });
                
            });
            // update profile for a user
            $scope.saveProfile = function() {
                var userResponse = [];
                angular.forEach($scope.vm.profile.questions, function(value) {
                    if (value.userResponse.optionsIds.length)
                        userResponse.push(value.userResponse);
                  });
                appService.updateProfileForSingleUser($scope.profileId, userResponse).then(function() {
                    toastService.show('Profile has been successfully saved');
                    $state.go($state.current, {}, { reload: true });
                });
            };
        }
    ]);;
angular.module('app')
    .controller('panelistSurveyDashboardCtrl', [
        '$scope', 'userService', 'localStorageService', '$state', 'authService', 'appService', 'toastService', 'modalService',
        function ($scope, userService, localStorageService, $state, authService, appService, toastService, modalService) {
            $scope.vm = {};
            $scope.vm.surveys = [];
            $scope.vm.page = 1;
            $scope.vm.getSurveyData = 'starting';
            //            $scope.vm.count = 10;
            //get all surveys
            appService.getSurveys($scope.vm.page, $scope.count).then(function (result) {
                $scope.vm.surveys = result;
                if ($scope.vm.surveys.data.length === 0)
                    $scope.vm.getSurveyData = 'noData';
            }, function(error) {
                $scope.vm.getSurveyData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            $scope.pageChanged = function () {
                appService.getSurveys($scope.vm.page, $scope.count).then(function (result) {
                    $scope.vm.surveys = result;
                });
            };
            $scope.showSurveyDetails = function (survey) {
                $scope.vm.survey = survey;
                modalService.open($scope, '/public/views/app/panelist/modals/viewSurveyDetails.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.startSurvey = function (id) {
                appService.startSurvey(id).then(function (result) {
                    window.open(result.url, '_self');
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
        }
    ]);;
angular.module('app')
    .controller('panelistRedemptionDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService', 'userService','$modalStack','$window',
        function ($scope, localStorageService, $state, appService, modalService, toastService, userService,$modalStack,$window) {
            $scope.vm = {};
            $scope.vm.redemptions = [];
            $scope.vm.redemptionModes = [];
            $scope.vm.redemptionMode = null;
            $scope.vm.minimumPoints = 0;
            $scope.vm.points = 0;
            $scope.vm.totalPoints = 0;
            $scope.vm.redeemedPoints = 0;
            $scope.vm.inProgressPoints = 0;
            $scope.vm.redeemablePoints = 0;
            $scope.vm.btnDisabled = false;
            $scope.vm.redemptionRequestDate = new Date();
            $scope.vm.remarks = '';
            $scope.vm.phoneVerified = localStorageService.get('phoneVerified');
            $scope.vm.page = 1;
            $scope.isMoreThanMinPoints = false;
            $scope.vm.getRequestData = 'starting';
            var xyz = "";
            //get all redemptions
            appService.getRedemptions($scope.vm.page, $scope.count).then(function (result) {
                $scope.vm.redemptions = result;
                if ($scope.vm.redemptions.data.length === 0)
                    $scope.vm.getRequestData = 'noData';
            }, function(error) {
                $scope.vm.getRequestData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //get total points
            appService.getTotalPoints().then(function (result) {
                $scope.vm.totalPoints = result.points;
            });
            //get redeemed points status
            appService.getRedemptionPointsStatus().then(function (result) {
                $scope.vm.redeemedPoints = result.completed;
                $scope.vm.inProgressPoints = result.inProgress + result.new;
            });
            $scope.createRedemptionRequestDialog = function () {
                $scope.vm.redeemablePoints = $scope.vm.totalPoints - $scope.vm.redeemedPoints - $scope.vm.inProgressPoints;
                if ($scope.vm.phoneVerified == 'false')
                    toastService.showError('You must verify your mobile first to redeem any points');
                else if ($scope.vm.redeemablePoints <= 0)
                    toastService.showError('You do not have any points to redeem');
                else {
                    $scope.vm.name = false;
                    $scope.vm.mobile = false;
                    $scope.vm.address = false;
                    appService.getRedemptionModes().then(function (result) {
                        $scope.vm.redemptionModes = result.values;
                    });
                    userService.getUserInfo().then(function (result) {
                        $scope.vm.userInfo = result.basicProfile;
                    });


                    modalService.open($scope, '/public/views/app/panelist/modals/createRedemption.html');
                    $scope.closeForm = function () {
                        $modalStack.dismissAll();
                    }
                }
            };
            //get all countries
            appService.getCountries().then(function (result) {
                $scope.vm.countries = result.data;
            });
            //get states for country
            $scope.getStates = function () {
                appService.getStates($scope.vm.userInfo.country).then(function (result) {
                    $scope.vm.states = result.states;
                });
            };
            //get cities
            $scope.getCities = function () {
                appService.getCities($scope.vm.userInfo.country, $scope.vm.userInfo.state).then(function (result) {
                    $scope.vm.cities = result.cities;
                });
            }
            $scope.getMinimumPoints = function (mode) {
                angular.forEach($scope.vm.redemptionModes, function (value) {
                    if (value.id == mode) {
                        $scope.vm.minimumPoints = value.minimumPoints;
                        $scope.vm.mobile = value.usePhone;
                        $scope.vm.name = value.useName;
                        $scope.vm.address = value.useAddress;
                        $scope.vm.points = value.minimumPoints;
                        $scope.checkIfMoreThanMinPoints();
                    }
                });
            };
            $scope.checkIfMoreThanMinPoints = function () {
                if ($scope.vm.points >= $scope.vm.minimumPoints && (($scope.vm.points) % 50) === 0)
                    $scope.isMoreThanMinPoints = true;
                else
                    $scope.isMoreThanMinPoints = false;
            }
 
            $scope.createConfirmRedemptionRequest = function () {
                   
                       if ($scope.vm.address) {
                                   var sel = document.createRedemptionRequestForm.country;
            var opt = sel.options[sel.selectedIndex];
                           var g = opt.value;
               
                                           var sel1 = document.createRedemptionRequestForm.state;
            var opt1 = sel1.options[sel1.selectedIndex];
                           var h = opt1.value;


                                             var sel2 = document.createRedemptionRequestForm.city;
            var opt2 = sel2.options[sel2.selectedIndex];
                           var l = opt2.value;
                                                    
                               if((l%1) ===0) {
                                   xyz = "abc";
                               }
                           if (g !== "" && h !== "" && xyz === "abc")
                           //                               modalService.askConfirmation($scope, 'Please confirm the details entered by you are correct. Your reward will be dispatched as per the details given by you', 'createRedemptionRequest()');
                               modalService.open($scope, '/public/views/app/panelist/modals/createRedemptionRequest.html');
                           else {
                               toastService.showError('Please select country state and city from dropdown list');
                           }
                       } else {

                           //                 modalService.askConfirmation($scope, 'Please confirm the details entered by you are correct. Your reward will be dispatched as per the details given by you', 'createRedemptionRequest()');
                           modalService.open($scope, '/public/views/app/panelist/modals/createRedemptionRequest.html');

                       }
                $scope.closeSecondModal = function() {
                    modalService.close();
                }
            }

            $scope.createRedemptionRequest = function () {
                $scope.vm.btnDisabled = true;

                if (!$scope.vm.name) //for mobile recharge mode name and address not required
                {
                    $scope.vm.userInfo.firstName = null;
                    $scope.vm.userInfo.addressLine1 = null;
                    $scope.vm.userInfo.addressLine2 = null;
                    $scope.vm.userInfo.country = null;
                    $scope.vm.userInfo.state = null;
                    $scope.vm.userInfo.city = null;
                    $scope.vm.userInfo.pincode = null;
                }

                appService.createRedemptionRequest($scope.vm.redemptionMode, $scope.vm.points,
                            $scope.vm.redemptionRequestDate, $scope.vm.userInfo)
                    .then(function () {
                   toastService.show("Redemption Request created successfully");
                    $modalStack.dismissAll();
                        //                        $state.go($state.current,{},{reload:true});
                    $window.location.reload();
                }, function (error) {
                    toastService.showError(error.data.message);
                    $modalStack.dismissAll();

                });

                //close self

            };

            $scope.pageChanged = function () {
                appService.getRedemptions($scope.vm.page, $scope.count).then(function (result) {
                    $scope.vm.redemptions = result;
                });
            };
        }
    ]);;
angular.module('app')
    .controller('panelistRewardDashboardCtrl', [
        '$scope', 'userService', 'localStorageService', '$state', 'authService', 'appService','toastService',
        function ($scope, userService, localStorageService, $state, authService, appService, toastService) {
            $scope.vm = {};
            $scope.vm.rewards = [];
            $scope.vm.page = 1;
            $scope.vm.getRewardData = 'starting';
            //get all rewards
            appService.getRewards($scope.vm.page, $scope.count).then(function (result) {
                $scope.vm.rewards = result;
                if ($scope.vm.rewards.data.length === 0)
                    $scope.vm.getRewardData = 'noData';
            }, function(error) {
                $scope.vm.getRewardData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //get rewards points status
            appService.getRewardsPointsStatus().then(function (result) {
                $scope.vm.surveyPoints = result.survey;
                $scope.vm.referralPoints = result.referral;
                $scope.vm.sweepstakePoints = result.sweepstake;
                $scope.vm.legacyPoints = result.legacy;
                $scope.vm.totalPoints = result.survey + result.referral + result.sweepstake + result.legacy;
            });
            $scope.pageChanged = function () {
                appService.getRewards($scope.vm.page, $scope.count).then(function (result) {
                    $scope.vm.rewards = result;
                });
            };

        }
    ]);;
angular.module('app')
    .controller('panelistReferralDashboardCtrl', [
        '$scope', 'appService', 'modalService', '$window', 'localStorageService', '$state', 'toastService', '$location',
        function ($scope, appService, modalService, $window, localStorageService, $state, toastService, $location) {
            $scope.vm = {};
            $scope.vm.referrals = [];
            $scope.vm.referralName = '';
            $scope.vm.referralEmail = '';
            $scope.vm.referralMobile = '';
            $scope.vm.showReferFriend = false;
            $scope.vm.FileUploaded = false;
            $scope.vm.file = null;
            $scope.vm.page = 1;
            var userId = localStorageService.get('id');
            $scope.vm.referralUrl = 'http://' + $location.host() + '/referrals/view/' + userId;
            $scope.vm.getReferralData = 'starting';

            //get all referrals
            appService.getReferrals($scope.vm.page, $scope.count).then(function (result) {
                $scope.vm.referrals = result;
                if ($scope.vm.referrals.data.length === 0) {
                    $scope.vm.getReferralData = 'noData';
                }
            }, function(error) {
                $scope.vm.getReferralData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });

            //refer a friend
            $scope.createReferral = function () {
                appService.createReferral($scope.vm.referralName, $scope.vm.referralEmail, $scope.vm.referralMobile).then(function () {
                    toastService.show("Referral created successfully");
                    $state.go($state.current, {}, { reload: true });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };

            //upload referrals from a csv file
            $scope.uploadReferralFile = function () {
                var file = document.getElementById("referralCreateFile").files[0];
                appService.uploadReferralFile(file).then(function () {
                    $state.go($state.current, {}, { reload: true });
                    toastService.show("Referral Uploaded Successfully");
                }, function (err) {
                    toastService.showError(err.data.error_description);
                });

            };

            $scope.file_changed = function () {
                var file = document.getElementById("referralCreateFile").files[0];
                if (angular.isDefined(file))
                    $scope.vm.fileUploaded = true;
                else
                    $scope.vm.fileUploaded = false;
            };

            //import referrals from gmail
            $scope.importFromGmail = function () {
                var id = localStorageService.get('id');
                var left = screen.width / 2 - 200,
                    top = screen.height / 2 - 250,
                    popup = $window.open('/Referrals/gmail/' + id, '', "top=" + top + ",left=" + left + ",width=400,height=500");
                popup.onbeforeunload = function () {
                    toastService.show("Referrals imported successfully");
                    $state.go($state.current, {}, { reload: true });
                };
            };

            //import referrals from yahoo
            $scope.importFromYahoo = function () {
                var id = localStorageService.get('id');
                var left = screen.width / 2 - 200,
                    top = screen.height / 2 - 250,
                    popup = $window.open('/Referrals/yahoo/' + id, '', "top=" + top + ",left=" + left + ",width=400,height=500");
                popup.onbeforeunload = function () {
                    toastService.show("Referrals imported successfully");
                    $state.go($state.current, {}, { reload: true });
                };
            };


            $scope.pageChanged = function () {
                appService.getReferrals($scope.vm.page, $scope.count).then(function (result) {
                    $scope.vm.referrals = result;
                });
            };
        }
    ]);;
angular.module('app')
    .controller('panelistChangePasswordCtrl', [
        '$scope', 'userService', 'localStorageService', '$state', 'authService', 'appService', 'toastService',
        function($scope, userService, localStorageService, $state, authService, appService, toastService) {
            $scope.vm = {};
            $scope.vm.currentPassword = '';
            $scope.vm.newPassword = '';
            $scope.vm.confirmPassword = '';
            $scope.changePassword = function() {
                appService.changePassword($scope.vm.currentPassword, $scope.vm.newPassword, $scope.vm.confirmPassword).then(function() {
                    toastService.show('Password changed successfully');
                });
            };
        }
    ]);;
angular.module('app')
    .controller('panelistAccountCtrl', [
        '$scope', 'userService', '$state', 'appService', 'toastService', 'modalService','$window',
        function ($scope, userService, $state, appService, toastService, modalService,$window) {
            $scope.vm = {};
            $scope.vm.toTitleCase = function (str) {
                return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
            }
            userService.getUserInfo().then(function (result) {
                $scope.vm.user = result;
                $scope.vm.userInfo = result.basicProfile;
                $scope.vm.a = $scope.vm.toTitleCase($scope.vm.userInfo.firstName);
                $scope.vm.b = $scope.vm.toTitleCase($scope.vm.userInfo.lastName);
            });
            //get user image
            appService.getUserPic().then(function (result) {
                $scope.vm.userPic = result.url;
            });
            //delete account
            $scope.confirmDeleteAccount = function () {
                modalService.askConfirmation($scope, 'Are you sure you want to delete your account?', 'deleteAccount()','You will not be able to take any surveys or claim any awards if you choose to delete your account.');
            }
            $scope.deleteAccount = function () {
                appService.deleteAccount().then(function () {
                    modalService.close();
                    toastService.show('Profile Deleted Successfully');
                    userService.logout();
                    //.then(function () {
                    $state.go('user.login');
                    //});
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
            //subscribe
            $scope.subscribe = function () {
                appService.subscribe().then(function () {
//                    $scope.vm.user.isUnsubscribed = false;
                    toastService.show("You are subscribed successfully");
                    //                    $window.location.reload();
                    $state.go($state.current, {}, { reload: true });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };

            //changing password
            $scope.changingPasswordDialog = function() {
                $scope.vm.currentPassword = '';
                $scope.vm.newPassword = '';
                $scope.vm.confirmPassword = '';

                modalService.open($scope, '/public/views/app/panelist/modals/changingPassword.html');
                $scope.closeForm = function() {
                    modalService.close();
                }
            };
            $scope.changingPassword = function() {
                appService.changePassword($scope.vm.currentPassword,$scope.vm.newPassword,$scope.vm.confirmPassword).then(function()
                {
                    modalService.close();
                    toastService.show("Password changed successfully");
                }, function (error) {
                toastService.showError(error.data.message);
            });
        };
               
        //unsubscribe
            $scope.confirmUnsubscribe = function () {
                modalService.askConfirmation($scope, 'Are you sure you want to unsubscribe yourself?', 'unsubscribe()');
            }
            $scope.unsubscribe = function () {
                appService.unsubscribe().then(function () {
                    modalService.close();
//                    $scope.vm.user.isUnsubscribed = true;
                  
                    //                    $window.location.reload();
                    $state.go($state.current, {}, { reload: true });
                    toastService.show("You are unsubscribed successfully");
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
            $scope.closeDialog = function () {
                modalService.close();
            };

        }
    ]);;
'use strict';

angular.module('app')
    .controller('panelistEditAccountCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService',
        function ($scope, userService, $state, toastService, localStorageService, appService) {
            $scope.referralSources = {};
            userService.getReferralSources().then(function (result) {
                $scope.referralSources = result.values;
            });

            $scope.vm = {};
            //get all countries
            appService.getCountries().then(function (result) {
                $scope.countries = result.data;
            });
            //get states for country
            $scope.getStates = function () {
                $scope.states = [];
                appService.getStates($scope.vm.country).then(function (result) {
                    $scope.states = result.states;
                });
                if ($scope.vm.country === $scope.vm.countryObj.id) {
                    $scope.vm.state = $scope.vm.stateObj.id;
                    $scope.vm.city = $scope.vm.cityObj.id;
                }
                else {
                    $scope.vm.state = '';
                    $scope.vm.city = '';
                }
            };
            //get cities
            $scope.getCities = function () {
                $scope.cities = [];
                appService.getCities($scope.vm.country, $scope.vm.state).then(function (result) {
                    $scope.cities = result.cities;
                });
                if ($scope.vm.country === $scope.vm.countryObj.id && $scope.vm.state === $scope.vm.stateObj.id)
                    $scope.vm.city = $scope.vm.cityObj.id;
                else
                    $scope.vm.city = '';
            };
            userService.getUserInfo().then(function (result) {
                $scope.vm = result.basicProfile;
                $scope.vm.dateFilled = moment($scope.vm.dateOfBirth).format("YYYY-MM-DD");
//                $scope.vm.currentDate = moment().format("YYYY-MM-DD");
                $scope.vm.allowedDate = moment().subtract(15, 'years').format('YYYY-MM-DD');

                $scope.getStates();
                $scope.getCities();
                $scope.vm.phoneVerified = localStorageService.get('phoneVerified');
            });
            $scope.updateAccount = function () {
//                if ($scope.vm.dateFilled > $scope.vm.currentDate) {
//                    toastService.showError('Please provide proper date of birth');
//                }

                if ($scope.vm.dateFilled > $scope.vm.allowedDate) {
                    toastService.showError('Your age must be greater than 15 to join this survey portal.');
                } else {

                    userService.editAccountByPanelist($scope.vm, $scope.vm.dateFilled).then(function() {
                        toastService.show('Successfully updated Profile');
                        $state.go('app.panelist.account');
                    });
                }
            }
        }
    ]);;
angular.module('app')
    .controller('panelistDashboardCtrl', [
        '$scope','toastService','$window','userService', 'appService',
        function ($scope,toastService,$window,userService, appService) {
            $scope.vm = {};
            $scope.vm.profiles = [];
            $scope.vm.profilesCompleted = null;
            $scope.vm.progressStatus = '';
            $scope.vm.pendingProfiles = 0;
            $scope.vm.totalReferralsSent = 0;
            $scope.vm.zoomIcon = false;
            //get user image
            appService.getUserPic().then(function (result) {
                $scope.vm.userPic = result.url;
            });
            //get all profiles
            appService.getProfiles().then(function (result) {
                $scope.vm.profiles = result.profiles;
                var sum = 0;
                $scope.vm.pendingProfiles = 0;
                angular.forEach($scope.vm.profiles, function (value) {
                    sum += value.percentageCompletion;
                    if (value.percentageCompletion < 100)
                        $scope.vm.pendingProfiles++;
                });
                $scope.vm.profilesCompleted = Math.floor(sum / $scope.vm.profiles.length);
                if ($scope.vm.profilesCompleted < 25)
                    $scope.vm.progressStatus = 'danger';
                else if ($scope.vm.profilesCompleted <= 75)
                    $scope.vm.progressStatus = 'warning';
                else
                    $scope.vm.progressStatus = 'success';
            });
            function toTitleCase(str) {
                return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
            }
            //get user info
            userService.getUserInfo().then(function (result) {
                $scope.vm.lastUpdatedProfile = result.lastUpdatedProfile;
               $scope.vm.userInfo = result.basicProfile;
                $scope.vm.a= toTitleCase($scope.vm.userInfo.firstName);
                $scope.vm.b = toTitleCase($scope.vm.userInfo.lastName);

            });
            


            //get rewards points status
            appService.getRewardsPointsStatus().then(function (result) {
                $scope.vm.surveyPoints = result.survey;
                $scope.vm.referralPoints = result.referral;
                $scope.vm.legacyPoints = result.legacy;
                $scope.vm.sweepstakePoints = result.sweepstake;
            });

            //get redeemed points status
            appService.getRedemptionPointsStatus().then(function (result) {
                $scope.vm.totalRedeemedPoints = result.completed + result.inProgress + result.new;
            });

            //get referrals status
            appService.getReferralsStatus().then(function (result) {
                $scope.vm.totalReferralsSent = result.pending + result.invited + result.accepted + result.pendingApproval + result.approved;
                $scope.vm.totalReferralsAccepted = result.approved;
            });

            //get surveys status
            appService.getSurveysStatus().then(function (result) {
                $scope.vm.notStartedSurveys = result.notStarted;
                $scope.vm.incompleteSurveys = result.incomplete + result.disqualified + result.outlier + result.overQuota + result.closedSurvey + result.rejected;
                $scope.vm.completeSurveys = result.complete + result.pointsRewarded;
                $scope.vm.totalSurveys = result.notStarted + result.incomplete + result.complete + result.disqualified + result.overQuota + result.closedSurvey + result.outlier + result.pointsRewarded + result.rejected;
            });

            $scope.file_changed = function () {
                var file = document.getElementById("fileId").files[0];
                appService.updateUserPic(file).then(function () {
                    appService.getUserPic().then(function (result) {
                        $scope.vm.userPic = result.url;
                        toastService.show("Profile Picture Uploaded Successfully");
                      $window.location.reload();
                       });
                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
           };
        }
    ]);;
angular.module('app')
    .controller('panelistSurveyFinishedCtrl', [
        '$scope', '$stateParams', function ($scope, $stateParams) {
            var surveyId = $stateParams.id;
            $scope.vm = {};

        }
    ]);;
angular.module('app')
    .controller('panelistMessageCtrl', [
        '$scope', 'userService', 'appService', 'toastService', '$state',
        function ($scope, userService, appService, toastService, $state) {
            $scope.vm = {};
            $scope.vm.queryType = '';
            $scope.vm.subject = '';
            $scope.vm.body = '';
            //get query Types
            appService.getQueryTypes().then(function (result) {
                $scope.vm.queryTypes = result.values;
            });
            $scope.submitQuery = function () {
                appService.submitMessage($scope.vm.queryType, $scope.vm.subject, $scope.vm.body).then(function () {
                    toastService.show("Your request has been successfullly recorded and will be resolved soon.");
                    $state.go($state.current, {}, { reload: true });
                });
            };
        }
    ]);;
angular.module('app')
    .controller('panelistVerifyMobileCtrl', [
        '$scope', 'userService', 'localStorageService', '$state',
        function ($scope, userService, localStorageService, $state) {
            $scope.vm = {};
            $scope.vm.mobile = '';
            userService.getUserInfo().then(function (response) {
                $scope.vm.mobile = response.basicProfile.mobile;
            });
            $scope.skipStep = function () {
                if (localStorageService.role == 'panelist')
                    $state.go('app.panelist.dashboard');
                else
                    $state.go('app.admin.dashboard', { 'role': role });
            };
            $scope.mobileVerification = function () {
                userService.verifyMobile($scope.vm.mobile).then(function () {
                    $state.go('app.panelist.verifyOTP');
                }, function (err) {
                    $scope.vm.message = err.data.error_description;
                });
            };
        }
    ]);;
angular.module('app')
    .controller('panelistVerifyOTPCtrl', [
        '$scope', '$window','userService', 'localStorageService', '$state', 'toastService','$rootScope',
        function ($scope, $window,userService,localStorageService, $state, toastService, $rootScope) {
            $scope.vm = {};
            $scope.vm.OTP = '';
            $scope.skipStep = function () {
                $scope.vm.role = localStorageService.get('role');
                if ($scope.vm.role == 'panelist')
                    $state.go('app.panelist.dashboard');
                else
                    $state.go('app.admin.dashboard', { 'role': localStorageService.role });
            };
            $scope.OTPVerification = function () {
                userService.verifyMobileCode($scope.vm.OTP).then(function () {
                    localStorageService.set('phoneVerified', true);
                    toastService.show('Phone Number has been verified');
//                    $state.go('app.panelist.dashboard', {}, { reload: true });
                    $scope.skipStep();
                    //                    $window.location.reload();
                                        $rootScope.$emit("CallParentMethod", {});

                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };
        }
    ]);;
angular.module('app')
    .controller('adminChangePasswordCtrl', [
        '$scope', 'userService', 'localStorageService', '$state', 'authService', 'appService',
        function($scope, userService, localStorageService, $state, authService, appService) {
            $scope.vm = {};
            $scope.vm.currentPassword = '';
            $scope.vm.newPassword = '';
            $scope.vm.confirmPassword = '';
            $scope.changePassword = function() {
                appService.changePassword($scope.vm.currentPassword, $scope.vm.newPassword, $scope.vm.confirmPassword).then(function() {
                });
            };
        }
    ]);;
angular.module('app')
    .controller('adminDashboardCtrl', [
        '$scope', 'localStorageService', 'toastService', 'userService', 'appService','$window',
        function ($scope, localStorageService, toastService, userService, appService,$window) {
            $scope.vm = {};
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.Math = $window.Math;
            $scope.vm.getDashboardSurveyData = 'starting';
            //surveys publish date
            $scope.vm.publishDate = {
                startDate: moment().subtract(30, 'days'),
                endDate: moment()
            };

       //survey filter 
            $scope.vm.dateRangeList = [
                {
                    name: "Last 30 days",
                    dateRange: {
                        startDate: moment().subtract(1, 'month'),
                        endDate: moment()
                    }
                },
                {
                    name: "Last 60 days",
                    dateRange: {
                        startDate: moment().subtract(2, 'months'),
                        endDate: moment()
                    }
                },
                {
                    name: "Last 90 days",
                    dateRange: {
                        startDate: moment().subtract(3, 'months'),
                        endDate: moment()
                    }
                },
                {
                    name: "Last Year",
                    dateRange: {
                        startDate: moment().subtract(1, 'year'),
                        endDate: moment()
                    }
                }
            ];
            //get surveys default
            appService.filterSurveys($scope.vm.page, $scope.vm.count, $scope.vm.publishDate).then(function (result) {
                $scope.vm.surveys = result;
                if ($scope.vm.surveys.data.length === 0)
                    $scope.vm.getDashboardSurveyData = 'noData';

                for (var i = 0; i < $scope.vm.surveys.data.length; i++) {
                    $scope.vm.a = $scope.vm.surveys.data[i].ir;
                    $scope.vm.b = (($scope.vm.a)*100).toFixed(2);
                    $scope.vm.surveys.data[i].ir = $scope.vm.b;
                }
            }, function(error) {
                $scope.vm.getDashboardSurveyData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            $scope.pageChanged = function () {
                appService.filterSurveys($scope.vm.page, $scope.vm.count, $scope.vm.publishDate).then(function (result) {
                    $scope.vm.surveys = result;

                    for (var i = 0; i < $scope.vm.surveys.data.length; i++) {
                        $scope.vm.c = $scope.vm.surveys.data[i].ir;
                        $scope.vm.d = (($scope.vm.c) * 100).toFixed(2);
                        $scope.vm.surveys.data[i].ir = $scope.vm.d;
                    }
                });
            };

            $scope.getSurveyAttemptData = function(a) {
                var surveyId = a;
                appService.getAttemptStatus(surveyId).then(function(result) {
                   // $scope.vm.surveyAttemptData = result;

                    //appService.filterSurveys($scope.vm.page, $scope.vm.count, $scope.vm.publishDate).then(function(result) {
                    //    $scope.vm.surveys = result;

                        for (var i = 0; i < $scope.vm.surveys.data.length; i++) {
                            if ($scope.vm.surveys.data[i].id === surveyId) {
                                $scope.vm.surveys.data[i].completes = result.complete;
                                $scope.vm.surveys.data[i].disqualified = result.disqualified;
                                $scope.vm.surveys.data[i].overquota =result.overQuota;
                                $scope.vm.surveys.data[i].inProgress = result.incomplete;
                            }
                        }
                  //  });
                });
            }
            //filter surveys 
            $scope.filterSurveys = function () {
                $scope.vm.page = 1;
                appService.filterSurveys($scope.vm.page, $scope.vm.count, $scope.vm.publishDate).then(function (result) {
                    $scope.vm.surveys = result;

                    for (var i = 0; i < $scope.vm.surveys.data.length; i++) {
                        $scope.vm.e = $scope.vm.surveys.data[i].ir;
                        $scope.vm.f = (($scope.vm.e) * 100).toFixed(2);
                        $scope.vm.surveys.data[i].ir = $scope.vm.f;
                    }
                });
            }
            //export surveys
            $scope.exportSurveysOnDashboard = function () {
                appService.exportSurveysOnDashboard($scope.vm.page, $scope.vm.count,$scope.vm.publishDate).then(function (data)
                                {
                                       var file = new Blob([data], {
                                           type: 'application/csv'
                                       });
                                       var fileUrl = URL.createObjectURL(file);
                                       var a = document.createElement('a');
                                       a.href = fileUrl;
                                       a.target = '_blank';
                                       a.download = "Surveys on dashboard.csv";
                                       document.body.appendChild(a);
                                       a.click();
                                       document.body.removeChild(a);
                                   });
            };
            
        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminCreateSurveyCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService','$window',
        function($scope, userService, $state, toastService, localStorageService, appService, $window) {
            $scope.vm = {};
            $scope.vm.surveyNames = [];
            $scope.vm.survey = {};
            $scope.vm.survey.blacklistIds = [];
            appService.getSurveyNames().then(function(result) {
                $scope.vm.surveyNames = result.names;
            });

            $scope.createSurvey = function() {
               appService.createSurvey($scope.vm.survey).then(function() {
                    toastService.show("Survey created successfully");
                    $state.go('app.admin.surveyDashboard');
                    $window.location.reload();
                }, function(err) {
                    toastService.showError("Please create the survey correctly");
                });
            };

        }
    ]);
 

   ;
angular.module('app')
    .controller('adminEditSurveyCtrl', [
        '$scope', '$state', 'toastService', 'localStorageService', 'appService', '$stateParams','$window',
        function($scope, $state, toastService, localStorageService, appService, $stateParams,$window) {
            $scope.vm = {};
            appService.getSurveyNames().then(function(result) {
                $scope.vm.surveyNames = result.names;
                angular.forEach($scope.vm.surveyNames, function(value, key) {
                    if (value.id == $stateParams.surveyId)
                        $scope.vm.surveyNames.splice(key, 1);
                });
            });
            appService.getSurvey($stateParams.surveyId).then(function(result) {
                $scope.vm.survey = result;
              
                $scope.vm.a = moment($scope.vm.survey.publishDate).format("YYYY-MM-DD");
                                $scope.vm.b = moment($scope.vm.survey.expiryDate).format("YYYY-MM-DD");
            });
            $scope.editSurvey = function() {
                appService.editSurvey($scope.vm.survey,$stateParams.surveyId,$scope.vm.a,$scope.vm.b).then(function() {
                    toastService.show("Survey updated successfully");
                  $window.location.href = '#/app/gaps/' + $stateParams.surveyId + '/surveyDetails';
                    $window.location.reload();

                }, function(err) {
                    toastService.showError("Please edit the survey correctly");
                });
            }
        }
    ]);;
//'use strict';

angular.module('app')
    .controller('adminSurveyDetailsCtrl', [
        '$scope', '$state', '$window', 'toastService', 'appService', '$stateParams','$modalStack', 'modalService', "Restangular", '$http',
        function ($scope, $state, $window, toastService, appService, $stateParams,$modalStack, modalService, restangular, $http) {
            $scope.vm = {};
            // $scope.vm.emailScheduleSamples = [];
            $scope.vm.emailSchedules = [];
            $scope.vm.emailSchedule = {};
            $scope.vm.blacklistedSurveys = "";
            //            $scope.vm.surveyAttemptStatus = '';
            var editTemplateId = '';
            var cancelEmailScheduleId = '';
            var sendEmailScheduleId = '';
            var indexToBeDeleted = '';
            $scope.vm.page = 1;
            $scope.vm.count = 10;
                        $scope.vm.attemptStatus = '';
                        $scope.vm.f = '';
            $scope.vm.btnDisabled = false;
            // var emailScheduleId = $stateParams.emailScheduleId;
            var surveyId = $stateParams.surveyId;
            $scope.vm.aStatus = '';
            $scope.vm.today = moment();
            appService.getSurvey(surveyId).then(function (result) {
                $scope.vm.survey = result;
                angular.forEach($scope.vm.survey.surveyBlacklists, function (value, key) {
                    if (key == 0)
                        $scope.vm.blacklistedSurveys += value.name;
                    else
                        $scope.vm.blacklistedSurveys += "," + value.name;
                });
            });
            //get all samples
            appService.getSamples(1, -1).then(function (result) {
                $scope.vm.samples = [];
                angular.forEach(result.data, function (value) {
                    if (value.isActive)
                        $scope.vm.samples.push(value);
                });
            });
            //get samples attached to email schedules
            //appService.getEmailScheduleSamples(emailScheduleId).then(function (result) {
            //    $scope.vm.emailScheduleSamples = [];
            //    angular.forEach(result.data, function (value) {
            //        $scope.vm.emailScheduleSamples.push(JSON.stringify(value));
            //    });
            //});
            //get all partners
            appService.getPartners(1, -1).then(function (result) {
                $scope.vm.partners = result.data;
            });
            //get partners attached to survey
            appService.getSurveyPartners(surveyId).then(function (result) {
                $scope.vm.surveyPartners = [];
                angular.forEach(result.data, function (value) {
                    $scope.vm.surveyPartners.push(JSON.stringify(value));
                });
            });
            //add partners
            $scope.addPartners = function () {
                var partnerIds = [];
                if (!$scope.vm.surveyPartners.length)
                    toastService.show('No partners are chosen to assign');
                else {
                    angular.forEach($scope.vm.surveyPartners, function (value) {
                        partnerIds.push(JSON.parse(value).id);
                    });
                    appService.addPartnersToSurvey(partnerIds, surveyId).then(function () {
                        toastService.show("Partners successfully added to survey");
                    });
                }
            };

            //edit surveys
            $scope.editSurvey = function () {
                $state.go('app.admin.editSurvey', { 'surveyId': surveyId });
            };

            //export surveys
            $scope.exportSurvey = function () {
                appService.exportSurvey($scope.vm.page, $scope.vm.count, surveyId, $scope.vm.f).then(function (data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Survey details.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                });
            };
            //upload approvals

            $scope.uploadApprovals = function () {
                var file = document.getElementById("uploadApprovalFileId").files[0];
                if (angular.isDefined(file)) {
                    appService.uploadSurveyApprovals($stateParams.surveyId, file).then(function (result) {
                        toastService.show("Approvals Uploaded Successfully\nApproved :" + result.approved + "  Rejected :" + result.rejected);
                    }, function (err) {
                        toastService.showError(err.data.error_description);
                    });
                } else {
                    toastService.showError("Please choose a file to upload");
                }


            };
            //upload unique links for survey

            $scope.uploadUniqueLinks = function () {
                var file = document.getElementById("uploadUniqueLinksFileId").files[0];
                if (angular.isDefined(file)) {
                    appService.uploadSurveyUniqueLinks($stateParams.surveyId, file).then(function () {
                        toastService.show("Links uploaded successfully");
                        document.getElementById("uploadApprovalFileId").value = "";
                    }, function (err) {
                        toastService.showError(err.data.error_description);
                    });
                } else {
                    toastService.showError("Please choose a file to upload");
                }


            };
            //attach samples to email schedules
            //$scope.attachSamples = function () {
            //    var sampleIds = [];
            //    if (!$scope.vm.emailScheduleSamples.length)
            //        toastService.show('No samples are chosen to assign');
            //    else {
            //        angular.forEach($scope.vm.emailScheduleSamples, function (value) {
            //            sampleIds.push(JSON.parse(value).id);
            //        });
            //        appService.attachSamples(sampleIds, emailScheduleId).then(function () {
            //            toastService.show("Samples successfully attached to email schedules");
            //        });
            //    }
            //};

            //get templates for the survey
            appService.getTemplates(surveyId).then(function (result) {
                $scope.vm.templates = result.data;
            });
            //create template for the survey
            $scope.createTemplateDialog = function () {
                appService.getEmailProperties().then(function (result) {
                    $scope.vm.items = result.values;
                });
                $scope.vm.name = '';
                $scope.vm.item = '';
                $scope.vm.isActive = true;
//                $scope.vm.body = '<p>Dear <span>[[FirstName]] <span>[[LastName]]</span></span>,</p><p><span>IndiaSpeaks brings to you another opportunity to earn rewards through the following survey. This note is to inform you that a survey is now in progress for which your participation is requested.</span></p><p></p><p><b>Reward &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[[SurveyPoints]] Reward Points</b><span> </span><br></p><p><span>Closing Date &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span>[[ClosingDate]]</span></span></p><p><span>Survey On &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [[SurveyName]]</span></p><p><span> Research Sponsor &nbsp; &nbsp;&nbsp;<span>[[ResearchSponsor]]</span></span></p><p><span> Length of Survey &nbsp; &nbsp; &nbsp; &nbsp;<span>[[SurveyLength]] </span>Minutes </span></p><p></p><p><span>You can access the survey by clicking or copying the following URL into your browser:</span></p><p><span><span>[[SurveyUrl]]</span></span></p><p></p><p><span>Please fill in the survey accurately so that you are eligible for the reward.</span></p><p></p><p><span>Best regards,</span></p><p><span>Tanya Basu</span></p><p><span>IndiaSpeaks Community Relations Manager</span></p><p><span><a href="https://www.facebook.com/indiaspeaks.net" target="_blank"><b>IndiaSpeaks Facebook</b></a></span></p><p></p><p></p><p><span><b>- PAYMENT -</b></span></p><p><span><b></b>The survey includes some screening questions to make sure your profile fits our client\'s needs for this particular study. If not, the questionnaire will simply end after these questions, and you will receive new survey opportunities soon. If you qualify and complete the entire survey , the survey incentive will be credited to your account at the end of survey. <br/></span></p><p><b>- TECHNICAL DIFFICULTIES -</b></span></p><p><span>If you encounter any technical difficulties while completing this survey please click here for help or send an email to <u>support@indiaspeaks.net</u></span></p><p><span><b>- WHY DID I RECEIVE THIS E-MAIL? -</b></span></p><p><span>You have received this because you have opted in to participate in IndiaSpeaks Online surveys. If you no longer wish to be a part of the IndiaSpeaks Online Community please click here or send an email to: <u>tanya.basu@indiaspeaks.net</u></span></p><p><span>This survey invitation is intended specifically for the IndiaSpeaks Online member to whom it was sent and is exclusively valid for that member. Publishing or forwarding the invitation is prohibited and may result in removal from the IndiaSpeaks Online panel.</span><br></p>';
                             //   $scope.vm.body = '<html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>IndiaSpeaks</title> <style> body{ margin:0; padding:0; } </style></head> <body> <div class="screen-container-wrap"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, maximum-scale=1"><link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,600&amp;subset=latin,cyrillic" rel="stylesheet" type="text/css"> <table width="100%" align="center" cellpadding="0" cellspacing="0" border="0" bordercolor="" style="background-color: #fafafa;"><tbody><tr><td class="" style="padding: 0 15px;"> <table class="" width="100%" align="center" cellpadding="0" cellspacing="0" border="0" bordercolor="" style="margin: 0 auto;"><!-- Spacer --><tbody><!-- End Spacer --><tr><td class="layouts-here"><repeater><div class="layouts-wrap"> <div class="layout-list ui-sortable"><div class="layout-item"><repeater><!-- Header type 1 --><table width="100%" align="center" cellpadding="0" cellspacing="0" border="0"><tbody><tr> <td style="background-color: #ffffff;"> <table width="100%" align="center" cellpadding="0" cellspacing="0" border="0"><tbody><!-- Logo --><tr><td class="logo" style="border-collapse: collapse; font-size: 0; text-align: center;"> <a href="" class="img-wrap" style="color: #2d2d2d; text-decoration: none;"><div class="bg-options-wrap removethis"><div class="block-bg-image bg-control-item" title="Change image"></div><div class="block-image-link bg-control-item" title="Change image link"></div></div> <img src="https://dl.dropboxusercontent.com/u/18689296/India-Speak/india-speak-mailer/images/logo.jpg" alt="IndiaSpeaks" title="IndiaSpeaks" width="300" height="114" style="border: 0 none;" data-bgedit="image"></a> </td> </tr><!-- End Logo --></tbody></table></td> </tr></tbody></table><!-- End Header type 1 --></repeater></div><div class="layout-item"><repeater><!-- Small white divider --><table width="100%" align="center" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="" height="10" style="font-size: 1px; line-height: 10px; background-color: #ffffff;"><singleline>&nbsp;</singleline></td> </tr></tbody></table><!-- End Small white divider --></repeater></div><div class="layout-item"><repeater><!-- Title centered --> <table width="100%" align="center" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="color-bg" style="background-color:#FFF; padding-left:35px; padding-right:35px;"> <table class="container" width="594" align="center" cellpadding="0" cellspacing="0" border="0" style="margin: 0 auto;"><tbody><tr><!-- content --><td class="h1-s mce-content-body" mc:edit="m5" data-color="4" style="font-family: Open Sans, Arial, sans-serif; font-size: 14px; font-weight: 400; line-height: 1.5; text-align: left; color: #333;" id="mce_10" data-ctag="multiline" data-clabel="title"><multiline label="title"><strong>Dear [[FirstName]] [[LastName]],</strong><br> <br> IndiaSpeaks brings to you another opportunity to earn rewards through the following survey. This note is to inform you that a survey is now in progress for which your participation is requested. </multiline></td> <!-- content --> </tr></tbody></table></td> </tr></tbody></table><!-- End Title centered --></repeater></div><div class="layout-item"><!-- Large image - left, title with button - right --><repeater><table width="100%" align="center" cellpadding="0" cellspacing="0" border="0"><tbody> <tr> <td style="background-color: #ffffff;">&nbsp;</td> </tr> <tr> <td style="background-color: #ffffff;"><table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tbody><tr> <th width="47%" valign="top" scope="row"><table class="m-w100" width="290" align="left" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt;"><tbody><tr><td align="right" valign="top" class="image" style="border-collapse: collapse; font-size: 0; text-align: center;"> <a href="" class="img-wrap" style="color: #2d2d2d; text-decoration: none;"><div class="bg-options-wrap removethis"><div class="block-bg-image bg-control-item" title="Change image"><img src="https://dl.dropboxusercontent.com/u/18689296/India-Speak/india-speak-mailer/images/paper_document_file_page_pen_text-512.png" alt="IndiaSpeaks" title="IndiaSpeaks" width="209" height="209" vspace="0" style="border: 0 none;" data-bgedit="image" editable="" data-delete="" label="image" mc:edit="m59" data-size="400px x Any height|600px x Any height"></div><div class="block-image-link bg-control-item" title="Change image link"></div><div class="blockAction blockAction--delete js-blockActionDelete" title="Delete block"></div></div> </a> </td> </tr></tbody></table> </th> <td width="53%"><table class="m-w100" width="290" align="left" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt;"><tbody> <tr> <td width="324" class="h2 mce-content-body" id="mce_11" style="font-family: Open Sans, Arial, sans-serif; line-height: 0.9; font-size: 44px; color: #2d2d2d; font-weight: 300; text-align: center; " mc:edit="m56" data-color="1" data-ctag="singleline"><singleline>REWARD</td> </tr> <tr> <td height="10" style="padding: 0 0px; line-height:20px;">&nbsp;</td> </tr> </tbody> </table> </singleline></td> </tr><tr><td align="center" class="sale mce-content-body" id="mce_12" style="font-family: Open Sans, Arial, sans-serif; line-height: 1; font-size: 50px; font-weight: 800; text-align: center; color: #ff6000;" mc:edit="m56" data-color="2" data-ctag="singleline"><singleline>[[SurveyPoints]] REWARD POINTS </singleline></td> </tr><tr><td class="" height="25" style="font-size: 1px; line-height: 25px;">&nbsp;</td> </tr><tr><td> <table width="200" align="center" cellpadding="0" cellspacing="0" border="0" style="margin: 0 auto;" data-delete=""><tbody><tr><td height="1" class="" style="font-size: 1px; line-height: 0; background-color: #2d2d2d;">&nbsp;</td> </tr><tr><td height="2" class="" style="font-size: 1px; line-height: 0;">&nbsp;</td> </tr><tr><td style="padding: 0 20px;"> <table width="100%" align="center" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td height="1" class="" style="font-size: 1px; line-height: 0; background-color: #2d2d2d;">&nbsp;</td> </tr></tbody></table></td> </tr></tbody></table></td> </tr><tr><td class="" height="18" style="font-size: 1px; line-height: 18px;">&nbsp;</td> </tr> <tr> </tr></tbody></table> </td> </tr> </tbody></table></td> </tr> <tr> <td style="background-color: #ffffff;">&nbsp;</td> </tr> <tr> <td style=" background:#fff; font-family: Open Sans, Arial, sans-serif; line-height: 1.2; font-size: 14px; text-align: center; color: #2d2d2d; font-weight: 800; background-color:#fff" id="mce_14" data-ctag="singleline">HURRY, CLOSING ON THURSDAY</td> </tr> <tr> <td style="background-color: #ffffff;">&nbsp;</td> </tr> <tr> <td style="background-color: #ffffff;"><table width="400" border="0" align="center" cellpadding="0" cellspacing="0" class="btn" style="margin: 0 auto;" data-delete=""><tbody><tr><td style="border-radius: 5px; font-family: Open Sans, Arial, sans-serif; font-size: 13px; font-weight: 700; line-height: 1; padding: 15px 28px; text-align: center; background-color: #2d2d2d; color: #ffffff;" id="mce_15" data-ctag="singleline" data-clabel="button" class="mce-content-body"><a style="color: #ffffff; text-decoration: none;" href="[[SurveyUrl]]" data-mce-href="#" data-mce-style="color: #ffffff; text-decoration: none;"><singleline label="button">START SURVEY</singleline></a></td> </tr></tbody></table></td> </tr> <tr> <td style="background-color: #ffffff;"><p style="color: #2d2d2d; font-family: Open Sans, Arial, sans-serif; font-size: 18px; text-align:center; font-style:italic;">Or</p></td> </tr> <tr> <td style="background-color: #ffffff;"><table class="m-w100" width="100%" align="center" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt;"><tbody><tr><td align="center" class="text mce-content-body" id="mce_34" style="color: #2d2d2d; font-family: Open Sans, Arial, sans-serif; font-size: 13px; line-height: 24px; padding-left:35px; padding-right:35px;" mc:edit="m65" data-ctag="multiline"><multiline>YOU CAN ACCESS THE SURVEY BY CLICKING OR COPYING THE FOLLOWING URL INTO YOUR BROWSER:</multiline></td> </tr></tbody></table></td> </tr> <tr> <td style="background-color: #ffffff;">&nbsp;</td> </tr> <tr> <td style="background-color: #ffffff;"><table class="m-w100" width="400" align="center" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt;"><tbody> <tr><td align="center" class="text mce-content-body" id="mce_34" style="color: #2d2d2d; font-family: Open Sans, Arial, sans-serif; font-size: 18px; line-height: 24px;"><strong> <multiline><a style="color: #ec1c1c; text-decoration: none;" href="#" data-color="2" data-mce-href="#" data-mce-style="color: #ec1c1c; text-decoration: none;">[[SurveyUrl]]</a></multiline> </strong></td> </tr></tbody></table></td> </tr> <tr> <td style="background-color: #ffffff;">&nbsp;</td> </tr> <tr> <td style="background-color: #ffffff;">&nbsp;</td> </tr> <tr><td style="background-color: #ffffff;"> <table width="100%" align="center" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td valign="top"> <!-- image content --> <!-- end image content --> </td> </tr></tbody></table></td> </tr></tbody></table><!-- Large image - left, title with button - right --></repeater></div> <table class="wrapper" width="600" border="0" cellspacing="0" cellpadding="0" align="center" style="background: #ff6000;"> <!-- section-7 --> </table> <div class="layout-item" style="background:#ff6000;"><repeater><!-- Footer type 1 --><table width="600" align="center" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="color-bg" style="background-color: #ff6000"><table width="825px" border="0" align="left" cellpadding="0" cellspacing="0"> <tbody> <tr> <td class="break4"> <table width="150" cellspacing="0" cellpadding="0" border="0" align="center" class="center2"> <tbody> <tr> <td height="29">&nbsp;</td> </tr> <tr> <td style="font-family: Montserrat, sans-serif; font-size: 16px; color: rgb(255, 255, 255); text-transform: uppercase; line-height: 31px; font-weight: bold; text-align: center; outline: none; outline-offset: 1px; position: relative;" class="editable edit-text"> Survey ENDS On </td> </tr> <tr> <td style="font-family: Montserrat, sans-serif; font-size: 13px; color: rgb(255, 255, 255); line-height: 31px; text-align: center; outline: none; outline-offset: 1px; position: relative;" class="editable edit-text" data-selector="td.editable" contenteditable="false"> [[ClosingDate]]</td> </tr> <tr> <td height="30">&nbsp;</td> </tr> </tbody> </table></td> <td class="break4"> <table width="100%" cellspacing="0" cellpadding="0" border="0" align="left" class="center2"> <tbody> <tr> <td height="29">&nbsp;</td> </tr> <tr> <td style="font-family: Montserrat, sans-serif; font-size: 16px; color: #ffffff; text-transform: uppercase; line-height: 31px; font-weight: bold; text-align: center;" class="editable" data-selector="td.editable"> Research Sponsor</td> </tr> <tr> <td style="font-family: Montserrat, sans-serif; font-size: 13px; color: #ffffff; line-height: 31px; text-align: center;" class="editable" data-selector="td.editable">[[ResearchSponsor]]</td> </tr> <tr> <td height="30">&nbsp;</td> </tr> </tbody> </table></td> <td class="break4"> <table width="100%" cellspacing="0" cellpadding="0" border="0" align="left" class="center2"> <tbody> <tr> <td height="29">&nbsp;</td> </tr> <tr> <td style="font-family: Montserrat, sans-serif; font-size: 16px; color: rgb(255, 255, 255); text-transform: uppercase; line-height: 31px; font-weight: bold; text-align: center; outline: none; outline-offset: 1px; position: relative;" class="editable edit-text" data-selector="td.editable" contenteditable="false"> Length of Survey </td> </tr> <tr> <td style="font-family: Montserrat, sans-serif; font-size: 13px; color: rgb(255, 255, 255); line-height: 31px; text-align: center; outline: none; outline-offset: 1px; position: relative;" class="editable edit-text" data-selector="td.editable" contenteditable="false">[[SurveyLength]]</td> </tr> <tr> <td height="30">&nbsp;</td> </tr> </tbody> </table></td> </tr> </tbody> </table></td> </tr></tbody></table><!-- End Footer type 1 --></repeater></div><div class="layout-item"><repeater><!-- Header type 2 --></repeater><!-- End Header type 2 --></div><div class="layout-item"><!-- Header image with icon --><repeater></repeater><!-- End Header image with icon --></div><div class="layout-item"> <repeater><!-- 3 Product column --><!-- End 3 Product column --></repeater></div><div class="layout-item"> <repeater><!-- Grey --><!-- End Grey --></repeater></div><div class="layout-item"> <repeater><!-- Header type 3 --><!-- End Header type 3 --></repeater></div><div class="layout-item"> <repeater><!-- Main title with image --><!-- End Main title with image --></repeater></div><div class="layout-item"> <repeater><!-- Countdown timer --><!-- End Countdown timer --></repeater></div><div class="layout-item"> <repeater><!-- Text with button --><!-- End Text with button --></repeater></div><div class="layout-item"> <repeater><!-- Grey --><!-- End Grey --></repeater></div><div class="layout-item"> <repeater><!-- Header type 4 --><!-- End Header type 4 --></repeater></div><div class="layout-item"> <repeater><!-- Title block --><!-- End Title centered --></repeater></div><div class="layout-item"> <repeater><!-- Countdown timer black --><!-- End Countdown timer black --></repeater></div><div class="layout-item"><!-- Product - image right --><repeater><!-- Product - image right --></repeater></div><div class="layout-item"><!-- Product - image left --><repeater><table width="100%" align="center" cellpadding="0" cellspacing="0" border="0" style="background:rgb(249, 249, 249);"><tbody> <tr> <td style="background-color: #ffffff;"><table align="center" border="0" cellpadding="0" cellspacing="0" class="wrapper_table" style="width: 600px; max-width: 600px; background-color:;"> <tbody><tr> <td> <table cellpadding="0" cellspacing="0" border="0"> <tbody><tr> <td class="content"> <table cellpadding="0" cellspacing="0" border="0"> <tbody><tr> <td class="padding" style="width: 20px;"> </td> <td class="content_row" align="center" style="width: 600px;"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tbody><tr> <td width="370" height="483" class="one_half"> <table cellpadding="0" cellspacing="0" border="0" width="100%" class="mobile_centered_table"> <tbody> <tr> <td align="center" valign="top">&nbsp;</td> </tr> <tr> <td align="center" valign="top">&nbsp;</td> </tr> <tr> <td align="center" valign="top"><table cellpadding="0" cellspacing="0" border="0"> <tbody> <tr> <td align="center" valign="top" width="40"><table cellpadding="0" cellspacing="0" border="0"> <tbody> <tr> <td class="bg_primary" align="center" width="40" height="40" bgcolor="#ff6000" style="border-radius: 15px;"><img src="https://dl.dropboxusercontent.com/u/18689296/India-Speak/india-speak-mailer/images/what4.png" width="15" height="11" border="0" style="display: block;" alt="what we do"></td> </tr> </tbody> </table></td> <td align="center"><table cellpadding="0" cellspacing="0" border="0"> <tbody> <tr> <td width="20"></td> <td class="dark_heading" data-editable="" align="center" style="color:#505050; font-weight: 700; font-size: 16px; font-family: Montserrat, sans-serif; text-transform: uppercase; line-height: 22px; text-align:left;text-align:justify"><b> PAYMENT</b> </td> </tr> <tr> <td width="20"></td> <td class="dark_text" data-editable="" align="center" style="color:#828788; font-weight: 400; font-size: 13px; font-family: Lato, sans-serif; text-transform: none; line-height: 25px; text-align: left;text-align:justify"> The survey includes some screening questions to make sure your profile fits our clients needs for this particular study. If not, the questionnaire will simply end after these questions, and you will receive new survey opportunities soon. If you qualify and complete the entire survey , the survey incentive will be credited to your account at the end of survey. </td> </tr> </tbody> </table></td> </tr> <tr> <td class="section_h" height="30"></td> </tr> <tr> <td align="center" valign="top" width="40"><table cellpadding="0" cellspacing="0" border="0"> <tbody> <tr> <td class="bg_primary" align="center" width="40" height="40" bgcolor="#ff6000" style="border-radius: 15px;"><img src="https://dl.dropboxusercontent.com/u/18689296/India-Speak/india-speak-mailer/images/what3.png" width="14" height="12" border="0" style="display: block;" alt="what we do"></td> </tr> </tbody> </table></td> <td align="center"><table cellpadding="0" cellspacing="0" border="0"> <tbody> <tr> <td width="20"></td> <td class="dark_heading" data-editable="" align="center" style="color:#505050; font-weight: 700; font-size: 16px; font-family: Montserrat, sans-serif; text-transform: uppercase; line-height: 22px; text-align:left;text-align:justify"><b> TECHNICAL DIFFICULTIES</b> </td> </tr> <tr> <td width="20"></td> <td class="dark_text" data-editable="" align="center" style="color:#828788; font-weight: 400; font-size: 13px; font-family: Lato, sans-serif; text-transform: none; line-height: 25px; text-align: left;text-align:justify"> If you encounter any technical difficulties while completing this survey please click here for help or send an email to <a href="mailto:support@indiaspeaks.net" style="text-decoration:none;">support@indiaspeaks.net</a>. </td> </tr> </tbody> </table></td> </tr> </tbody> </table></td> </tr> <tr> <td align="center" valign="top">&nbsp;</td> </tr> <tr> <td align="center" valign="top">&nbsp;</td> </tr> <tr> <td height="177" align="center" valign="top"> <table cellpadding="0" cellspacing="0" border="0"> <tbody><tr> <td align="center" valign="top" width="40"> <table cellpadding="0" cellspacing="0" border="0"> <tbody><tr> <td class="bg_primary" align="center" width="40" height="40" bgcolor="#ff6000" style="border-radius: 15px;"> <img src="https://dl.dropboxusercontent.com/u/18689296/India-Speak/india-speak-mailer/images/what5.png" width="14" height="12" border="0" style="display: block;" alt="IndiaSpeaks" title="IndiaSpeaks"> </td> </tr> </tbody></table> </td> <td align="center"> <table cellpadding="0" cellspacing="0" border="0"> <tbody><tr> <td width="20"></td> <td class="dark_heading" data-editable="" align="center" style="color:#505050; font-weight: 700; font-size: 16px; font-family: Montserrat, sans-serif; text-transform: uppercase; line-height: 22px; text-align: left;text-align:justify"> <b>WHY DID I RECEIVE THIS E-MAIL? </b></td> </tr> <tr> <td width="20"></td> <td class="dark_text" data-editable="" align="center" style="color:#828788; font-weight: 400; font-size: 13px; font-family: Lato, sans-serif; text-transform: none; line-height: 25px; text-align: left;text-align:justify"> The survey includes some screening questions to make sure your profile fits our clients needs for this particular study. If not, the questionnaire will simply end after these questions, and you will receive new survey opportunities soon. If you qualify and complete the entire survey , the survey incentive will be credited to your account at the end of survey. </td> </tr> </tbody></table> </td> </tr> <tr> <td class="section_h" height="30"></td> </tr> </tbody></table></td> </tr> </tbody></table> </td> <td class="nomobile" width="20"></td> </tr> </tbody></table> </td> <td class="padding" style="width: 20px;"> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> </tbody></table></td> </tr> </tbody></table><!-- End Product - image right --></repeater></div><div class="layout-item"> <repeater><!-- Contacts --><!-- End Contacts --></repeater></div><div class="layout-item"> <repeater><!-- Grey --><!-- End Grey --></repeater></div><div class="layout-item"> <repeater><!-- Header type 5 --></repeater><!-- End Header type 5 --></div><div class="layout-item"> <repeater><!-- Image --><!-- End Image --></repeater></div><div class="layout-item"><!-- Product gallery --><repeater></repeater><!-- End Product gallery --></div><div class="layout-item"> <repeater><!-- Footer type 2 --><!-- End Footer type 2 --></repeater></div></div> </div></repeater></td> </tr><tr><td> <!-- Footer --> <table id="unsubscribe" class="footer" width="100%" align="center" cellpadding="0" cellspacing="0" border="0"><!-- Spacer --><tbody><tr><td class="" height="30" style="font-size: 1px; line-height: 0;">&nbsp;</td> </tr><!-- End Spacer --><tr><td class="va-top"> <!-- Copyright --> <table class="m-w100" align="left" width="250" cellspacing="0" cellpadding="0" border="0" style="border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt;"><tbody><tr><td class="text mce-content-body" mc:edit="m132" style="color: #505050; font-family: Open Sans, Arial, sans-serif; font-size: 13px; line-height: 24px;" id="mce_92" data-ctag="multiline">&nbsp;&nbsp;&nbsp;&nbsp;<multiline>Copyright � 2015 IndiaSpeaks</multiline></td> </tr></tbody></table><!-- Unsubscribe --><table class="m-w100" align="right" width="250" cellspacing="0" cellpadding="0" border="0" style="border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt;"><tbody><tr><td class="text mce-content-body" style="color: #505050; font-family: Open Sans, Arial, sans-serif; font-size: 13px; line-height: 24px; text-align: right;" mc:edit="m133" id="mce_93" data-ctag="singleline"><unsubscribe style="text-decoration: none; color: #505050;" data-mce-style="text-decoration: none; color: #505050;">unsubscribe</unsubscribe> | <a style="color: #505050; text-decoration: none;" href="http://www.indiaspeaks.net/" data-mce-href="#" data-mce-style="color:#505050; text-decoration: none;"><singleline> go to the website</singleline></a>&nbsp;&nbsp;&nbsp;&nbsp;</td> </tr></tbody></table></td> </tr><!-- Spacer --><tr><td class="" height="30" style="font-size: 1px; line-height: 0;">&nbsp;</td> </tr><!-- End Spacer --></tbody></table><!-- End Footer --></td> </tr></tbody></table></td> </tr></tbody></table> </div> </body></html>';
                $http.get('/public/views/app/admin/partials/surveyTemplate.html').then(function (response) {
                    $scope.vm.body = response.data;
                });

                $scope.vm.subject = 'A New Survey from Indiaspeaks.net';
                modalService.open($scope, '/public/views/app/admin/modals/createTemplate.html', 'lg');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.insertInSubject = function () {
                var textBox = document.getElementsByName("subject")[0];
                if (document.selection) {
                    textBox.focus();
                    var sel = document.selection.createRange();
                    sel.text = "[[" + $scope.vm.item + "]]";
                    return;
                } if (textBox.selectionStart || textBox.selectionStart == "0") {
                    var tStart = textBox.selectionStart;
                    var tEnd = textBox.selectionEnd;
                    var valStart = textBox.value.substring(0, tStart);
                    var valEnd = textBox.value.substring(tEnd, textBox.value.length);
                    textBox.value = valStart + "[[" + $scope.vm.item + "]]" + valEnd;
                } else {
                    textBox.value += "[[" + $scope.vm.item + "]]";
                }
                $scope.vm.subject = textBox.value;
                textBox.focus();
                $scope.vm.item = '';
            };
            $scope.createTemplate = function () {
                appService.createTemplate(surveyId, $scope.vm.name, $scope.vm.isActive, $scope.vm.body, $scope.vm.subject).then(function () {
                    appService.getTemplates(surveyId).then(function (result) {
                        $scope.vm.templates = result.data;
                    });
                    toastService.show("Template Created Successfully");
                    modalService.close();
                });
            };
            //view template for the survey
            $scope.viewTemplateDialog = function (template) {
                $scope.vm.body = template.body;
                $scope.vm.subject = template.subject;
                modalService.open($scope, '/public/views/app/admin/modals/viewTemplate.html','lg');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            //edit template for the survey
            $scope.editTemplateDialog = function (template) {
                appService.getEmailProperties().then(function (result) {
                    $scope.vm.items = result.values;
                });
                editTemplateId = template.id;
                $scope.vm.disableIsActive = template.isActive;
                $scope.vm.name = template.name;
                $scope.vm.isActive = template.isActive;
                $scope.vm.body = template.body;
                $scope.vm.subject = template.subject;
                modalService.open($scope, '/public/views/app/admin/modals/editTemplate.html', 'lg');

                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.editTemplate = function () {
                appService.editTemplate(surveyId, editTemplateId, $scope.vm.name, $scope.vm.isActive, $scope.vm.body, $scope.vm.subject).then(function () {
                    appService.getTemplates(surveyId).then(function (result) {
                        $scope.vm.templates = result.data;
                    });
                    toastService.show("Template updated successfully");
                    modalService.close();
                });
            };
            //get email schedules for the survey
            appService.getEmailSchedules(surveyId).then(function (result) {
                $scope.vm.emailSchedules = result.data;
            });
            //go to unique link details page for survey with unique URLs 
            $scope.goToUniqueLinksDetails = function () {
                appService.getUniqueLinks(surveyId).then(function (result) {
                    $scope.vm.uniqueLinks = result.data;
                });
                var url = $state.href('app.admin.linksForSurvey', { 'surveyId': $stateParams.surveyId });
                window.open(url, '_blank');
            };

            //get reports for survey
            $scope.getReports = function () {
//                appService.getUniqueReports(surveyId).then(function(result) {
//                    $scope.vm.uniqueReports = result.data;
//                });
                var url = $state.href('app.admin.reportsForSurvey', { 'surveyId': $stateParams.surveyId });
                window.open(url, '_blank');
            }

            //create email schedule for the survey
            $scope.createEmailScheduleDialog = function () {
                $scope.vm.emailSchedule = {};
                $scope.vm.emailSchedule.emailScheduleName = '';
                $scope.vm.emailSchedule.scheduleType = 0;
                modalService.open($scope, '/public/views/app/admin/modals/createEmailSchedule.html');
                //                $scope.vm.a = $scope.vm.survey.expiryDate;
                //                $scope.vm.b = new Date($scope.vm.a);
                //                                $scope.vm.b.setDate($scope.vm.b.getDate() - 1);
                $scope.vm.a = moment($scope.vm.survey.expiryDate).format("DD-MM-YYYY");

                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.createEmailSchedule = function () {
                $scope.vm.btnDisabled = true;
                if ($scope.vm.emailSchedule.isSendAll)
                    $scope.vm.emailSchedule.count = '';
                appService.createEmailSchedule(surveyId, $scope.vm.emailSchedule).then(function () {
                    appService.getEmailSchedules(surveyId).then(function (result) {
                        $scope.vm.emailSchedules = result.data;
                    });
                    toastService.show("Emails scheduled Successfully");
                    modalService.close();
                });
            };
            //create reminder email schedule for the survey
            $scope.createRemindEmailScheduleDialog = function (schedule) {
                $scope.vm.remindEmailSchedule = {};
                $scope.vm.remindEmailSchedule.emailScheduleName = '';
                $scope.vm.remindEmailSchedule.baseEmailScheduleId = schedule.id;
                $scope.vm.remindEmailSchedule.scheduleType = 1;
                modalService.open($scope, '/public/views/app/admin/modals/remindEmailSchedule.html');
                $scope.vm.b = moment($scope.vm.survey.expiryDate).format("DD-MM-YYYY");

                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.createRemindEmailSchedule = function () {
                if ($scope.vm.remindEmailSchedule.isSendAll)
                    $scope.vm.remindEmailSchedule.count = '';
                appService.createEmailSchedule(surveyId, $scope.vm.remindEmailSchedule).then(function () {
                    appService.getEmailSchedules(surveyId).then(function (result) {
                        $scope.vm.emailSchedules = result.data;
                    });
                    toastService.show("Emails scheduled Successfully");
                    modalService.close();
                });
            };
            //cancel email schedule
            $scope.cancelEmailScheduleDialog = function (emailScheduleId) {
                cancelEmailScheduleId = emailScheduleId;
                modalService.askConfirmation($scope, 'Are you sure you want to cancel this email schedule?', 'cancelEmailSchedule()');
            }

            //send email schedule
            $scope.sendScheduleNowDialog = function (emailScheduleId) {
                sendEmailScheduleId = emailScheduleId;
                modalService.askConfirmation($scope, 'Are you sure you want to send this schedule now?', 'sendEmailSchedule()');
            }
            $scope.sendEmailSchedule = function () {
                appService.sendEmailSchedule(surveyId, sendEmailScheduleId).then(function () {
                    appService.getEmailSchedules(surveyId).then(function (result) {
                        $scope.vm.emailSchedules = result.data;
                    });
                    toastService.show("Email schedule Sent Successfully");
                    modalService.close();
                });
            }


            $scope.cancelEmailSchedule = function () {
                appService.cancelEmailSchedule(surveyId, cancelEmailScheduleId).then(function () {
                    appService.getEmailSchedules(surveyId).then(function (result) {
                        $scope.vm.emailSchedules = result.data;
                    });
                    toastService.show("Email schedule cancelled Successfully");
                    modalService.close();
                });
            }
            //update email schedule
            $scope.updateEmailScheduleDialog = function (schedule) {
                $scope.vm.emailSchedule = schedule;
                modalService.open($scope, '/public/views/app/admin/modals/updateEmailSchedule.html');
                $scope.vm.c = moment($scope.vm.survey.expiryDate).format("DD-MM-YYYY");
                $scope.vm.d = moment($scope.vm.emailSchedule.scheduleDate).format("YYYY-MM-DD");
                $scope.vm.emailSchedule.emailScheduleName = schedule.emailScheduleName;
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.updateEmailSchedule = function () {
                if ($scope.vm.emailSchedule.isSendAll)
                    $scope.vm.emailSchedule.count = '';
                appService.updateEmailSchedule(surveyId, $scope.vm.emailSchedule, $scope.vm.d).then(function () {
                    appService.getEmailSchedules(surveyId).then(function (result) {
                        $scope.vm.emailSchedules = result.data;
                    });
                    toastService.show("Email Schedule updated Successfully");
                    modalService.close();
                });
            };
            //close survey
            $scope.closeSurveyDialog = function () {
                modalService.askConfirmation($scope, 'Are you sure you want to close this survey?', 'closeSurvey()');
            };
            $scope.closeSurvey = function () {
                appService.closeSurvey(surveyId).then(function () {
                    $state.go($state.current, {}, { reload: true });
                    toastService.show("Survey closed successfully");
                    modalService.close();
                });
            };
            //open survey
            $scope.openSurveyDialog = function () {
                modalService.askConfirmation($scope, 'Are you sure you want to open this survey?', 'openSurvey()');
            };
            $scope.openSurvey = function () {
                appService.openSurvey(surveyId).then(function () {
                    $state.go($state.current, {}, { reload: true });
                    toastService.show("Survey opened successfully");
                    modalService.close();
                });
            };

            //send emails for testing


//            $scope.sendEmailDialog = function (template) {
//                $scope.vm.template = template;
//                modalService.askConfirmation($scope, 'Are you sure you want to send this template ?', 'sendEmail()');
//            };
//            $scope.sendEmail = function () {
//                appService.sendEmail(surveyId, $scope.vm.template.id).then(function () {
//                    modalService.close();
//                    toastService.show("Template sent successfully");
//                });
//            };

            $scope.sendEmailDialog = function(template) {
                $scope.vm.template = template;
                $scope.vm.k = '';
                modalService.open($scope, '/public/views/app/admin/modals/createTestEmail.html');

                $scope.closeForm = function () {
                    modalService.close();
                }
            };

            $scope.createTestTemplate = function () {
                appService.createTestTemplate(surveyId,$scope.vm.template.id,$scope.vm.k).then(function () {
                    modalService.close();
                    toastService.show("Template sent successfully.");
                  }, function (error) {
                    toastService.showError(error.data.message);
                });
            };

            //get initial attempts
            appService.getAttempts($scope.vm.page, $scope.vm.count, surveyId, $scope.vm.f).then(function (result) {
                $scope.vm.attempts = result;
            });

          
            //get filtered attempts
            $scope.getAttempts = function () {
                appService.getAttempts($scope.vm.page, $scope.vm.count, surveyId, $scope.vm.f).then(function (result) {
                    $scope.vm.attempts = result;
                    //$scope.vm.a = [];
                    //$scope.vm.b = [];

                    //$scope.vm.a = $scope.vm.attempts.data;
                    //for (var i = 0; i < $scope.vm.a.length; i++) {
                    //    if ($scope.vm.a[i].attemptStatus != "Outlier") {
                    //        $scope.vm.b.push($scope.vm.a[i]);
                    //       $scope.vm.c++;
                    //    }
                    //}
                    //if (($scope.vm.c) % 10 == 0) {
                    //    $scope.vm.newCount = Math.floor($scope.vm.c / 10);
                    //}
                    //else if (($scope.vm.c) % 10 != 0) {
                    //    $scope.vm.newCount = (Math.floor($scope.vm.c / 10)) + 1;


                    //}
                });
            };


            //get attempts status
            appService.getAttemptStatus(surveyId).then(function (result) {
                $scope.vm.attemptStatus = result;
                $scope.vm.f = $scope.vm.attemptStatus;
            });

            $scope.pageChanged = function () {
                appService.getAttempts($scope.vm.page, $scope.vm.count, surveyId, $scope.vm.f).then(function (result) {
                    $scope.vm.attempts = result;
                });
            };
            // get survey attempt statuses
            appService.getSurveyAttemptStatuses().then(function (result) {
                $scope.vm.surveyAttemptStatuses = result.values;
                });

            //change attempt status
            $scope.changeAttemptStatus = function () {
                $scope.vm.user = '';
                $scope.vm.selectedItem = 'closedSurvey';
                modalService.open($scope, '/public/views/app/admin/modals/changeStatus.html');

//                $scope.closeForm = function () {
//                    modalService.close();
//                }
            };

            $scope.changeSurveyAttemptStatus = function() {
                modalService.askConfirmation($scope, 'Are you sure you want to change the Attempt Status for these attempts?', 'changeStatus()');
            };
            $scope.changeStatus = function () {
            appService.changeAttemptStatus(surveyId, $scope.vm.selectedItem, $scope.vm.user).then(function (result) {
                $modalStack.dismissAll();
                    toastService.show("Survey Attempt Status changed successfully.");
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };

            //close attempt status dialog box
            $scope.closeAttemptStatus = function() {
                $modalStack.dismissAll();
            };

            //  delete survey allocation entry
            $scope.deleteSurveyAllocationDialog = function (index) {
                indexToBeDeleted = index;
                modalService.askConfirmation($scope, 'Are you sure you want to delete this survey allocation', 'deleteSurveyAllocation()');
            };

            $scope.deleteSurveyAllocation = function () {
                appService.deleteSurveyAllocation($scope.vm.attempts.data[indexToBeDeleted].id).then(function () {
                    toastService.show("Survey Allocation Entry deleted successfully.");
                    $window.location.reload();

                }, function (error) {
                    toastService.showError(error.data.message);
                });
                modalService.close();
            };

        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminRewardDetailsCtrl', [
        '$scope', '$state', 'toastService', 'appService', '$stateParams',
        function($scope, $state, toastService, appService, $stateParams) {
            $scope.vm = {};
            appService.getReward($stateParams.rewardId).then(function(result) {
                $scope.vm.reward = result;
            });
        }
    ]);;
angular.module('app')
    .controller('adminSweepstakeDetailsCtrl', [
        '$scope', '$state', 'toastService', 'appService', '$stateParams',
        function ($scope, $state, toastService, appService, $stateParams) {
            $scope.vm = {};
            appService.getSweepstake($stateParams.sweepstakeId).then(function (result) {
                $scope.vm.sweepstake = result;
            });

            //export sweepstake details
            $scope.exportSweepstakeDetails = function () {
                appService.exportSweepstakeDetails($stateParams.sweepstakeId).then(function (data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Sweepstake details.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                });
            }
        }
    ]);
;
'use strict';

angular.module('app')
    .controller('adminReferralDetailsCtrl', [
        '$scope', '$state', 'toastService', 'appService', '$stateParams',
        function($scope, $state, toastService, appService, $stateParams) {
            $scope.vm = {};
            appService.getReferral($stateParams.referralId).then(function(result) {
                $scope.vm.referral = result;
            });
            $scope.cancelReferral = function() {
                appService.cancelReferral($scope.vm.referral.id).then(function() {
                    appService.getReferral($stateParams.referralId).then(function(result) {
                        $scope.vm.referral = result;
                    });
                });
            };
            $scope.approveReferral = function() {
                appService.approveReferral($scope.vm.referral.id).then(function() {
                    appService.getReferral($stateParams.referralId).then(function(result) {
                        $scope.vm.referral = result;
                    });
                });
            };
        }
    ]);;
angular.module('app')
    .controller('adminPanelistDetailsCtrl', [
        '$scope', '$state', 'toastService', 'appService', '$stateParams', 'userService', 'modalService','$window',
        function ($scope, $state, toastService, appService, $stateParams, userService, modalService, $window) {
            $scope.vm = {};
            $scope.vm.surveys = [];
            $scope.vm.rewards = [];
            $scope.vm.referrals = [];
            $scope.vm.secs = [];
            $scope.vm.redemptions = [];
            $scope.vm.basicProfileDetails = [];
            $scope.vm.rewardDetails = [];
            $scope.vm.surveyDetails = [];
            $scope.vm.surveyPage = 1;
            $scope.vm.rewardPage = 1;
            $scope.vm.referralPage = 1;
//            $scope.vm.secPage = 1;
            $scope.vm.redemptionPage = 1;
            $scope.vm.count = 10;
            $scope.vm.panelistLabels = [];
            var currentPassword = '';
            var panelistId = $stateParams.panelistId;
            //get user image
            appService.getUserPic(panelistId).then(function (result) {
                $scope.vm.userPic = result.url;
            });
            //get user info
            userService.getUserInfo(panelistId).then(function (result) {
                $scope.vm.user = result;
                $scope.vm.userInfo = result.basicProfile;
            });
            //get all labels
            appService.getLabels(1, -1).then(function (result) {
                $scope.vm.labels = result.data;
            });
            //get labels assigned to panelist
            appService.getLabels(1, -1, panelistId).then(function (result) {
                angular.forEach(result.data, function (value) {
                    $scope.vm.panelistLabels.push(JSON.stringify(value));
                });
            });
            //assign labels
            $scope.assignLabels = function () {
                var labelIds = [];
                if (!$scope.vm.panelistLabels.length)
                    toastService.show('No labels are chosen to assign');
                else {
                    angular.forEach($scope.vm.panelistLabels, function (value) {
                        labelIds.push(JSON.parse(value).id);
                    });
                    appService.assignLabels(labelIds, panelistId).then(function () {
                        toastService.show("Labels successfully assigned to panelist");
                    });
                }
            };
            //get all surveys
            appService.getSurveys($scope.vm.surveyPage, $scope.vm.count, panelistId).then(function (result) {
                $scope.vm.surveys = result;
                $scope.vm.totalSurveys = result.totalCount;
            });
            $scope.surveyPageChanged = function () {
                appService.getSurveys($scope.vm.surveyPage, $scope.vm.count, panelistId).then(function (result) {
                    $scope.vm.surveys = result;
                });
            };
            //download basic profile details
            $scope.downloadBasicProfileDetails = function () {
                appService.downloadBasicProfileDetails(panelistId).then(function (data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Panelist profiles.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    toastService.show("Panelist profiles exported successfully");
                });
            };

            //download reward details
            $scope.downloadRewardDetails = function () {
                appService.downloadRewardDetails(panelistId).then(function (data) {

                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Panelist rewards.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    toastService.show("Panelist reward details exported successfully");
                });
            };

            //download survey details
            $scope.downloadSurveyDetails = function () {
                appService.downloadSurveyDetails(panelistId).then(function (data) {

                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Panelist surveys.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    toastService.show("Panelist survey details exported successfully");
                });
            };

            //get surveys status
            appService.getSurveysStatus(panelistId).then(function (result) {
                $scope.vm.notStartedSurveys = result.notStarted;
                $scope.vm.incompleteSurveys = result.incomplete;
                $scope.vm.completeSurveys = result.complete;
              
            });
            //get all rewards
            appService.getRewards($scope.vm.rewardPage, $scope.vm.count, panelistId).then(function (result) {
                $scope.vm.rewards = result;
            });
            $scope.rewardPageChanged = function () {
                appService.getRewards($scope.vm.rewardPage, $scope.vm.count, panelistId).then(function (result) {
                    $scope.vm.rewards = result;
                });
            };
            //get all secs
            appService.getUserSecs(panelistId).then(function(result) {
                $scope.vm.secs = result;
                $scope.vm.a = $scope.vm.secs.name;
            });
//            $scope.secPageChanged = function() {
//                appService.getUserSecs($scope.vm.secPage, $scope.vm.count, panelistId).then(function (result) {
//                    $scope.vm.secs = result;
//                });
//            };
            //get rewards points status
            appService.getRewardsPointsStatus(panelistId).then(function (result) {
                $scope.vm.surveyPoints = result.survey;
                $scope.vm.referralPoints = result.referral;
                $scope.vm.legacyPoints = result.legacy;
                $scope.vm.sweepstakePoints = result.sweepstake;
            });
            //get all redemptions
            appService.getRedemptions($scope.vm.redemptionPage, $scope.vm.count, panelistId).then(function (result) {
                $scope.vm.redemptions = result;
            });
            $scope.redemptionPageChanged = function () {
                appService.getRedemptions($scope.vm.redemptionPage, $scope.vm.count).then(function (result) {
                    $scope.vm.redemptions = result;
                });
            };
            //get total points
            appService.getTotalPoints(panelistId).then(function (result) {
                $scope.vm.totalPoints = result.points;
            });
            //get redeemed points status
            appService.getRedemptionPointsStatus(panelistId).then(function (result) {
                $scope.vm.redeemedPoints = result.completed;
                $scope.vm.inProgressPoints = result.inProgress + result.new;
                $scope.vm.totalRedeemedPoints = result.completed + result.inProgress + result.new;
            });
            //get all referrals
            appService.getReferrals($scope.vm.referralPage, $scope.vm.count, panelistId).then(function (result) {
                $scope.vm.referrals = result;
            });
            $scope.referralPageChanged = function () {
                appService.getReferrals($scope.vm.referralPage, $scope.vm.count, panelistId).then(function (result) {
                    $scope.vm.referrals = result;
                });
            };
            //get referrals status
            appService.getReferralsStatus(panelistId).then(function (result) {
                $scope.vm.totalReferralsSent = result.pending + result.invited + result.accepted + result.pendingApproval + result.approved;
                $scope.vm.totalReferralsAccepted = result.approved;
            });
            //change password
            $scope.changePasswordDialog = function () {
                $scope.vm.newPassword = '';
                $scope.vm.confirmPassword = '';
                modalService.open($scope, '/public/views/app/admin/modals/panelistChangePassword.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.changePassword = function () {
                appService.changePassword(currentPassword, $scope.vm.newPassword, $scope.vm.confirmPassword, panelistId).then(function () {
                    toastService.show("Password changed successfully");
                    modalService.close();
                });
            };
            //revert delete account
            $scope.confirmRevertDelete = function() {
                modalService.askConfirmation($scope, 'Are you sure you want to undelete this account ?', 'revertDeleteAccount()');
            };
            $scope.revertDeleteAccount = function() {
                appService.revertDeleteAccount(panelistId).then(function() {
                    modalService.close();
                    toastService.show('Panelist account undeleted successfully');
                    $window.location.reload();
                }, function(err) {
                    toastService.showError(err.data.error_description);
                });
            };
            //delete account
            $scope.confirmDeleteAccount = function (deletion) {
                if (deletion == 'temporary')
                    modalService.open($scope, '/public/views/app/admin/modals/panelistDeleteAccount.html');
                else
                    modalService.open($scope, '/public/views/app/admin/modals/panelistPermanentDeleteAccount.html');
            };
            $scope.deleteAccount = function () {
                appService.deleteAccount(panelistId).then(function () {
                    modalService.close();
                    toastService.show('Panelist Deleted Successfully');
                    $window.location.reload();
//                    $scope.vm.isDeleted = function () {
//                        if ($scope.vm.user.deleteConfirmDate !== null) {
//                            $scope.vm.a = true;
//                        }
//                    }
//                    $state.go('app.admin.panelistDashboard');
                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };
            $scope.permanentDeleteAccount = function () {
                appService.permanentDeleteAccount(panelistId).then(function () {
                    modalService.close();
                    toastService.show('Panelist Permanently Deleted Successfully');
                    $window.location.reload();
//                  $scope.vm.isDeleted=function() {
//                      if ($scope.vm.user.deleteConfirmDate === null) {
//                          $scope.vm.a = true;
//                      }
//                  }
                    //                    $state.go('app.admin.panelistDashboard');

                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };
            $scope.closeDialog = function () {
                modalService.close();
            };
            //subscribe panelist
            $scope.confirmSubscribePanelist = function () {
                modalService.open($scope, '/public/views/app/admin/modals/panelistSubscription.html');
            }
            $scope.subscribePanelist = function () {
                appService.subscribe(panelistId).then(function () {
                    modalService.close();
                    $scope.vm.user.isUnsubscribed = false;
                    toastService.show("Panelist subscribed successfully");
                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };
            //unsubscribe panelist
            $scope.confirmUnsubscribePanelist = function () {
                modalService.open($scope, '/public/views/app/admin/modals/panelistUnsubscription.html');
            }
            $scope.unsubscribePanelist = function () {
                appService.unsubscribe(panelistId).then(function () {
                    modalService.close();
                    $scope.vm.user.isUnsubscribed = true;
                    toastService.show("Panelist unsubscribed successfully");
                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };
            //edit panelist account details
            $scope.editPanelistAccount = function () {
                $state.go('app.admin.panelist.editPanelistAccount', { panelistId: panelistId });
            }
            //resend verification email
            $scope.emailVerification = function () {
                userService.verifyEmail($scope.vm.user.email).then(function () {
                    toastService.show("Verification email sent successfully.");
                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };
        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminEditPanelistAccountCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', '$stateParams',
        function ($scope, userService, $state, toastService, localStorageService, appService, $stateParams) {
            var panelistId = $stateParams.panelistId;
            $scope.referralSources = {};
            userService.getReferralSources().then(function (result) {
                $scope.referralSources = result.values;
            });

            $scope.vm = {};
            //get all countries
            appService.getCountries().then(function (result) {
                $scope.countries = result.data;
            });
            //get states for country
            $scope.getStates = function () {
                $scope.states = [];
                appService.getStates($scope.vm.country).then(function (result) {
                    $scope.states = result.states;
                });
                if ($scope.vm.country === $scope.vm.countryObj.id) {
                    $scope.vm.state = $scope.vm.stateObj.id;
                    $scope.vm.city = $scope.vm.cityObj.id;
                }
                else {
                    $scope.vm.state = '';
                    $scope.vm.city = '';
                }
            };
            //get cities
            $scope.getCities = function () {
                $scope.cities = [];
                appService.getCities($scope.vm.country, $scope.vm.state).then(function (result) {
                    $scope.cities = result.cities;
                });
                if ($scope.vm.country === $scope.vm.countryObj.id && $scope.vm.state === $scope.vm.stateObj.id)
                    $scope.vm.city = $scope.vm.cityObj.id;
                else
                    $scope.vm.city = '';
            };
            userService.getUserInfo(panelistId).then(function (result) {
                $scope.vm = result.basicProfile;
                $scope.vm.dateFilled = moment($scope.vm.dateOfBirth).format("YYYY-MM-DD");
                //                $scope.vm.b = moment().format("YYYY-MM-DD");
                $scope.vm.allowedDate = moment().subtract(15, 'years').format('YYYY-MM-DD');
                $scope.vm.legacyError = result.legacyError;
                $scope.getStates();
                $scope.getCities();
                $scope.vm.phoneVerified = localStorageService.get('phoneVerified');
            });
            $scope.updateAccount = function () {
                if ($scope.vm.dateFilled > $scope.vm.allowedDate)
                    toastService.showError('The age you have entered for the panelist is less than 15. Please try again');
                else {
                    appService.updatePanelistAccount(panelistId, $scope.vm, $scope.vm.dateFilled).then(function() {
                        toastService.show('Successfully updated Profile');
                        $state.go('app.admin.panelist.panelistDetails');

                    });
                }
            }
        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminRedemptionRequestDetailsCtrl', [
        '$scope', '$state', 'toastService', 'appService', '$stateParams', 'modalService',
        function ($scope, $state, toastService, appService, $stateParams, modalService) {
            $scope.vm = {};
            $scope.vm.approvedPoints = 0;
            $scope.vm.notes = '';
            appService.getRedemptionRequest($stateParams.redemptionRequestId).then(function (result) {
                $scope.vm.redemptionRequest = result;
            });
            $scope.approveRedemptionRequestDialog = function () {
                $scope.vm.approvedPoints = $scope.vm.redemptionRequest.pointsRequested;
                $scope.vm.notes = '';
                modalService.open($scope, '/public/views/app/admin/modals/approveRedemptionRequest.html');
            }
            $scope.approveRedemptionRequest = function () {
                appService.approveRedemptionRequest($scope.vm.redemptionRequest.id, $scope.vm.approvedPoints, $scope.vm.notes).then(function () {
                    appService.getRedemptionRequest($stateParams.redemptionRequestId).then(function (result) {
                        $scope.vm.redemptionRequest = result;
                        toastService.show("Redemption Request approved sucessfully");
                    }, function (error) {
                        toastService.showError(error.data.message);
                    });
                    modalService.close();
                });
            };
            $scope.cancelRedemptionRequestDialog = function () {
                $scope.vm.notes = '';
                modalService.open($scope, '/public/views/app/admin/modals/cancelRedemptionRequest.html');
            }
            $scope.cancelRedemptionRequest = function () {
                appService.cancelRedemptionRequest($scope.vm.redemptionRequest.id, $scope.vm.notes).then(function () {
                    appService.getRedemptionRequest($stateParams.redemptionRequestId).then(function (result) {
                        $scope.vm.redemptionRequest = result;
                        toastService.show("Redemption Request cancelled successfully");
                    }, function (error) {
                        toastService.showError(error.data.message);
                    });
                    modalService.close();
                });
            };
        }
    ]);;
angular.module('app')
    .controller('adminSurveyDashboardCtrl', [
        '$scope', 'userService', 'localStorageService', '$state', '$stateParams', 'authService', 'appService','toastService',
        function($scope, userService, localStorageService, $state,authService, $stateParams, appService, toastService) {
            $scope.vm = {};
            $scope.vm.surveys = [];
            $scope.vm.surveyTypes = null;
            $scope.vm.dateRangeList = ["Last 30 days", "Last 60 days", "Last 90 days", "Last Year"];
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.vm.surveyName = '';
            $scope.vm.clientName = '';
            $scope.vm.surveyType = null;
            $scope.vm.dateRange = "Last 30 days";
            $scope.vm.getSurveyDataForAdmin = 'starting';
            //var panelistId = $stateParams.panelistId;
            //  userService.getUserInfo(panelistId).then(function(result) {
            //      $scope.vm.panelist = result;
            //  });
            $scope.vm.publishDate = {
                startDate:  moment().subtract(1,'month'),
                endDate:  moment()
            };
            $scope.vm.expiryDate = {
                startDate: moment().subtract(6, 'months'),
                endDate: moment().add(6, 'months')
            };
            $scope.publishDateRange = function() {
                switch ($scope.vm.dateRange) {
                case $scope.vm.dateRangeList[0]:
                    $scope.vm.publishDate = {
                        startDate: moment().subtract(1, 'month'),
                        endDate: moment()
                    };
                    break;
                case $scope.vm.dateRangeList[1]:
                    $scope.vm.publishDate = {
                        startDate: moment().subtract(2, 'months'),
                        endDate: moment()
                    };
                    break;
                case $scope.vm.dateRangeList[2]:
                    $scope.vm.publishDate = {
                        startDate: moment().subtract(3, 'months'),
                        endDate: moment()
                    };
                    break;
                case $scope.vm.dateRangeList[3]:
                    $scope.vm.publishDate = {
                        startDate: moment().subtract(1, 'year'),
                        endDate: moment()
                    };
                    break;
                default:
                    $scope.vm.publishDate = {
                        startDate: moment().subtract(1, 'month'),
                        endDate: moment()
                    };
                }
            }

            $scope.action = function(event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterSurveys();
                }
            };

            //get initial surveys
            appService.filterSurveys($scope.vm.page, $scope.vm.count, $scope.vm.publishDate, $scope.vm.expiryDate,
                $scope.vm.surveyName, $scope.vm.clientName, $scope.vm.surveyType).then(function(result) {
                $scope.vm.surveys = result;
                if ($scope.vm.surveys.data.length === 0)
                    $scope.vm.getSurveyDataForAdmin = 'noData';
//              for (var i = 0; i < $scope.vm.surveys.data.length; i++) {
//                  if ($scope.vm.surveys.data[i].publishDate != null && $scope.vm.surveys.data[i].expiryDate != null) {
//                      $scope.vm.a = new Date($scope.vm.surveys.data[i].publishDate);
//                      $scope.vm.b = new Date($scope.vm.surveys.data[i].expiryDate);
//                      $scope.vm.a.setHours($scope.vm.a.getHours() + 5);
//                      $scope.vm.b.setHours($scope.vm.b.getHours() + 5);
//                      $scope.vm.a.setMinutes($scope.vm.a.getMinutes() + 30);
//                      $scope.vm.b.setMinutes($scope.vm.b.getMinutes() + 30);
//                      $scope.vm.surveys.data[i].publishDate = $scope.vm.a;
//                      $scope.vm.surveys.data[i].expiryDate = $scope.vm.b;
//                      }
//              }

            }, function(error) {
                $scope.vm.getSurveyDataForAdmin = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
                });

            //export surveys
            $scope.exportSurveys = function() {
                appService.exportSurveys($scope.vm.page, $scope.vm.count, $scope.vm.publishDate, $scope.vm.expiryDate,
                    $scope.vm.surveyName, $scope.vm.clientName, $scope.vm.surveyType).then(function(data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Surveys.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                });
            };

            //get survey names
            appService.getSurveyNames().then(function(result) {
                $scope.vm.surveyNames = result.names;
            });
            //get client names
            appService.getClientNames().then(function(result) {
                $scope.vm.clientNames = result;
            });
            //get survey types
            appService.getSurveyTypes().then(function(result) {
                $scope.vm.surveyTypes = result.values;
            });
            $scope.pageChanged = function() {
                
                    appService.filterSurveys($scope.vm.page, $scope.vm.count, $scope.vm.publishDate, $scope.vm.expiryDate,
                        $scope.vm.surveyName, $scope.vm.clientName, $scope.vm.surveyType).then(function(result) {
                        $scope.vm.surveys = result;
                    });
                }
            

            //filter surveys

                $scope.filterSurveys = function() {
                    appService.filterSurveys($scope.vm.page, $scope.vm.count, $scope.vm.publishDate, $scope.vm.expiryDate,
                    $scope.vm.surveyName, $scope.vm.clientName, $scope.vm.surveyType).then(function(result) {
                    $scope.vm.surveys = result;
                });
            };
        
            //clear filter
            $scope.clearFilters = function() {
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                $scope.vm.surveyName = '';
                $scope.vm.clientName = '';
                $scope.vm.surveyType = null;
                $scope.vm.dateRange = "Last 30 days";
                $scope.vm.publishDate = {
                    startDate: moment().subtract(1, 'month'),
                    endDate: moment()
                };
                $scope.vm.expiryDate = {
                    startDate: moment().subtract(6, 'months'),
                    endDate: moment().add(6, 'months')
                };
                appService.filterSurveys($scope.vm.page, $scope.vm.count, $scope.vm.publishDate, $scope.vm.expiryDate,
                    $scope.vm.surveyName, $scope.vm.clientName, $scope.vm.surveyType).then(function(result) {
                    $scope.vm.surveys = result;
                });
            };
        }
    ]);

;
angular.module('app')
    .controller('adminRedemptionDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService', 'userService',
        function ($scope, localStorageService, $state, appService, modalService, toastService, userService) {
            $scope.vm = {};
            $scope.vm.redemptions = null;
            $scope.vm.redemptionModes = [];
            $scope.vm.requestStatuses = null;
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.vm.requestStatus = '';
            $scope.vm.redemptionMode = [];
            $scope.vm.approveRedemptionsClicked = false;
            $scope.vm.email = '';
            $scope.vm.requestDate = {
                startDate: moment().subtract(1, 'months'),
                endDate: moment()
            };

            $scope.vm.getRequestDataForAdmin = 'starting';

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterRedemptions();
                }
            };
            //get redemption modes
            appService.getRedemptionModes().then(function (result) {
                $scope.vm.redemptionModes = result.values;
            });
            //get redemption request status
            appService.getRedemptionRequestStatuses().then(function (result) {
                $scope.vm.requestStatuses = result.values;
                $scope.vm.requestStatus = 'new';
                //get initial redemptions
                appService.filterRedemptions($scope.vm.page, $scope.vm.count, $scope.vm.requestDate,
                    $scope.vm.redemptionMode, $scope.vm.requestStatus, $scope.vm.email).then(function (response) {
                        $scope.vm.redemptions = response;
                    if ($scope.vm.redemptions.data.length === 0)
                        $scope.vm.getRequestDataForAdmin = 'noData';
                }, function(error) {
                    $scope.vm.getRequestDataForAdmin = 'requestFailed';
                    toastService.showError("There was some error while loading data. Please refresh the page again");
                });
            });
            //export Redemption requests
            $scope.exportRedemptions = function () {
                appService.exportRedemptions($scope.vm.page, $scope.vm.count, $scope.vm.requestDate,
                    $scope.vm.redemptionMode, $scope.vm.requestStatus, $scope.vm.email).then(function (data) {
                        var file = new Blob([data], {
                            type: 'application/csv'
                        });
                        var fileUrl = URL.createObjectURL(file);
                        var a = document.createElement('a');
                        a.href = fileUrl;
                        a.target = '_blank';
                        a.download = "RedemptionRequests.csv";
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        toastService.show("Redemption Requests exported successfully");
                    }, function (err) {
                        toastService.showError(err.data.error_description);
                    });
            };
            $scope.pageChanged = function() {
                appService.filterRedemptions($scope.vm.page, $scope.vm.count, $scope.vm.requestDate,
                         $scope.vm.redemptionMode, $scope.vm.requestStatus, $scope.vm.email).then(function (response) {
                             $scope.vm.redemptions = response;
                         });
                }
            //filter redemption requests
            $scope.filterRedemptions = function () {
                appService.filterRedemptions($scope.vm.page, $scope.vm.count, $scope.vm.requestDate,
                     $scope.vm.redemptionMode, $scope.vm.requestStatus, $scope.vm.email).then(function (response) {
                         $scope.vm.redemptions = response;
                     });
            };
            //clear filter
            $scope.clearFilters = function () {
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                $scope.vm.requestStatus = '';
                $scope.vm.redemptionMode = [];
                $scope.vm.email = '';
                $scope.vm.requestDate = {
                    startDate: moment().subtract(6, 'months'),
                    endDate: moment()
                };
                appService.filterRedemptions($scope.vm.page, $scope.vm.count, $scope.vm.requestDate, $scope.vm.redemptionMode, $scope.vm.requestStatus, $scope.vm.email).then(function (result) {
                    $scope.vm.redemptions = result;
                });
            };
            $scope.approveRedemptions = function () {
                var file = document.getElementById("approveRedemptionsFileId").files[0];
                if (angular.isDefined(file)) {
                    appService.uploadRedemptionApprovals(file).then(function () {
                        toastService.show("Approvals Uploaded Successfully");
                        $scope.vm.approveRedemptionsClicked = false;
                        $scope.clearFilters();
                    }, function (err) {
                        toastService.showError(err.data.error_description);
                    });
                } else {
                    toastService.showError("Please choose a file to upload");
                }
            };
        }
    ]);;
angular.module('app')
    .controller('adminRedemptionModeDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService', 'userService',
        function ($scope, localStorageService, $state, appService, modalService, toastService, userService) {
            $scope.vm = {};
            $scope.vm.redemptionModes = [];
            $scope.vm.name = '';
            $scope.vm.minimumPoints = 0;
            $scope.vm.useName = false;
            $scope.vm.useAddress = false;
            $scope.vm.usePhone = false;
            $scope.vm.description = '';
            var redemptionModeId = '';
            $scope.vm.getRedemptionModeData = 'starting';
            //get redemption modes
            appService.getRedemptionModes().then(function (result) {
                $scope.vm.redemptionModes = result.values;
                if ($scope.vm.redemptionModes.length === 0)
                    $scope.vm.getRedemptionModeData = 'noData';
            }, function(error) {
                $scope.vm.getRedemptionModeData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //create redemption mode
            $scope.createRedemptionModeDialog = function () {
                $scope.vm.name = '';
                $scope.vm.minimumPoints = 0;
                $scope.vm.useName = false;
                $scope.vm.useAddress = false;
                $scope.vm.usePhone = false;
                $scope.vm.description = '';
                modalService.open($scope, '/public/views/app/admin/modals/createRedemptionMode.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
          $scope.createRedemptionMode = function () {
                appService.createRedemptionMode($scope.vm.name, $scope.vm.minimumPoints, $scope.vm.description,
                    $scope.vm.useName, $scope.vm.useAddress, $scope.vm.usePhone).then(function () {
                        modalService.close();
                        appService.getRedemptionModes().then(function (result) {
                            $scope.vm.redemptionModes = result.values;
                            toastService.show("Redemption mode created successfully");
                        }, function (error) {
                            toastService.showError(error.data.message);
                        });
                    });
          };
            //edit redemption mode
            $scope.editRedemptionModeDialog = function (index) {
                redemptionModeId = $scope.vm.redemptionModes[index].id;
                $scope.vm.name = $scope.vm.redemptionModes[index].name;
                $scope.vm.minimumPoints = $scope.vm.redemptionModes[index].minimumPoints;
                $scope.vm.useName = $scope.vm.redemptionModes[index].useName;
                $scope.vm.useAddress = $scope.vm.redemptionModes[index].useAddress;
                $scope.vm.usePhone = $scope.vm.redemptionModes[index].usePhone;
                $scope.vm.description = $scope.vm.redemptionModes[index].description;
                modalService.open($scope, '/public/views/app/admin/modals/editRedemptionMode.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.editRedemptionMode = function () {
                appService.editRedemptionMode(redemptionModeId, $scope.vm.name, $scope.vm.minimumPoints, $scope.vm.description,
                    $scope.vm.useName, $scope.vm.useAddress, $scope.vm.usePhone).then(function () {
                        modalService.close();
                        appService.getRedemptionModes().then(function (result) {
                            $scope.vm.redemptionModes = result.values;
                            toastService.show("Redemption Mode updated successfully");
                        }, function (error) {
                            toastService.showError(error.data.message);
                        });
                    });
            }
         }
    ]);;
angular.module('app')
    .service('reportService', function() {
        })
    .controller('adminSurveyEmailReportDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService',
        function ($scope, localStorageService, $state, appService) {
            $scope.vm = {};
            $scope.vm.surveyEmailReports = {};
            $scope.vm.showSurveyEmailReportsData = 0;
            //get survey email reports
            appService.getSurveyEmailReports().then(function (result) {
                $scope.vm.surveyEmailReports = result;
                $scope.vm.showSurveyEmailReportsData = 1;
            });

            //refresh survey email report data

            $scope.refreshSurveyEmailReportCount = function () {
                appService.getSurveyEmailReports().then(function (result) {
                    $scope.vm.surveyEmailReports = result;
                });
                $scope.vm.currentDate = moment().format('YYYY-MM-DD hh:mm:ss a');
            };
                
          $scope.getSurveyById = function (surveyId) {
                return $scope.vm.surveyEmailReports.allSurveys[surveyId];
          };

            $scope.getSurveyDate = function(surveyId) {
//                var surveyDate = new Date($scope.vm.surveyEmailReports.allSurveys[surveyId].closeDate).toString();
                //                return surveyDate;
                if($scope.vm.surveyEmailReports.allSurveys[surveyId].closeDate!==null)
                return moment($scope.vm.surveyEmailReports.allSurveys[surveyId].closeDate).format('YYYY-MM-DD');
            }

        

            //get current date time for page

            //     document.getElementById("demo").innerHTML = Date();
            $scope.vm.currentDate = moment().format('YYYY-MM-DD hh:mm:ss a');

//            $scope.$on('$stateChangeSuccess', function() {
//                reportService.all('reports').customGET('emails').then(function (result) {
//                    $scope.vm.report = result;
//                });
//            });
        }
    ]);;
angular.module('app')
    .controller('adminRewardDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService',
        function ($scope, localStorageService, $state, appService, modalService, toastService) {
            $scope.vm = {};
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.vm.rewardType = '';
            $scope.vm.getRewardDataForAdmin = 'starting';
            $scope.vm.rewardDate = {
                startDate: moment().subtract(6, 'months'),
                endDate: moment().add(6, 'months')
            };

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterRewards();
                }
            };
            //get initial rewards
            appService.filterRewards($scope.vm.page, $scope.vm.count, $scope.vm.rewardDate, $scope.vm.rewardType).then(function (result) {
                $scope.vm.rewards = result;
                if ($scope.vm.rewards.data.length === 0)
                    $scope.vm.getRewardDataForAdmin = 'noData';
            }, function(error) {
                $scope.vm.getRewardDataForAdmin = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //export rewards
            $scope.exportRewards = function () {
                appService.exportRewards($scope.vm.page, $scope.vm.count, $scope.vm.rewardDate, $scope.vm.rewardType)
                    .then(function (data) {
                        var file = new Blob([data], {
                            type: 'application/csv'
                        });
                        var fileUrl = URL.createObjectURL(file);
                        var a = document.createElement('a');
                        a.href = fileUrl;
                        a.target = '_blank';
                        a.download = "Rewards.csv";
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        toastService.show("Rewards exported successfully");
                    }, function (error) {
                        toastService.showError(error.data.message);
                    });
            }
            //get reward types
            appService.getRewardTypes().then(function (result) {
                $scope.vm.rewardTypes = result.values;
            });
            $scope.pageChanged = function () {

                appService.filterRewards($scope.vm.page, $scope.vm.count, $scope.vm.rewardDate, $scope.vm.rewardType).then(function (result) {
                    $scope.vm.rewards = result;
                });

            };
            //filter reward requests
            $scope.filterRewards = function () {
                appService.filterRewards($scope.vm.page, $scope.vm.count, $scope.vm.rewardDate, $scope.vm.rewardType).then(function (result) {
                    $scope.vm.rewards = result;
                });
            };
            //clear filter
            $scope.clearFilters = function () {
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                $scope.vm.rewardType = '';
                $scope.vm.rewardDate = {
                    startDate: moment().subtract(6, 'months'),
                    endDate: moment().add(6, 'months')
                };
                appService.filterRewards($scope.vm.page, $scope.vm.count, $scope.vm.rewardDate, $scope.vm.rewardType).then(function (result) {
                    $scope.vm.rewards = result;
                });
            };
            //revoke reward
            $scope.revoke = function (index) {
                appService.revokeReward($scope.vm.rewards.data[index].userId, $scope.vm.rewards.data[index].id).then(function () {
                    $scope.vm.rewards.data[index].rewardStatus = 'Revoked';
                    toastService.show('Reward revoked successfully');
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
            //grant reward
            $scope.grant = function (index) {
                appService.grantReward($scope.vm.rewards.data[index].userId, $scope.vm.rewards.data[index].id).then(function () {
                    $scope.vm.rewards.data[index].rewardStatus = 'Approved';
                    toastService.show('Reward granted successfully');
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
        }
    ]);;
angular.module('app')
    .controller('adminReferralDashboardCtrl', [
        '$scope', '$state', 'appService', 'toastService',
        function ($scope,  $state, appService, toastService) {
            $scope.vm = {};
            $scope.vm.referralStatus = '';
            $scope.vm.referralMethod = '';
            $scope.vm.userEmail = '';
            $scope.vm.referralEmail = '';
            $scope.vm.phoneNumberConfirmed = '';
            $scope.vm.signupIp = '';
            $scope.vm.approveReferralClicked = false;
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.vm.getReferralDataForAdmin = 'starting';
            $scope.vm.createDate = {
                startDate: moment().subtract(6, 'months'),
                endDate: moment()
            };

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterReferrals();
                }
            };
            //get initial referrals
            appService.filterReferrals($scope.vm.page, $scope.vm.count, $scope.vm.createDate, $scope.vm.referralStatus, $scope.vm.referralMethod, $scope.vm.userEmail, $scope.vm.referralEmail, $scope.vm.phoneNumberConfirmed, $scope.vm.signupIp).then(function (result) {
                $scope.vm.referrals = result;
                if ($scope.vm.referrals.data.length === 0)
                    $scope.vm.getReferralDataForAdmin = 'noData';
            }, function(error) {
                $scope.vm.getReferralDataForAdmin = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //export referrals
            $scope.exportReferrals = function () {
                appService.exportReferrals($scope.vm.page, $scope.vm.count, $scope.vm.createDate, $scope.vm.referralStatus,
                    $scope.vm.referralMethod, $scope.vm.userEmail, $scope.vm.referralEmail,$scope.vm.phoneNumberConfirmed,$scope.vm.signupIp).then(function (data) {
                        var file = new Blob([data], {
                            type: 'application/csv'
                        });
                        var fileUrl = URL.createObjectURL(file);
                        var a = document.createElement('a');
                        a.href = fileUrl;
                        a.target = '_blank';
                        a.download = "Referrals.csv";
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    });
            }
            //get referral statuses
            appService.getReferralStatuses().then(function (result) {
                $scope.vm.referralStatuses = result.values;
            });
            //get referral methods
            appService.getReferralMethods().then(function (result) {
                $scope.vm.referralMethods = result.values;
            });
            
            $scope.pageChanged = function () {
                appService.filterReferrals($scope.vm.page, $scope.vm.count, $scope.vm.createDate, $scope.vm.referralStatus, $scope.vm.referralMethod, $scope.vm.userEmail, $scope.vm.referralEmail, $scope.vm.phoneNumberConfirmed, $scope.vm.signupIp).then(function (result) {
                    $scope.vm.referrals = result;
                });
            };
            //filter referrals
            $scope.filterReferrals = function () {
                appService.filterReferrals($scope.vm.page, $scope.vm.count, $scope.vm.createDate, $scope.vm.referralStatus, $scope.vm.referralMethod, $scope.vm.userEmail, $scope.vm.referralEmail, $scope.vm.phoneNumberConfirmed, $scope.vm.signupIp).then(function (result) {
                    $scope.vm.referrals = result;
                });
            };
            //clear filter
            $scope.clearFilters = function () {
                $scope.vm.referralStatus = '';
                $scope.vm.referralMethod = '';
                $scope.vm.userEmail = '';
                $scope.vm.referralEmail = '';
                $scope.vm.phoneNumberConfirmed = '';
                $scope.vm.signupIp = '';
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                $scope.vm.createDate = {
                    startDate: moment().subtract(6, 'months'),
                    endDate: moment()
                };
                appService.filterReferrals($scope.vm.page, $scope.vm.count, $scope.vm.createDate, $scope.vm.referralStatus, $scope.vm.referralMethod, $scope.vm.userEmail, $scope.vm.referralEmail, $scope.vm.phoneNumberConfirmed, $scope.vm.signupIp).then(function (result) {
                    $scope.vm.referrals = result;
                });
            };
            $scope.approveReferrals = function () {
                var file = document.getElementById("approveReferralsFileId").files[0];
                if (angular.isDefined(file)) {
                    appService.uploadReferralApprovals(file).then(function (result) {
                        $scope.vm.approveReferralClicked = false;
                        //                        toastService.show("Approvals Uploaded Successfully");
                        toastService.show("Approvals Uploaded Successfully\nApproved :" + result.approved.length + "  Rejected :" + result.rejected.length);

                        $scope.clearFilters();
                    }, function (err) {
                        toastService.showError(err.data.error_description);
                    });
                } else {
                    toastService.showError("Please choose a file to upload");
                }
            };
        }
    ]);;
angular.module('app')
    .controller('adminPanelistDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'toastService', 'modalService',
        function ($scope, localStorageService, $state, appService, toastService, modalService) {
            $scope.vm = {};
            $scope.vm.filter = {};
            $scope.vm.panelists = null;
            $scope.vm.userIds = '';
            $scope.vm.filter.email = '';
            $scope.vm.filter.phoneNumber = '';
            $scope.vm.filter.fromAge = '';
            $scope.vm.filter.toAge = '';
            $scope.vm.filter.gender = '';
            $scope.vm.filter.userActiveStatus = '';
            $scope.vm.filter.minRegistrationDate = '';
            $scope.vm.filter.maxRegistrationDate = '';
            $scope.vm.filter.tierIds = [];
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.vm.filter.surveyIds = [];
            $scope.vm.filter.stateIds = [];
            $scope.vm.filter.cityIds = [];
            $scope.vm.filter.secIds = [];
            $scope.vm.profileQuestions = [];
            $scope.vm.getPanelistData = 'starting';
//            $scope.vm.filter.includeDeleted = false;
            $scope.vm.filter.includeUnsubscribed = false;
            //get all surveys names
            appService.getSurveyNames().then(function (result) {
                $scope.vm.surveyNames = result.names;
            });

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterPanelist();
                }
            };
            //get all states
            appService.getAllStates().then(function (result) {
                $scope.vm.states = result.states;
            });
            //get all cities
            appService.getAllCities().then(function (result) {
                $scope.vm.cities = result.cities;
            });
            //get all tiers
            appService.getTiers().then(function (result) {
                $scope.vm.tiers = result.tiers;
                $scope.vm.tiers.sort();
            });
            //get all surveys
            appService.getSurveys().then(function(result) {
                $scope.vm.surveys = result.surveys;
            });
            //get all secs
            appService.getSecs().then(function (result) {
                $scope.vm.secs = result.data;
            });
            //get user active statuses
            appService.getUserActiveStatus().then(function (result) {
                $scope.vm.userActiveStatuses = result.values;
            });
            //get profiles
            appService.getProfiles().then(function (result) {
                $scope.vm.profiles = result.profiles;
            });
            //get operands
            appService.getOperands().then(function (result) {
                $scope.vm.operands = result.values;
            });
            $scope.getQuestionsForProfile = function (profileQuestion) {
                angular.forEach($scope.vm.profiles, function (value) {
                    if (profileQuestion.profileId == value.id) {
                        profileQuestion.name = value.name;
                    }
                });
                appService.getQuestionsForProfile(profileQuestion.profileId).then(function (result) {
                    profileQuestion.questionsForProfile = result.data;
                });
            };
            $scope.show = function (profileQuestion) {
                var obj = JSON.parse(profileQuestion.question);
                profileQuestion.questionId = obj.id;
                profileQuestion.options = obj.options;
                profileQuestion.questionText = obj.text;
            };
            $scope.addQuestion = function () {
                $scope.vm.profileQuestions.push({ profileId: '', questionId: '', optionId: '', operand: '' });
            }
            $scope.removeQuestion = function (index) {
                $scope.vm.profileQuestions.splice(index, 1);
            }
            //            todo:keep in mind to change
            //export panelists
            $scope.exportPanelist = function () {
                appService.exportPanelists($scope.vm.page, $scope.vm.count, $scope.vm.filter, $scope.vm.profileQuestions, $scope.vm.userIds).then(function (data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Panelists.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    toastService.show("Panelists exported successfully");
                });
            };
            $scope.pageChanged = function () {
                appService.filterPanelists($scope.vm.page, $scope.vm.count, $scope.vm.filter, $scope.vm.profileQuestions, $scope.vm.userIds).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
            //filter panelists
            $scope.filterPanelist = function () {
                $scope.vm.getPanelistData = 'requestSent';
                $scope.vm.panelists = [];
                appService.filterPanelists($scope.vm.page, $scope.vm.count, $scope.vm.filter, $scope.vm.profileQuestions, $scope.vm.userIds).then(function (result) {
                    $scope.vm.panelists = result;
                    if ($scope.vm.panelists.data.length === 0)
                        $scope.vm.getPanelistData = 'noData';
                }, function(error) {
                    $scope.vm.getPanelistData = 'requestFailed';
                    toastService.showError("There was some error while loading data. Please refresh the page again");
                });
            };
            $scope.createPanelistSampleDialog = function () {
                $scope.vm.name = '';
                $scope.vm.description = '';
                $scope.vm.isActive = true;
                modalService.open($scope, '/public/views/app/admin/modals/createPanelistSample.html');
            };
            $scope.createPanelistSample = function () {
                appService.createPanelistSample($scope.vm.name, $scope.vm.description, $scope.vm.isActive, $scope.vm.filter, $scope.vm.profileQuestions).then(function () {
                    modalService.close();
                    toastService.show("Sample added successfully");
                });
            }
            //clear filter
            $scope.clearFilters = function () {
                $scope.vm.userIds = '';
                $scope.vm.filter.email = '';
                $scope.vm.filter.phoneNumber = '';
                $scope.vm.filter.fromAge = '';
                $scope.vm.filter.toAge = '';
                $scope.vm.filter.gender = '';
                $scope.vm.filter.userActiveStatus = '';
                $scope.vm.filter.minRegistrationDate = '';
                $scope.vm.filter.maxRegistrationDate = '';
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                $scope.vm.filter.surveyIds = [];
                $scope.vm.filter.stateIds = [];
                $scope.vm.filter.cityIds = [];
                $scope.vm.filter.tierIds = [];
                $scope.vm.filter.secIds = [];
                $scope.vm.profileQuestions = [];
                $scope.vm.panelists = [];
                $scope.vm.filter.includeUnsubscribed = false;
            };
            //panelist details
            $scope.goToPanelistDetails = function (id) {
                var url = $state.href('app.admin.panelist.panelistDetails', { 'panelistId': id });
                window.open(url, '_blank');
            };
        }
    ]);;
angular.module('app')
    .controller('adminRegisteredPanelistOnlyDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'toastService',
        function ($scope, localStorageService, $state, appService, toastService) {
            $scope.vm = {};
            $scope.vm.name = '';
            $scope.vm.email = '';
            $scope.vm.phoneNumber = '';
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.vm.getRegisteredPanelistsForAdmin = 'starting';

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterPanelist();
                }
            };
            //get initial panelists
            appService.filterRegisteredOnlyPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (result) {
                $scope.vm.panelists = result;
                if ($scope.vm.panelists.data.length === 0)
                    $scope.vm.getRegisteredPanelistsForAdmin = 'noData';
            }, function(error) {
                $scope.vm.getRegisteredPanelistsForAdmin = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            $scope.pageChanged = function () {
                appService.filterRegisteredOnlyPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
            //filter panelists
            $scope.filterPanelist = function () {
                appService.filterRegisteredOnlyPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
            //export panelists
            $scope.exportPanelist = function () {
                appService.exportRegisteredOnlyPanelists($scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Registered only panelists.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    toastService.show("Panelists exported successfully");
                });
            };
            //clear filter
            $scope.clearFilters = function () {
                $scope.vm.name = '';
                $scope.vm.email = '';
                $scope.vm.phoneNumber = '';
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                appService.filterRegisteredOnlyPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
        }
    ]);;
angular.module('app')
    .controller('adminBasicProfilePanelistOnlyDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService','toastService',
        function ($scope, localStorageService, $state, appService,toastService) {
            $scope.vm = {};
            $scope.vm.panelists = null;
            $scope.vm.name = '';
            $scope.vm.email = '';
            $scope.vm.phoneNumber = '';
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.vm.getBasicProfilePanelistDataForAdmin = 'starting';

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterPanelist();
                }
            };

            //get initial panelists
            appService.filterBasicProfilePanelistsOnly($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (result) {
                $scope.vm.panelists = result;
                if ($scope.vm.panelists.data.length === 0)
                    $scope.vm.getBasicProfilePanelistDataForAdmin = 'noData';
            }, function(error) {
                $scope.vm.getBasicProfilePanelistDataForAdmin = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            $scope.pageChanged = function () {
                appService.filterBasicProfilePanelistsOnly($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
            //export panelists
            $scope.exportPanelist = function () {
                appService.exportBasicProfileOnlyPanelists($scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Basic profile only panelists.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    toastService.show("Panelists exported successfully");
                });
            };
            //filter panelists
            $scope.filterPanelist = function () {
                appService.filterBasicProfilePanelistsOnly($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
            //clear filter
            $scope.clearFilters = function () {
                $scope.vm.name = '';
                $scope.vm.email = '';
                $scope.vm.phoneNumber = '';
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                appService.filterBasicProfilePanelistsOnly($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
        }
    ]);;
angular.module('app')
    .controller('adminUnsubscribedPanelistOnlyDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'toastService','modalService',
        function ($scope, localStorageService, $state, appService, toastService, modalService) {
            $scope.vm = {};
            $scope.vm.panelists = null;
            $scope.vm.name = '';
            $scope.vm.email = '';
            $scope.vm.phoneNumber = '';
            $scope.vm.includeUnsubscribed = false;
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            var indexToBeUnsubscribed = '';
            $scope.vm.getUnsubscribedPanelistsForAdmin = 'starting';

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterPanelist();
                }
            };
            //get initial panelists
            appService.filterUnsubscribedRequestPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.includeUnsubscribed).then(function (result) {
                $scope.vm.panelists = result;
                if ($scope.vm.panelists.data.length === 0)
                    $scope.vm.getUnsubscribedPanelistsForAdmin = 'noData';
            }, function(error) {
                $scope.vm.getUnsubscribedPanelistsForAdmin = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //export panelists
            $scope.exportPanelist = function () {
                appService.exportUnsubscribedRequestPanelists($scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.includeUnsubscribed).then(function (data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Unsubscribed panelists.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    toastService.show("Panelists exported successfully");
                });
            };
            $scope.pageChanged = function () {
                appService.filterUnsubscribedRequestPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.includeUnsubscribed).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
            //filter panelists
            $scope.filterPanelist = function () {
                appService.filterUnsubscribedRequestPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.includeUnsubscribed).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
            //clear filter
            $scope.clearFilters = function () {
                $scope.vm.name = '';
                $scope.vm.email = '';
                $scope.vm.phoneNumber = '';
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                $scope.vm.includeUnsubscribed = false;
                appService.filterUnsubscribedRequestPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.includeUnsubscribed).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
            $scope.unsubscribePanelistDialog = function (index) {
                indexToBeUnsubscribed= index;
                modalService.askConfirmation($scope, 'Are you sure you want to unsubscribe this panelist', 'unsubscribePanelist()');
            };
            $scope.unsubscribePanelist = function () {
                appService.unsubscribe($scope.vm.panelists.data[indexToBeUnsubscribed].id).then(function () {
                    if ($scope.vm.includeUnsubscribed)
                        $scope.vm.panelists.data[indexToBeUnsubscribed].unsubscribeDate = moment();
                    else
                        $scope.vm.panelists.data.splice(indexToBeUnsubscribed, 1);
                    modalService.close();
                    toastService.show('Panelist Unsubscribed Successfully');
                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };
        }
    ]);
       ;
angular.module('app')
    .controller('adminDeletedPanelistOnlyDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'toastService', 'modalService',
        function ($scope, localStorageService, $state, appService, toastService, modalService) {
            $scope.vm = {};
            $scope.vm.panelists = null;
            $scope.vm.name = '';
            $scope.vm.email = '';
            $scope.vm.phoneNumber = '';
            $scope.vm.includeDeleted = false;
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            var indexToBeDeleted = '';
            $scope.vm.getDeletedPanelistsForAdmin = 'starting';

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterPanelist();
                }
            };
            //get initial panelists
            appService.filterDeletedRequestPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name,
                $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.includeDeleted).then(function (result) {
                    $scope.vm.panelists = result;
                if ($scope.vm.panelists.data.length === 0)
                    $scope.vm.getDeletedPanelistsForAdmin = 'noData';
            }, function(error) {
                $scope.vm.getDeletedPanelistsForAdmin = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            $scope.pageChanged = function () {
                appService.filterDeletedRequestPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name,
                    $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.includeDeleted).then(function (result) {
                        $scope.vm.panelists = result;
                    });
            };
            //export panelists
            $scope.exportPanelist = function () {
                appService.exportDeletedRequestPanelists($scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber,
                    $scope.vm.includeDeleted).then(function (data) {
                        var file = new Blob([data], {
                            type: 'application/csv'
                        });
                        var fileUrl = URL.createObjectURL(file);
                        var a = document.createElement('a');
                        a.href = fileUrl;
                        a.target = '_blank';
                        a.download = "Deleted panelists.csv";
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        toastService.show("Panelists exported successfully");
                    });
            };
            //filter panelists
            $scope.filterPanelist = function () {
                appService.filterDeletedRequestPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name,
                    $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.includeDeleted).then(function (result) {
                        $scope.vm.panelists = result;
                    });
            };
            //clear filter
            $scope.clearFilters = function () {
                $scope.vm.name = '';
                $scope.vm.email = '';
                $scope.vm.phoneNumber = '';
                $scope.vm.includeDeleted = false;
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                appService.filterDeletedRequestPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name,
                    $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.includeDeleted).then(function (result) {
                        $scope.vm.panelists = result;
                    });
            };
            $scope.deletePanelistDialog = function (index) {
                indexToBeDeleted = index;
                modalService.askConfirmation($scope, 'Are you sure you want to delete this panelist', 'deletePanelist()');
            };
            $scope.deletePanelist = function () {
                appService.permanentDeleteAccount($scope.vm.panelists.data[indexToBeDeleted].id).then(function () {
                    if ($scope.vm.includeDeleted)
                        $scope.vm.panelists.data[indexToBeDeleted].deleteConfirmDate = moment();
                    else
                        $scope.vm.panelists.data.splice(indexToBeDeleted, 1);
                    modalService.close();
                    toastService.show('Panelist Deleted Successfully');
                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };
        }
    ]);;
angular.module('app')
    .controller('adminLegacyErrorPanelistOnlyDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'toastService',
        function ($scope, localStorageService, $state, appService, toastService) {
            $scope.vm = {};
            $scope.vm.panelists = null;
            $scope.vm.name = '';
            $scope.vm.email = '';
            $scope.vm.phoneNumber = '';
            $scope.vm.legacyErrorType = '';
            $scope.vm.page = 1;
            $scope.vm.count = 10;

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterPanelist();
                }
            };
            //get legacy error types
            appService.getLegacyErrorTypes().then(function(result) {
                $scope.vm.legacyErrorTypes = result.values;
            });
            //get initial panelists
            appService.filterLegacyErrorPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.legacyErrorType).then(function(result) {
                $scope.vm.panelists = result;
            });

            $scope.pageChanged = function () {
                appService.filterLegacyErrorPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.legacyErrorType).then(function (result) {
                    $scope.vm.panelists = result;
                } );
            };


            //filter panelists

            $scope.filterPanelist = function () {
                appService.filterLegacyErrorPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.legacyErrorType).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };

            //export panelists

            $scope.exportPanelist = function () {
                appService.exportLegacyErrorPanelists($scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber,$scope.vm.legacyErrorType).then(function (data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Legacy error only panelists.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    toastService.show("Panelists exported successfully");
                });
            };

            //clear filter

            $scope.clearFilters = function () {
                $scope.vm.name = '';
                $scope.vm.email = '';
                $scope.vm.phoneNumber = '';
                $scope.vm.legacyErrorType = '';
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                appService.filterLegacyErrorPanelists($scope.vm.page, $scope.vm.count, $scope.vm.name, $scope.vm.email, $scope.vm.phoneNumber, $scope.vm.legacyErrorType).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
        }
    ]);
;
angular.module('app')
    .controller('adminBouncedPanelistsOnlyDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'toastService',
        function ($scope, localStorageService, $state, appService, toastService) {
            $scope.vm = {};
            $scope.vm.filter = {};
            $scope.vm.filter.email = '';
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.vm.filter.blacklistType = '';
            $scope.vm.filter.type = '';
            $scope.vm.filter.subType = '';
            $scope.vm.filter.registrationDate = {
                startDate: moment().subtract(7, 'days'),
                endDate: moment()
            };
            $scope.vm.filter.blacklistType = '';
            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterPanelist();
                }
            };
            $scope.vm.getBouncedPanelistsForAdmin = 'starting';
            //get initial panelists
            appService.filterBouncedOnlyPanelists($scope.vm.page, $scope.vm.count, $scope.vm.filter).then(function (result) {
                $scope.vm.panelists = result;
                if ($scope.vm.panelists.data.length === 0)
                    $scope.vm.getBouncedPanelistsForAdmin = 'noData';
            }, function(error) {
                $scope.vm.getBouncedPanelistsForAdmin = 'reuqestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            $scope.pageChanged = function () {
                appService.filterBouncedOnlyPanelists(
                    $scope.vm.page, $scope.vm.count, $scope.vm.filter).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };

            //filter panelists
            $scope.filterPanelist = function () {
                appService.filterBouncedOnlyPanelists($scope.vm.page, $scope.vm.count, $scope.vm.filter).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };

            //go to panelist details
            $scope.goToPanelistDetails = function (id) {
                var url = $state.href('app.admin.panelist.panelistDetails', { 'panelistId': id });
                window.open(url, '_blank');
            };

            //export panelists
            $scope.exportBouncedOnlyPanelist = function () {
                appService.exportBouncedOnlyPanelists($scope.vm.page,$scope.vm.count,$scope.vm.filter).then(function (data) {
                    var file = new Blob([data], {
                        type: 'application/csv'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileUrl;
                    a.target = '_blank';
                    a.download = "Bounced only panelists.csv";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    toastService.show("Panelists exported successfully");
                });
            };
            //clear filter
            $scope.clearFilters = function () {
                $scope.vm.page = 1;
                $scope.vm.count = 10;
                $scope.vm.filter.email = '';
                $scope.vm.filter.blacklistType = '';
                $scope.vm.filter.registrationDate = {
                    startDate: moment().subtract(7, 'days'),
                    endDate: moment()
                };
               
                appService.filterBouncedOnlyPanelists($scope.vm.page, $scope.vm.count, $scope.vm.filter).then(function (result) {
                    $scope.vm.panelists = result;
                });
            };
        }
    ]);;
angular.module('app')
    .controller('adminPanelistProfileCtrl', [
        '$scope', 'userService', 'localStorageService', '$state', 'authService', 'appService', '$stateParams', 'toastService',
        function($scope, userService, localStorageService, $state, authService, appService, $stateParams, toastService) {
            $scope.vm = {};
            $scope.vm.profile = [];
            $scope.vm.progressStatus = '';
            $scope.vm.profileCompleted = null;
            $scope.profileId = $stateParams.profileId;
            var panelistId = $stateParams.panelistId;
            //get a single profile for a user 
            appService.getProfile($scope.profileId, panelistId).then(function(result) {
                $scope.vm.profile = result;
                $scope.vm.profileCompleted = result.percentageCompletion;
                if ($scope.vm.profile.percentageCompletion < 25)
                    $scope.vm.progressStatus = 'danger';
                else if ($scope.vm.profile.percentageCompletion <= 75)
                    $scope.vm.progressStatus = 'warning';
                else
                    $scope.vm.progressStatus = 'success';
                angular.forEach($scope.vm.profile.questions, function(value) {
                    if (value.userResponse == null)
                        value.userResponse = { questionId: value.id, optionsIds: [] };
                });
                //              console.log($scope.vm.profile.questions);
            });
            // update profile for a user
            $scope.saveProfile = function() {
                var userResponse = [];
                angular.forEach($scope.vm.profile.questions, function(value) {
                    if (value.userResponse.optionsIds.length)
                        userResponse.push(value.userResponse);
                });
                appService.updateProfileForSingleUser($scope.profileId, userResponse, panelistId).then(function() {
                    toastService.show('Profile has been successfully saved');
                    $state.go($state.current, {}, { reload: true });
                });
            };
        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminLabelDashboardCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', 'modalService',
        function ($scope, userService, $state, toastService, localStorageService, appService, modalService) {
            $scope.vm = {};
            $scope.vm.page = 1;
            var indexToBeDeleted = '';
            var count = 10;
            $scope.vm.labels = [];
            var editLabelId = '';
            $scope.vm.getLabelData = 'starting';
            appService.getLabels($scope.vm.page, count).then(function (result) {
                $scope.vm.labels = result;
                if ($scope.vm.labels.data.length === 0)
                    $scope.vm.getLabelData = 'noData';
            }, function(error) {
                $scope.vm.getLabelData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //create label
            $scope.createLabelDialog = function () {
                $scope.vm.name = '';
                $scope.vm.description = '';
                modalService.open($scope, '/public/views/app/admin/modals/createLabel.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.createLabel = function () {
                appService.createLabel($scope.vm.name, $scope.vm.description).then(function () {
                    modalService.close();
                    appService.getLabels($scope.vm.page, count).then(function (result) {
                        $scope.vm.labels = result;
                        toastService.show("Label created successfully");
                    });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
            //page changed
            $scope.pageChanged = function () {
                appService.getLabels($scope.vm.page, count).then(function (result) {
                    $scope.vm.labels = result;
                });
            };
            //edit label
            $scope.editLabelDialog = function (label) {
                $scope.vm.name = label.name;
                $scope.vm.description = label.description;
                editLabelId = label.id;
                modalService.open($scope, '/public/views/app/admin/modals/editLabel.html');
            };
            $scope.editLabel = function () {
                appService.editLabel(editLabelId, $scope.vm.name, $scope.vm.description).then(function () {
                    modalService.close();
                    appService.getLabels($scope.vm.page, count).then(function (result) {
                        $scope.vm.labels = result;
                        toastService.show("Label updated successfully");
                    });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
            //delete label dialog
            $scope.deleteLabelDialog = function (index) {
                indexToBeDeleted = index;
                modalService.askConfirmation($scope, 'Are you sure you want to delete this label?', 'deleteLabel()');
            }

            //delete label
            $scope.deleteLabel = function () {
                appService.deleteLabel($scope.vm.labels.data[indexToBeDeleted].id).then(function () {
                    $scope.vm.labels.data.splice(indexToBeDeleted, 1);
                    toastService.show("Label deleted successfully");
                }, function (error) {
                    toastService.showError(error.data.message);
                });
                modalService.close();
            };
        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminSampleDashboardCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', 'modalService',
        function ($scope, userService, $state, toastService, localStorageService, appService, modalService) {
            $scope.vm = {};
            $scope.vm.nameFilter = '';
            $scope.vm.page = 1;
            $scope.vm.count = 10;
            $scope.vm.samples = [];
            $scope.vm.getSampleData = 'starting';
            var editSampleId = '';

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterSample();
                }
            };
            //get initial samples
            appService.filterSamples($scope.vm.page, $scope.vm.count, $scope.vm.nameFilter).then(function (result) {
                $scope.vm.samples = result;
                if ($scope.vm.samples.data.length === 0)
                    $scope.vm.getSampleData = 'noData';
            }, function(error) {
                $scope.vm.getSampleData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //filter samples
            $scope.filterSample = function () {
                appService.filterSamples($scope.vm.page, $scope.vm.count, $scope.vm.nameFilter).then(function (result) {
                    $scope.vm.samples = result;
                });
            };
            //clear filters
            $scope.clearFilters = function () {
                $scope.vm.nameFilter = '';
                $scope.filterSample();
            }
            //page changed
            $scope.pageChanged = function () {
                //$scope.filterSample();
                appService.filterSamples($scope.vm.page, $scope.vm.count, $scope.vm.nameFilter).then(function (result) {
                    $scope.vm.samples = result;
                });
              };
            //get all tiers
            appService.getTiers().then(function (result) {
                $scope.vm.tiers = result.tiers;
                $scope.vm.tiers.sort();
            });

            //get all states
            appService.getAllStates().then(function(result) {
                $scope.vm.states = result.states;
            });

            //get all cities
            appService.getAllCities().then(function (result) {
                $scope.vm.cities = result.cities;
            });
            //create sample
            $scope.createSampleDialog = function () {
                $scope.vm.name = '';
                $scope.vm.description = '';
                $scope.vm.isActive = true;
                $scope.vm.gender = "null";
                $scope.vm.fromAge = '';
                $scope.vm.toAge = '';
                $scope.vm.tierIds = [];
                $scope.vm.cityIds = [];
                $scope.vm.stateIds = [];
                $scope.vm.registrationDate = { startDate: null, endDate: null };
                modalService.open($scope, '/public/views/app/admin/modals/createSample.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.createSample = function () {
                var tierIds = [];
                var cityIds = [];
                var stateIds = [];
                if ($scope.vm.tierIds.length) {
                    angular.forEach($scope.vm.tierIds, function (value) {
                        tierIds.push(JSON.parse(value));
                    });
                }
                if ($scope.vm.cityIds.length) {
                    angular.forEach($scope.vm.cityIds, function (value) {
                        cityIds.push(JSON.parse(value));
                    });
                }

                if ($scope.vm.stateIds.length) {
                    angular.forEach($scope.vm.stateIds, function(value) {
                        stateIds.push(JSON.parse(value));
                    });
                }
                appService.createSample($scope.vm.name, $scope.vm.description, $scope.vm.isActive, $scope.vm.gender
                    , $scope.vm.fromAge, $scope.vm.toAge, tierIds, cityIds,stateIds, $scope.vm.registrationDate).then(function () {
                        modalService.close();
                        appService.getSamples($scope.vm.page, $scope.vm.count).then(function (result) {
                            $scope.vm.samples = result;
                         toastService.show("Sample created successfully");
                        });
                    }, function (error) {
                        toastService.showError(error.data.message);
                    });
            };
            //edit sample
            $scope.editSampleDialog = function (sample) {
                $scope.vm.name = sample.name;
                $scope.vm.description = sample.description;
                $scope.vm.isActive = sample.isActive;
                if (sample.gender == null)
                    $scope.vm.gender = "null";
                else
                    $scope.vm.gender = sample.gender.toString();
                $scope.vm.fromAge = sample.fromAge;
                $scope.vm.toAge = sample.toAge;
                $scope.vm.tierIds = [];
                angular.forEach(sample.tiers, function (value) {
                    $scope.vm.tierIds.push(JSON.stringify(value));
                });
                $scope.vm.cityIds = [];
                angular.forEach(sample.cities, function (value) {
                    $scope.vm.cityIds.push(JSON.stringify(value));
                });
                $scope.vm.stateIds = [];
                angular.forEach(sample.states, function(value) {
                    $scope.vm.stateIds.push(JSON.stringify(value));
                });
                $scope.vm.registrationDate = { startDate: sample.fromRegistrationDate, endDate: sample.toRegistrationDate };
                editSampleId = sample.id;
                modalService.open($scope, '/public/views/app/admin/modals/editSample.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.editSample = function () {
                var tierIds = [];
                var cityIds = [];
                var stateIds = [];
                if ($scope.vm.tierIds.length) {
                    angular.forEach($scope.vm.tierIds, function (value) {
                        tierIds.push(JSON.parse(value));
                    });
                }
                if ($scope.vm.cityIds.length) {
                    angular.forEach($scope.vm.cityIds, function (value) {
                        cityIds.push(JSON.parse(value));
                    });
                }
                if ($scope.vm.stateIds.length) {
                    angular.forEach($scope.vm.stateIds, function (value) {
                        stateIds.push(JSON.parse(value));
                    });
                }
                appService.editSample(editSampleId, $scope.vm.name, $scope.vm.description, $scope.vm.isActive, $scope.vm.gender
                    , $scope.vm.fromAge, $scope.vm.toAge, $scope.vm.tierIds, $scope.vm.cityIds,$scope.vm.stateIds, $scope.vm.registrationDate).then(function () {
                        modalService.close();
                        appService.getSamples($scope.vm.page, $scope.vm.count).then(function (result) {
                            $scope.vm.samples = result;
                            toastService.show("Sample updated successfully");
                        });
                    }, function (error) {
                        toastService.showError(error.data.message);
                    });
            };
            $scope.getProfileCount = function (index) {
                appService.getProfileCountForSample($scope.vm.samples.data[index].id).then(function (result) {
                    $scope.vm.samples.data[index].profileCount = result.count;
                }, function (error) {
                    if (error.status == 404)
                        toastService.showError("We are calculating the profile count. Please try again later.");
                });
            }
            $scope.clearDate = function () {
                $scope.vm.registrationDate = { startDate: null, endDate: null };
            };
            $scope.getSampleStats = function (sampleId) {
                $scope.vm.sampleStats = null;
                appService.getSampleStats(sampleId).then(function (result) {
                    $scope.vm.sampleStats = result;
                }, function (error) {
                    if (error.status == 404)
                        toastService.showError("We are still calculating the stats. Please try again later.");
                });
            }
        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminSecDashboardCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', 'modalService',
        function ($scope, userService, $state, toastService, localStorageService, appService, modalService) {
            $scope.vm = {};
            $scope.vm.nameFilter = '';
            $scope.vm.page = 1;
            var count = 10;
            $scope.vm.secs = [];
            var editSecId = '';
            $scope.vm.getSecData = 'starting';

            $scope.action = function (event) {
                if (event.which === 13) {
                    event.preventDefault();
                    $scope.filterSec();
                }
            };

            //get initial Secs
            appService.filterSecs($scope.vm.page, count, $scope.vm.nameFilter).then(function (result) {
                $scope.vm.secs = result;
                if ($scope.vm.secs.data.length === 0)
                    $scope.vm.getSecData = 'noData';
            },function(error) {
                $scope.vm.getSecData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            $scope.filterSec = function () {
                appService.filterSecs($scope.vm.page, count, $scope.vm.nameFilter).then(function (result) {
                    $scope.vm.secs = result;
                });
            };
            //clear filters
            $scope.clearFilters = function () {
                $scope.vm.nameFilter = '';
                $scope.filterSec();
            }
            //page changed
            $scope.pageChanged = function () {
                $scope.filterSec();
            };
          //create SEC
            $scope.createSecDialog = function () {
                $scope.vm.name = '';
                $scope.vm.description = '';
                $scope.vm.isActive = true;
                modalService.open($scope, '/public/views/app/admin/modals/createSec.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.createSec = function () {
                appService.createSec($scope.vm.name, $scope.vm.description, $scope.vm.isActive
                     ).then(function () {
                        modalService.close();
                        appService.getSecs($scope.vm.page, count).then(function (result) {
                            $scope.vm.secs = result;
                            toastService.show("Sec created successfully");
                        });
                    }, function (error) {
                        toastService.showError(error.data.message);
                    });
            };
            //edit sec
            $scope.editSecDialog = function (sec) {
                $scope.vm.name = sec.name;
                $scope.vm.description = sec.description;
                $scope.vm.isActive = sec.isActive;
              editSecId = sec.id;
              modalService.open($scope, '/public/views/app/admin/modals/editSec.html');
              $scope.closeForm = function () {
                  modalService.close();
              }
            };
            $scope.editSec = function () {
                appService.editSec(editSecId, $scope.vm.name, $scope.vm.description, $scope.vm.isActive
                    ).then(function () {
                        modalService.close();
                        appService.getSecs($scope.vm.page, count).then(function (result) {
                            $scope.vm.secs = result;
                          toastService.show("Sec updated successfully");
                        });
                    }, function (error) {
                        toastService.showError(error.data.message);
                    });
            };
            $scope.getProfileCount = function (index) {
                appService.getProfileCountForSec($scope.vm.secs.data[index].id).then(function (result) {
                    $scope.vm.secs.data[index].profileCount = result.count;
                }, function (error) {
                    if (error.status == 404)
                        toastService.showError("We are calculating the profile count. Please try again later.");
                });
            }
         }
    ]);;
'use strict';

angular.module('app')
    .controller('adminSampleQuestionsCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', 'modalService', '$stateParams',
        function ($scope, userService, $state, toastService, localStorageService, appService, modalService, $stateParams) {
            $scope.vm = {};
            $scope.vm.sampleQuestions = [];
            var idToBeDeleted = '';
            $scope.vm.profiles = [];
            $scope.vm.questionsForProfile = [];
            $scope.vm.profileId = '';
            $scope.vm.questionId = '';
            $scope.vm.operandId = '';
            $scope.vm.questionToBeAdded = {};
            $scope.vm.options = [];
            var sampleId = $stateParams.sampleId;
            //get questions
            appService.getSampleQuestions(sampleId).then(function (result) {
                $scope.vm.sampleQuestions = result.data;
                angular.forEach($scope.vm.sampleQuestions, function (value) {
                    var optionsNameArray = [];
                    value.optionsName = '';
                    angular.forEach(value.question.options, function (option) {
                        if (value.options.indexOf(option.id) > -1)
                            optionsNameArray.push(option.value);
                    });
                    value.optionsName = optionsNameArray.join(',');
                });
            });
            $scope.addSampleQuestionDialog = function () {
                $scope.vm.profileId = '';
                $scope.vm.questionId = '';
                $scope.vm.questionsForProfile = [];
                $scope.vm.optionIds = [];
                $scope.vm.questionToBeAdded = {};
                $scope.vm.options = [];
                modalService.open($scope, '/public/views/app/admin/modals/addSampleQuestion.html');
            };
            //get profiles
            appService.getProfiles().then(function (result) {
                $scope.vm.profiles = result.profiles;
            });
            //get operands
            appService.getOperands().then(function (result) {
                $scope.vm.operands = result.values;
            });
            $scope.getQuestionsForProfile = function (profileId) {
                appService.getQuestionsForProfile(profileId).then(function (result) {
                    $scope.vm.questionsForProfile = result.data;
                });
            };

            //add sample question
            $scope.addSampleQuestion = function () {
                appService.addSampleQuestion(sampleId, $scope.vm.questionId, $scope.vm.optionIds,
                    $scope.vm.operandId).then(function () {
                        modalService.close();
                        toastService.show('Question added successfully');
                        appService.getSampleQuestions(sampleId).then(function (result) {
                            $scope.vm.sampleQuestions = result.data;
                            angular.forEach($scope.vm.sampleQuestions, function (value) {
                                var optionsNameArray = [];
                                value.optionsName = '';
                                angular.forEach(value.question.options, function (option) {
                                    if (value.options.indexOf(option.id) > -1)
                                        optionsNameArray.push(option.value);
                                });
                                value.optionsName = optionsNameArray.join(',');
                            });
                        });
                    }, function (error) {
                        toastService.showError(error.data.message);
                    });
            };
            $scope.show = function () {
                var obj = JSON.parse($scope.vm.questionToBeAdded);
                $scope.vm.questionId = obj.id;
                $scope.vm.options = obj.options;
            };
            //delete question dialog
            $scope.deleteQuestionDialog = function (id) {
                idToBeDeleted = id;
                modalService.askConfirmation($scope, 'Are you sure you want to delete this question?', 'deleteQuestion()');
            }
            $scope.deleteQuestion = function () {
                appService.deleteSampleQuestion(sampleId, idToBeDeleted).then(function () {
                    toastService.show('Question deleted successfully');
                    modalService.close();
                    appService.getSampleQuestions(sampleId).then(function (result) {
                        $scope.vm.sampleQuestions = result.data;
                        angular.forEach($scope.vm.sampleQuestions, function (value) {
                            var optionsNameArray = [];
                            value.optionsName = '';
                            angular.forEach(value.question.options, function (option) {
                                if (value.options.indexOf(option.id) > -1)
                                    optionsNameArray.push(option.value);
                            });
                            value.optionsName = optionsNameArray.join(',');
                        });
                    });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            }
            $scope.closeDialog = function () {
                modalService.close();
            };
        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminSecQuestionsCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', 'modalService', '$stateParams',
        function ($scope, userService, $state, toastService, localStorageService, appService, modalService, $stateParams) {
            $scope.vm = {};
            $scope.vm.secQuestions = [];
            var idToBeDeleted = '';
            $scope.vm.profiles = [];
            $scope.vm.questionsForProfile = [];
            $scope.vm.profileId = '';
            $scope.vm.questionId = '';
            $scope.vm.operandId = '';
            $scope.vm.questionToBeAdded = {};
            $scope.vm.options = [];
            var secId = $stateParams.secId;
            //get questions
            appService.getSecQuestions(secId).then(function (result) {
                $scope.vm.secQuestions = result.data;
                angular.forEach($scope.vm.secQuestions, function (value) {
                    var optionsNameArray = [];
                    value.optionsName = '';
                    angular.forEach(value.question.options, function (option) {
                        if (value.options.indexOf(option.id) > -1)
                            optionsNameArray.push(option.value);
                    });
                    value.optionsName = optionsNameArray.join(',');
                });
            });
            $scope.addSecQuestionDialog = function () {
                $scope.vm.profileId = '';
                $scope.vm.questionId = '';
                $scope.vm.questionsForProfile = [];
                $scope.vm.optionIds = [];
                $scope.vm.questionToBeAdded = {};
                $scope.vm.options = [];
                modalService.open($scope, '/public/views/app/admin/modals/addSecQuestion.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            //get profiles
            appService.getProfiles().then(function (result) {
                $scope.vm.profiles = result.profiles;
            });
            //get operands
            appService.getOperands().then(function (result) {
                $scope.vm.operands = result.values;
            });
            $scope.getQuestionsForProfile = function (profileId) {
                appService.getQuestionsForProfile(profileId).then(function (result) {
                    $scope.vm.questionsForProfile = result.data;
                });
            };

            //add sec question
            $scope.addSecQuestion = function () {
                appService.addSecQuestion(secId, $scope.vm.questionId, $scope.vm.optionIds
                    ).then(function () {
                        modalService.close();
                        toastService.show('Question added successfully');
                        appService.getSecQuestions(secId).then(function (result) {
                            $scope.vm.secQuestions = result.data;
                            angular.forEach($scope.vm.secQuestions, function (value) {
                                var optionsNameArray = [];
                                value.optionsName = '';
                                angular.forEach(value.question.options, function (option) {
                                    if (value.options.indexOf(option.id) > -1)
                                        optionsNameArray.push(option.value);
                                });
                                value.optionsName = optionsNameArray.join(',');
                            });
                        });
                    }, function (error) {
                        toastService.showError(error.data.message);
                    });
            };
            $scope.show = function () {
                var obj = JSON.parse($scope.vm.questionToBeAdded);
                $scope.vm.questionId = obj.id;
                $scope.vm.options = obj.options;
            };
            //delete question dialog
            $scope.deleteQuestionDialog = function (id) {
                idToBeDeleted = id;
                modalService.askConfirmation($scope, 'Are you sure you want to delete this question?', 'deleteQuestion()');
            }
            $scope.deleteQuestion = function () {
                appService.deleteSecQuestion(secId, idToBeDeleted).then(function () {
                    toastService.show('Question deleted successfully');
                    modalService.close();
                    appService.getSecQuestions(secId).then(function (result) {
                        $scope.vm.secQuestions = result.data;
                        angular.forEach($scope.vm.secQuestions, function (value) {
                            var optionsNameArray = [];
                            value.optionsName = '';
                            angular.forEach(value.question.options, function (option) {
                                if (value.options.indexOf(option.id) > -1)
                                    optionsNameArray.push(option.value);
                            });
                            value.optionsName = optionsNameArray.join(',');
                        });
                    });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            }
            $scope.closeDialog = function () {
                modalService.close();
            };
        }
    ]);;
angular.module('app')
    .controller('adminNewsletterDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService', 'userService','$http',
    function ($scope, localStorageService, $state, appService, modalService, toastService, userService,$http) {
        $scope.vm = {};
        $scope.vm.page = 1;
        $scope.vm.count = 10;
        var indexToBeDeleted = '';
        $scope.vm.todayDate = moment();
        $scope.vm.getNewsletterData = 'starting';

        //get newsletters
        appService.getNewsletters($scope.vm.page, $scope.vm.count).then(function (result) {
            $scope.vm.newsletters = result;
            if ($scope.vm.newsletters.data.length === 0)
                $scope.vm.getNewsletterData = 'noData';
        }, function(error) {
            $scope.vm.getNewsletterData = 'requestFailed';
            toastService.showError("There was some error while loading data. Please refresh the page again");
        });
        $scope.pageChanged = function () {
            appService.getNewsletters($scope.vm.page, $scope.vm.count).then(function (result) {
                $scope.vm.newsletters = result;
            });
        };
        //create newsletter
        $scope.createNewsletterDialog = function () {
            $scope.vm.newsletter = {};
            //            $scope.vm.newsletter.body = '<p>Dear Panelist, <br/><br/>Thank You for choosing IndiaSpeaks to voice your valuable opinion!<br/><br/>Congratulations! You have redeemed yourself cash as part of Indiaspeaks rewards redemption benefits for successful referrals/surveys that you have completed.<br/><br/>IndiaSpeaks is India’s premium survey portal – where we invite registered users to take part in product / brand surveys and earn attractive reward points for their opinions.<br/><br/>Also, remember that there are more prizes to be won regularly. All you need to do is fill in the surveys that we will send out to you from time to time. And that gives you a chance to earn rewards from Rs. 20 to Rs. 2000 and enter into monthly sweepstakes. You can either REDEEM your points or donate them to a charitable organization of your choice.<br/><br/>Don’t let this be a secret…talk about us. If you successfully bring a person a friend on-board, you also earn 20 IndiaSpeaks points whenever a person referred by you becomes a member.<br/><br/>All the surveys that you respond to are used by various companies to provide better products or services to customers - so your opinion will count!<br/><br/>We hope that this will be the beginning of a lasting and a fruitful relationship.<br/><br/><br/><b>Warm Regards,<br/>IndiaSpeaks Online Panel</b></p>';
            $http.get('/public/views/app/admin/partials/newsletterTemplate.html').then(function(response) {
                $scope.vm.newsletter.body = response.data;
            });
            modalService.open($scope, '/public/views/app/admin/modals/createNewsletter.html');
            $scope.closeForm = function () {
                modalService.close();
            }
        };
        $scope.createNewsletter = function () {
            appService.createNewsletter($scope.vm.newsletter.name, $scope.vm.newsletter.sendDate, $scope.vm.newsletter.subject, $scope.vm.newsletter.body, $scope.vm.newsletter.emails).then(function () {
                modalService.close();
                toastService.show("Newsletter created successfully.");
                appService.getNewsletters($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.newsletters = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
        };
        //edit newsletter
        $scope.editNewsletterDialog = function (newsletter) {
            $scope.vm.newsletter = newsletter;
            $scope.vm.a = moment($scope.vm.newsletter.sendDate).format("YYYY-MM-DD");

            modalService.open($scope, '/public/views/app/admin/modals/editNewsletter.html');
            $scope.closeForm = function () {
                modalService.close();
            }
        };
        $scope.editNewsletter = function () {
            appService.editNewsletter($scope.vm.newsletter.id, $scope.vm.newsletter.name, $scope.vm.a, $scope.vm.newsletter.subject, $scope.vm.newsletter.body, $scope.vm.newsletter.emails).then(function () {
                modalService.close();
                toastService.show("Newsletter edited successfully.");
                appService.getNewsletters($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.newsletters = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
        };
        //show newsletter body
        $scope.viewNewsletterBody = function (newsletter) {
            $scope.vm.newsletter = newsletter;
            modalService.open($scope, '/public/views/app/admin/modals/viewNewsletterBody.html', 'lg');
            $scope.closeForm = function () {
                modalService.close();
            }
        };
        //send newsletter
        $scope.sendNewsletterDialog = function (newsletter) {
            $scope.vm.newsletter = newsletter;
            modalService.askConfirmation($scope, 'Are you sure you want to send this newsletter ?', 'sendNewsletter()');
        };
        $scope.sendNewsletter = function () {
            appService.sendNewsletter($scope.vm.newsletter.id).then(function () {
                modalService.close();
                toastService.show("Newsletter sent successfully");
            });
        };
        //delete newsletter dialog
        $scope.deleteNewsletterDialog = function (index) {
            indexToBeDeleted = index;
            modalService.askConfirmation($scope, 'Are you sure you want to delete this newsletter?', 'deleteNewsletter()');
        };
        $scope.deleteNewsletter = function () {
            appService.deleteNewsletter($scope.vm.newsletters.data[indexToBeDeleted].id).then(function () {
                toastService.show("Newsletter deleted successfully.");
                appService.getNewsletters($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.newsletters = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
            modalService.close();
        };
    }]);;
'use strict';

angular.module('app')
    .controller('adminNewsletterDetailsCtrl', [
        '$scope', '$state', 'toastService', 'appService', '$stateParams',
        function ($scope, $state, toastService, appService, $stateParams) {
            $scope.vm = {};
            var newsletterId = $stateParams.newsletterId;
            appService.getNewsletter(newsletterId).then(function (result) {
                $scope.vm.newsletter = result;
            });
            //get all samples
            appService.getSamples(1, -1).then(function (result) {
                $scope.vm.samples = [];
                angular.forEach(result.data, function (value) {
                    if (value.isActive)
                        $scope.vm.samples.push(value);
                });
            });
            //get samples attached to newsletter
            appService.getNewsletterSamples(newsletterId).then(function (result) {
                $scope.vm.newsletterSamples = [];
                angular.forEach(result.data, function (value) {
                    $scope.vm.newsletterSamples.push(JSON.stringify(value));
                });
            });

            //attach samples to newsletter
            $scope.attachSamples = function () {
                var sampleIds = [];
                if (!$scope.vm.newsletterSamples.length)
                    toastService.show('No samples are chosen to assign');
                else {
                    angular.forEach($scope.vm.newsletterSamples, function (value) {
                        sampleIds.push(JSON.parse(value).id);
                    });
                    appService.attachSamplesToNewsletter(sampleIds, newsletterId).then(function () {
                        toastService.show("Samples successfully attached to newsletter");
                        $state.go('app.admin.newsletterDashboard');
                    });
                }
            };
        }
    ]);;
angular.module('app')
    .controller('adminPartnerDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService', 'userService',
    function ($scope, localStorageService, $state, appService, modalService, toastService, userService) {
        $scope.vm = {};
        $scope.vm.page = 1;
        $scope.vm.count = 10;
        var indexToBeDeleted = '';
        $scope.vm.getPartnerData = 'starting';

        //get partners
        appService.getPartners($scope.vm.page, $scope.vm.count).then(function (result) {
            $scope.vm.partners = result;
            if ($scope.vm.partners.data.length === 0)
                $scope.vm.getPartnerData = 'noData';
        }, function(error) {
            $scope.vm.getPartnerData = 'requestFailed';
            toastService.showError("There was some error while loading data. Please refresh the page again");
        });
        $scope.pageChanged = function () {
            appService.getPartners($scope.vm.page, $scope.vm.count).then(function (result) {
                $scope.vm.partners = result;
            });
        };
        //get all samples
        appService.getSamples(1, -1).then(function (result) {
            $scope.vm.samples = result.data;
        });
        //create partner
        $scope.createPartnerDialog = function () {
            $scope.vm.partner = {};
            modalService.open($scope, '/public/views/app/admin/modals/createPartner.html');
            $scope.closeForm = function () {
                modalService.close();
            }
        };
        $scope.createPartner = function () {
            appService.createPartner($scope.vm.partner.name, $scope.vm.partner.description, $scope.vm.partner.successUrl, $scope.vm.partner.overquotaUrl, $scope.vm.partner.disqualifiedUrl).then(function () {
                modalService.close();
                toastService.show("Partner created successfully.");
                appService.getPartners($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.partners = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
        };
        //edit partner
        $scope.editPartnerDialog = function (partner) {
            $scope.vm.partner = partner;
            modalService.open($scope, '/public/views/app/admin/modals/editPartner.html');
            $scope.closeForm = function () {
                modalService.close();
            }
        };
        $scope.editPartner = function () {
            appService.editPartner($scope.vm.partner.id, $scope.vm.partner.name, $scope.vm.partner.description, $scope.vm.partner.successUrl, $scope.vm.partner.overquotaUrl, $scope.vm.partner.disqualifiedUrl).then(function () {
                modalService.close();
                toastService.show("Partner edited successfully.");
                appService.getPartners($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.partners = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
        };
        //show partner body
        $scope.viewPartnerDescription = function (partner) {
            $scope.vm.partner = partner;
            modalService.open($scope, '/public/views/app/admin/modals/viewPartnerDescription.html');
        };
        //delete partner dialog
        $scope.deletePartnerDialog = function (index) {
            indexToBeDeleted = index;
            modalService.askConfirmation($scope, 'Are you sure you want to delete this partner?', 'deletePartner()');
        };
        $scope.deletePartner = function () {
            appService.deletePartner($scope.vm.partners.data[indexToBeDeleted].id).then(function () {
                toastService.show("Partner deleted successfully.");
                appService.getPartners($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.partners = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
            modalService.close();
        };
    }]);;
angular.module('app')
    .controller('adminMarketingLinkDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService', 'userService',
    function ($scope, localStorageService, $state, appService, modalService, toastService, userService) {
        $scope.vm = {};
        $scope.vm.page = 1;
        $scope.vm.count = 10;
        var indexToBeDeleted = '';
        var idToBeEdited = '';
        $scope.vm.getMarketingLinkData = 'starting';

        //get marketingLinks
        appService.getMarketingLinks($scope.vm.page, $scope.vm.count).then(function (result) {
            $scope.vm.marketingLinks = result;
            if ($scope.vm.marketingLinks.data.length === 0)
                $scope.vm.getMarketingLinkData = 'noData';
        }, function(error) {
            $scope.vm.getMarketingLinkData = 'requestFailed';
            toastService.showError("There was some error while loading data. Please refresh the page again");
        });
        $scope.pageChanged = function () {
            appService.getMarketingLinks($scope.vm.page, $scope.vm.count).then(function (result) {
                $scope.vm.marketingLinks = result;
            });
        };
        //create marketingLink
        $scope.createMarketingLinkDialog = function () {
            $scope.vm.name = "";
            $scope.vm.description = "";
            modalService.open($scope, '/public/views/app/admin/modals/createMarketingLink.html');
            $scope.closeForm = function () {
                modalService.close();
            }
        };
        $scope.createMarketingLink = function () {
            appService.createMarketingLink($scope.vm.name, $scope.vm.description).then(function () {
                modalService.close();
                toastService.show("Marketing Link created successfully.");
                appService.getMarketingLinks($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.marketingLinks = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
        };
        //edit marketingLink
        $scope.editMarketingLinkDialog = function (marketingLink) {
            idToBeEdited = marketingLink.id;
            $scope.vm.name = marketingLink.name;
            $scope.vm.description = marketingLink.description;
            modalService.open($scope, '/public/views/app/admin/modals/editMarketingLink.html');
            $scope.closeForm = function () {
                modalService.close();
            }
        };
        $scope.editMarketingLink = function () {
            appService.editMarketingLink(idToBeEdited, $scope.vm.name, $scope.vm.description).then(function () {
                modalService.close();
                toastService.show("Marketing Link edited successfully.");
                appService.getMarketingLinks($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.marketingLinks = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
        };
        //show marketingLink description
        $scope.viewMarketingLinkDescription = function (marketingLink) {
            $scope.vm.marketingLink = marketingLink;
            modalService.open($scope, '/public/views/app/admin/modals/viewMarketingLinkDescription.html');
        };
        //delete marketingLink dialog
        $scope.deleteMarketingLinkDialog = function (index) {
            indexToBeDeleted = index;
            modalService.askConfirmation($scope, 'Are you sure you want to delete this marketing Link ?', 'deleteMarketingLink()');
        };
        $scope.deleteMarketingLink = function () {
            appService.deleteMarketingLink($scope.vm.marketingLinks.data[indexToBeDeleted].id).then(function () {
                toastService.show("Marketing Link deleted successfully.");
                appService.getMarketingLinks($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.marketingLinks = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
            modalService.close();
        };

        //export marketing links
        $scope.exportMarketingLinks = function () {
            appService.exportMarketingLinks($scope.vm.page, $scope.vm.count).then(function (data) {
                var file = new Blob([data], {
                    type: 'application/csv'
                });
                var fileUrl = URL.createObjectURL(file);
                var a = document.createElement('a');
                a.href = fileUrl;
                a.target = '_blank';
                a.download = "MarketingLinks.csv";
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
        }

        //get users
        $scope.viewUsers = function (linkId) {
            $state.go('app.admin.marketingLinkUsers', { marketingLinkId: linkId });
        };
    }]);;
angular.module('app')
    .controller('adminMarketingLinkUsersCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService', 'userService', '$stateParams',
    function ($scope, localStorageService, $state, appService, modalService, toastService, userService, $stateParams) {
        $scope.vm = {};
        $scope.vm.page = 1;
        $scope.vm.count = 10;
        var linkId = $stateParams.marketingLinkId;
        $scope.vm.getMarketingLinkUsersData = 'starting';

        //get link detail
        appService.getMarketingLink(linkId).then(function (result) {
            $scope.vm.marketingLink = result;
        });
        //get marketing Link users

        appService.getUsersForLink(linkId, $scope.vm.page, $scope.vm.count).then(function (result) {
            $scope.vm.marketingLinkUsers = result;
            if ($scope.vm.marketingLinkUsers.data.length === 0)
                $scope.vm.getMarketingLinkUsersData = 'noData';
        }, function(error) {
            $scope.vm.getMarketingLinkUsersData = 'requestFailed';
            toastService.showError("There was some error while loading data. Please refresh the page again");
        });

        $scope.pageChanged = function () {
            appService.getUsersForLink(linkId, $scope.vm.page, $scope.vm.count).then(function (result) {
                $scope.vm.marketingLinkUsers = result;
            });
        };

        //export marketing link users details
        $scope.exportMarketingLinkUserDetails = function () {
            appService.exportMarketingLinkUserDetails(linkId).then(function (data) {
                var file = new Blob([data], {
                    type: 'application/csv'
                });
                var fileUrl = URL.createObjectURL(file);
                var a = document.createElement('a');
                a.href = fileUrl;
                a.target = '_blank';
                a.download = "Marketing Link User details.csv";
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
        }
    }]);;
angular.module('app')
    .controller('adminSweepstakeDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService',
    function ($scope, localStorageService, $state, appService, modalService, toastService) {
        $scope.vm = {};
        $scope.vm.page = 1;
        $scope.vm.count = 10;
        $scope.vm.getSweepstakeData = 'starting';

        //get sweepstakes
        appService.getSweepstakes($scope.vm.page, $scope.vm.count).then(function (result) {
            $scope.vm.sweepstakes = result;
            if ($scope.vm.sweepstakes.data.length === 0)
                $scope.vm.getSweepstakeData = 'noData';
        }, function (erorr) {
            $scope.vm.getSweepstakeData = 'requestFailed';
            toastService.showError("There was some error while loading data. Please refresh the page again");
        });
        $scope.pageChanged = function () {
            appService.getSweepstakes($scope.vm.page, $scope.vm.count).then(function (result) {
                $scope.vm.sweepstakes = result;
            });
        };

        //create sweepstake
        $scope.createSweepstakeDialog = function () {
            $scope.vm.sweepstakeDate = '';
            modalService.open($scope, '/public/views/app/admin/modals/createSweepstake.html');
            $scope.closeForm = function () {
                modalService.close();
            }
        };
        $scope.createSweepstake = function () {
            appService.createSweepstake($scope.vm.sweepstakeDate).then(function () {
                toastService.show("Sweepstake created successfully.");
                appService.getSweepstakes($scope.vm.page, $scope.vm.count).then(function (result) {
                    $scope.vm.sweepstakes = result;
                });
            }, function (error) {
                toastService.showError(error.data.message);
            });
            modalService.close();
        };

        //approve sweepstake
        $scope.approveRequestDialog = function (id) {
            modalService.askConfirmation($scope, 'Are you sure you want to approve this sweepstake ?', 'approve()');
            $scope.approve = function () {
                appService.approveSweepstake(id).then(function () {
                    toastService.show('Sweepstake approved successfully');
                    appService.getSweepstakes($scope.vm.page, $scope.vm.count).then(function (result) {
                        $scope.vm.sweepstakes = result;
                        modalService.close();
                    });
                });
            }, function (error) {
                toastService.showError(error.data.message);
            };
        }

        //export sweepstakes

        $scope.exportSweepstakes = function () {
            appService.exportSweepstakes($scope.vm.page, $scope.vm.count).then(function (data) {
                var file = new Blob([data], {
                    type: 'application/csv'
                });
                var fileUrl = URL.createObjectURL(file);
                var a = document.createElement('a');
                a.href = fileUrl;
                a.target = '_blank';
                a.download = "Sweepstakes.csv";
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
        }


    }]);;
'use strict';
angular.module('app')
    .controller('adminEmailsForScheduleCtrl', [
        '$scope', 'localStorageService', '$state','$window', 'appService', '$stateParams','toastService','modalService',
    function ($scope, localStorageService, $state,$window, appService, $stateParams,toastService,modalService) {
        $scope.vm = {};
        $scope.vm.page = 1;
        $scope.vm.count = 10;
        var emailScheduleId = $stateParams.emailScheduleId;
        var surveyId = $stateParams.surveyId;
     //get emails for schedule
        appService.getEmailsForSchedule($scope.vm.page, $scope.vm.count, surveyId, emailScheduleId).then(function (result) {
            $scope.vm.emailsForSchedule = result;
        });
        //get emails for schedule status
        appService.getEmailsForScheduleStatus($scope.vm.page, $scope.vm.count, surveyId, emailScheduleId).then(function (result) {
            $scope.vm.total = result.total;
            $scope.vm.sent = result.sent;
            $scope.vm.unSent = result.unsent;
        });
        $scope.pageChanged = function () {
            appService.getEmailsForSchedule($scope.vm.page, $scope.vm.count, surveyId, emailScheduleId).then(function (result) {
                $scope.vm.emailsForSchedule = result;
            });
        };
        //get all samples
        appService.getSamples(1, -1).then(function (result) {
            $scope.vm.samples = [];
            angular.forEach(result.data, function (value) {
                if (value.isActive)
                    $scope.vm.samples.push(value);
            });
        });
        //get samples attached to email schedules
        appService.getEmailScheduleSamples(emailScheduleId).then(function (result) {
            $scope.vm.emailScheduleSamples = [];
            angular.forEach(result.data, function (value) {
                $scope.vm.emailScheduleSamples.push(JSON.stringify(value));
            });
        });

        //panelist details
        $scope.goToPanelistDetails = function (id) {
            var url = $state.href('app.admin.panelist.panelistDetails', { 'panelistId': id });
            window.open(url, '_blank');
        };

        //attach samples to email schedules
        $scope.attachSamples = function () {
            var sampleIds = [];
            if ($scope.vm.emailScheduleSamples.length==0)
                toastService.showError('No samples are chosen to assign');
            else {
                angular.forEach($scope.vm.emailScheduleSamples, function (value) {
                    sampleIds.push(JSON.parse(value).id);
                });
                appService.attachSamplesToEmailSchedule(sampleIds, emailScheduleId).then(function () {
                    toastService.show('Samples successfully attached to email schedules');
                    $window.location.href = '#/app/gaps/' + surveyId + '/surveyDetails';
                   });
            }
        };

        //refresh email count data
        $scope.refreshEmailCount = function() {
            appService.getEmailsForScheduleStatus($scope.vm.page, $scope.vm.count, surveyId, emailScheduleId).then(function(result) {
                $scope.vm.total = result.total;
                $scope.vm.sent = result.sent;
                $scope.vm.unSent = result.unsent;
            });
        };

        //get details of survey
        appService.getSurvey(surveyId).then(function(result) {
            $scope.vm.survey = result;
        });

        //add users to email schedule

        $scope.addUsers = function() {
            $scope.vm.user = '';
            modalService.open($scope, '/public/views/app/admin/modals/addUser.html');

            $scope.closeForm = function () {
                modalService.close();
            }
        };

        $scope.createUser = function() {
            appService.createUser(surveyId, emailScheduleId,$scope.vm.user).then(function(result) {
                modalService.close();
                toastService.show("Users added successfully.");
            },function(error) {
                toastService.showError(error.data.message);
            });
        };
    }]);;
angular.module('app')
    .controller('adminPlaceDashboardCtrl', [
        '$scope', 'appService', 'modalService', 'toastService',
        function ($scope, appService, modalService, toastService) {
            $scope.vm = {};
            $scope.vm.activeCountryId = '';
            $scope.vm.activeStateId = '';
            $scope.vm.activeCityId = '';
            $scope.vm.citiesForTiers = '';
            $scope.vm.countries = null;
            $scope.vm.getCountryData = 'starting';
            $scope.vm.getStateData = 'starting';
            $scope.vm.getCityData = 'starting';
            //get all countries
            appService.getCountries().then(function (result) {
                $scope.vm.countries = result.data;
                if ($scope.vm.countries.length === 0)
                    $scope.vm.getCountryData = 'noData';
            }, function(error) {
                $scope.vm.getCountryData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //get all states
            $scope.getStates = function (countryId) {
                //$scope.vm.activeStateId = '';
                $scope.vm.activeCountryId = countryId;
                $scope.vm.states = [];
                appService.getStates(countryId).then(function (result) {
                    $scope.vm.states = result.states;
                    if ($scope.vm.states.length === 0)
                        $scope.vm.getStateData = 'noData';
                }, function(error) {
                    $scope.vm.getStateData = 'requestFailed';
                    toastService.showError("There was some error while loading data. Please refresh the page again");
                });
            };
            //get all cities
            $scope.getCities = function (countryId, stateId) {
                $scope.vm.activeStateId = stateId;
                $scope.vm.cities = [];
                appService.getCities(countryId, stateId).then(function (result) {
                    $scope.vm.cities = result.cities;
                    if ($scope.vm.cities.length === 0)
                        $scope.vm.getCityData = 'noData';
                }, function(error) {
                    $scope.vm.getCityData = 'requestFailed';
                    toastService.showError("There was some error while loading data. Please refresh the page again");
                });
            };
            
            //add a new country
            $scope.addCountryDialog = function () {
                $scope.vm.name = '';
                modalService.open($scope, '/public/views/app/admin/modals/addCountry.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.addCountry = function () {
                appService.addCountry($scope.vm.name).then(function () {
                    appService.getCountries().then(function (result) {
                        $scope.vm.countries = result.data;
                    });
                    toastService.show("Country Added  Successfully");
                    modalService.close();
                });
            };
            //edit a country
            $scope.editCountryDialog = function (country) {
                $scope.vm.country = country;
                $scope.vm.countryName = country.name;
                modalService.open($scope, '/public/views/app/admin/modals/editCountry.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.editCountry = function () {
                appService.editCountry($scope.vm.country.id, $scope.vm.countryName).then(function () {
                    modalService.close();
                    toastService.show("Country Edited successfully.");
                    appService.getCountries($scope.vm.page, $scope.vm.count).then(function (result) {
                        $scope.vm.countries = result.data;
                    });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
            //add a new state
            $scope.addStateDialog = function () {
                $scope.vm.stateName = '';
                $scope.vm.countryId = '';
                modalService.open($scope, '/public/views/app/admin/modals/addState.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.addState = function () {
                appService.addState($scope.vm.countryId, $scope.vm.stateName).then(function () {
                    appService.getStates($scope.vm.countryId).then(function(result) {
                        $scope.vm.states = result.states;
                    });
                    toastService.show("State Added  Successfully");
                    modalService.close();
                });
            };
            //edit a state
            $scope.editStateDialog = function (state) {
                $scope.vm.state = state;
                $scope.vm.stateName = state.name;
                modalService.open($scope, '/public/views/app/admin/modals/editState.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.editState = function () {
                appService.editState($scope.vm.state.countryId, $scope.vm.state.id, $scope.vm.stateName).then(function () {
                    modalService.close();
                    toastService.show("State Edited Successfully");
                    appService.getStates($scope.vm.activeCountryId).then(function (result) {
                        $scope.vm.states = result.states;
                });
                   }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
            //add a new city
            $scope.addCityDialog = function () {
                $scope.vm.cityName = '';
                $scope.vm.countryId = '';
                $scope.vm.stateId = '';
                $scope.vm.tier = '';
                modalService.open($scope, '/public/views/app/admin/modals/addCity.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.addCity = function () {

                appService.addCity($scope.vm.countryId, $scope.vm.stateId, $scope.vm.cityName,$scope.vm.tier).then(function () {
                    appService.getCities($scope.vm.countryId,$scope.vm.stateId).then(function(result) {
                        $scope.vm.cities = result.cities;
                    });
                    toastService.show("City Added Successfully");
                    modalService.close();
                });
            };
            //edit a city
            $scope.editCityDialog = function (city) {
                $scope.vm.city = city;
                $scope.vm.cityName = city.name;
                $scope.vm.tier = city.tier;
                modalService.open($scope, '/public/views/app/admin/modals/editCity.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.editCity = function () {
                appService.editCity($scope.vm.city.state.countryId, $scope.vm.city.state.id, $scope.vm.city.id, $scope.vm.cityName,$scope.vm.tier).then(function () {
                    modalService.close();
                    toastService.show("City Edited Successfully");
                    appService.getCities($scope.vm.city.state.countryId,$scope.vm.city.stateId).then(function(result) {
                        $scope.vm.cities = result.cities;
                    });
                   }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
        }
    ]);


;
angular.module('app')
    .controller('adminMessageDashboardCtrl', [
        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService',
    function ($scope, localStorageService, $state, appService, modalService, toastService) {
        $scope.vm = {};
        $scope.vm.page = 1;
        $scope.vm.queryType = '';
        $scope.vm.queryStatus = '';
        $scope.vm.email = '';
        $scope.vm.getMessageData = 'starting';
        $scope.action = function (event) {
            if (event.which === 13) {
                event.preventDefault();
                $scope.filterMessages();
            }
        };
        //get query Types
        appService.getQueryTypes().then(function (result) {
            $scope.vm.queryTypes = result.values;
        });
        //get query statuses
        appService.getQueryStatus().then(function (result) {
            $scope.vm.queryStatuses = result.values;
        });
        //get initial messages
        appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType,$scope.vm.queryStatus, $scope.vm.email).then(function (result) {
            $scope.vm.messages = result;
            if ($scope.vm.messages.data.length === 0)
                $scope.vm.getMessageData = 'noData';
        }, function(error) {
            $scope.vm.getMessageData = 'requestFailed';
            toastService.showError("There was some error while loading data. Please refresh the page again");
        });
        $scope.filterMessages = function () {
            appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType,$scope.vm.queryStatus, $scope.vm.email).then(function (result) {
                $scope.vm.messages = result;
            });
        };
        $scope.pageChanged = function () {
            appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType,$scope.vm.queryStatus, $scope.vm.email).then(function (result) {
                $scope.vm.messages = result;
            });
        };
        //view message body
        $scope.viewMessageBody = function (message) {
            $scope.vm.message = message;
            modalService.open($scope, '/public/views/app/admin/modals/viewMessageBody.html');
        };
        $scope.markResolved = function (id) {
            appService.markMessageResolved(id).then(function () {
                toastService.show("Message marked resolved successfully");
                appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType, $scope.vm.queryStatus,$scope.vm.email).then(function (result) {
                    $scope.vm.messages = result;
                });
            });
        };
        //clear filter
        $scope.clearFilters = function () {
            $scope.vm.page = 1;
            $scope.vm.queryType = '';
            $scope.vm.queryStatus = '';
            $scope.vm.email = '';
            appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType, $scope.vm.email).then(function (result) {
                $scope.vm.messages = result;
            });
        };
    }]);;
angular.module('app')
.controller('adminHelpDashboardCtrl', ['$scope', '$location', '$anchorScroll',
  function ($scope, $location, $anchorScroll) {
      $scope.gotoTop = function () {
         $location.hash('top');
          $anchorScroll();
      };
  }]);






//angular.module('app')
//    .controller('adminHelpDashboardCtrl', [
//        '$scope', 'localStorageService', '$state', 'appService', 'modalService', 'toastService',
//    function ($scope, localStorageService, $state, appService, modalService, toastService) {
//        $scope.vm = {};
//        $scope.vm.page = 1;
//        $scope.vm.queryType = '';
//        $scope.vm.queryStatus = '';
//        $scope.vm.email = '';
//        //get query Types
//        appService.getQueryTypes().then(function (result) {
//            $scope.vm.queryTypes = result.values;
//        });
//        //get query statuses
//        appService.getQueryStatus().then(function (result) {
//            $scope.vm.queryStatuses = result.values;
//        });
//        //get initial messages
//        appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType, $scope.vm.email).then(function (result) {
//            $scope.vm.messages = result;
//        });
//        $scope.filterMessages = function () {
//            appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType, $scope.vm.email).then(function (result) {
//                $scope.vm.messages = result;
//            });
//        };
//        $scope.pageChanged = function () {
//            appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType, $scope.vm.email).then(function (result) {
//                $scope.vm.messages = result;
//            });
//        };
//        //view message body
//        $scope.viewMessageBody = function (message) {
//            $scope.vm.message = message;
//            modalService.open($scope, '/public/views/app/admin/modals/viewMessageBody.html');
//        };
//        $scope.markResolved = function (id) {
//            appService.markMessageResolved(id).then(function () {
//                toastService.show("Message marked resolved successfully");
//                appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType, $scope.vm.email).then(function (result) {
//                    $scope.vm.messages = result;
//                });
//            });
//        };
//        //clear filter
//        $scope.clearFilters = function () {
//            $scope.vm.page = 1;
//            $scope.vm.queryType = '';
//            $scope.vm.email = '';
//            appService.filterMessages($scope.vm.page, $scope.count, $scope.vm.queryType, $scope.vm.email).then(function (result) {
//                $scope.vm.messages = result;
//            });
//        };
//    }]);;
//angular.module('app')
//.controller('adminLinksForSurveyCtrl', ['$scope', '$window', 'appService', '$stateParams',
//  function ($scope,$window,appService,$stateParams) {
//      $scope.vm = {};
//      var surveyId = $stateParams.surveyId;
//      appService.getUniqueLinks(surveyId).then(function (result) {
//          $scope.vm.uniqueLinks = result.data;
//      });
//
//  }]);
function adminLinksForSurveyCtrl($scope,$stateParams,appService) {
    $scope.vm = {};
    $scope.vm.page = 1;
    $scope.vm.count = 10;
    var surveyId = $stateParams.surveyId;
    appService.getUniqueLinks($scope.vm.page,$scope.vm.count,surveyId).then(function(result) {
        $scope.vm.uniqueLinks = result;
    });
    $scope.pageChanged=function() {
        appService.getUniqueLinks($scope.vm.page,$scope.vm.count,surveyId).then(function (result) {
            $scope.vm.uniqueLinks = result;
        });
    }
}
adminLinksForSurveyCtrl.$inject = ['$scope','$stateParams','appService'];
angular.module('app').controller('adminLinksForSurveyCtrl', adminLinksForSurveyCtrl);;
//angular.module('app')
//.controller('adminReportsForSurveyCtrl', ['$scope', '$window', 'appService', '$stateParams',
//  function ($scope,$window,appService,$stateParams) {
//      $scope.vm = {};
//      var surveyId = $stateParams.surveyId;
//      appService.getUniqueReports(surveyId).then(function (result) {
//          $scope.vm.reports = result;
//      });
//
//  }]);
function adminReportsForSurveyCtrl($scope, $stateParams, appService) {
    $scope.vm = {};
    var surveyId = $stateParams.surveyId;

  appService.getUniqueReports(surveyId).then(function(result) {
        $scope.vm.reports = result;
        if ($scope.vm.reports.survey.surveyType === 0)
            $scope.vm.reports.survey.surveyType = 'Open';
        else
            $scope.vm.reports.survey.surveyType = 'Closed';
        if ($scope.vm.reports.survey.isPaused === false)
            $scope.vm.reports.survey.isPaused = '';
        else
            $scope.vm.reports.survey.isPaused = 'Paused';
      if ($scope.vm.reports.survey.closeDate !== null)
          $scope.vm.reports.survey.closeDate = moment($scope.vm.reports.survey.closeDate).format('YYYY-MM-DD hh:mm:ss a');
      else
          $scope.vm.reports.survey.closeDate = '';
          
        console.log($scope.vm.reports);
        $scope.vm.avg = $scope.vm.reports.attemptDurationStats.avg;
        $scope.vm.minutesAvg = parseInt(($scope.vm.avg) / 60);
        $scope.vm.secondsAvg = parseInt(($scope.vm.avg) % 60);
        $scope.vm.max = $scope.vm.reports.attemptDurationStats.max;
        $scope.vm.minutesMax = parseInt(($scope.vm.max) / 60);
        $scope.vm.secondsMax = parseInt(($scope.vm.max) % 60);
        $scope.vm.min = $scope.vm.reports.attemptDurationStats.min;
        $scope.vm.minutesMin = parseInt(($scope.vm.min) / 60);
        $scope.vm.secondsMin = parseInt(($scope.vm.min) % 60);

        $scope.vm.attemptsByDay = $scope.vm.reports.attemptsByDay;
        $scope.vm.emailSentByDay = $scope.vm.reports.emailSentByDay;
      $scope.vm.emailCount = 0;
        for (var a in $scope.vm.emailSentByDay) {
            $scope.vm.emailCount = $scope.vm.emailCount + $scope.vm.emailSentByDay[a];
        }
        $scope.vm.finalEmailCount = $scope.vm.emailCount;

        $scope.vm.attemptCount = 0;
        for (var b in $scope.vm.attemptsByDay) {
            $scope.vm.attemptCount = $scope.vm.attemptCount + $scope.vm.attemptsByDay[b];
        }
        $scope.vm.finalAttemptCount = $scope.vm.attemptCount;
  });

  $scope.refreshSurveyReportCount = function () {

      appService.getUniqueReports(surveyId).then(function (result) {
          $scope.vm.reports = result;
          if ($scope.vm.reports.survey.surveyType === 0)
              $scope.vm.reports.survey.surveyType = 'open';
          else
              $scope.vm.reports.survey.surveyType = 'closed';
          if ($scope.vm.reports.survey.isPaused === false)
              $scope.vm.reports.survey.isPaused = '';
          else
              $scope.vm.reports.survey.isPaused = 'Paused';

          if ($scope.vm.reports.survey.closeDate !== null)
              $scope.vm.reports.survey.closeDate = moment($scope.vm.reports.survey.closeDate).format('YYYY-MM-DD hh:mm:ss a');
          else
              $scope.vm.reports.survey.closeDate = '';

         $scope.vm.avg = $scope.vm.reports.attemptDurationStats.avg;
          $scope.vm.minutesAvg = parseInt(($scope.vm.avg) / 60);
          $scope.vm.secondsAvg = parseInt(($scope.vm.avg) % 60);
          $scope.vm.max = $scope.vm.reports.attemptDurationStats.max;
          $scope.vm.minutesMax = parseInt(($scope.vm.max) / 60);
          $scope.vm.secondsMax = parseInt(($scope.vm.max) % 60);
          $scope.vm.min = $scope.vm.reports.attemptDurationStats.min;
          $scope.vm.minutesMin = parseInt(($scope.vm.min) / 60);
          $scope.vm.secondsMin = parseInt(($scope.vm.min) % 60);

          $scope.vm.attemptsByDay = $scope.vm.reports.attemptsByDay;
          $scope.vm.emailSentByDay = $scope.vm.reports.emailSentByDay;

      });

    };
    appService.getAttemptStatus(surveyId).then(function(result) {
        $scope.vm.attemptStatus = result;
    });
}
adminReportsForSurveyCtrl.$inject = ['$scope', '$stateParams', 'appService'];
angular.module('app').controller('adminReportsForSurveyCtrl', adminReportsForSurveyCtrl);;
'use strict';

angular.module('app')
    .controller('adminProfileDashboardCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', 'modalService',
        function ($scope, userService, $state, toastService, localStorageService, appService, modalService) {
            $scope.vm = {};
            var editProfileId = '';
            var deleteProfileId = '';
            $scope.vm.getProfileData = 'starting';
            //get all profiles
            appService.getProfiles().then(function (result) {
                $scope.vm.profiles = result.profiles;
                if ($scope.vm.profiles.length === 0)
                    $scope.vm.getProfileData = 'noData';
            }, function(error) {
                $scope.vm.getProfileData = 'requestFailed';
                toastService.showError("There was some error while loading data. Please refresh the page again");
            });
            //create profile
            $scope.createProfileDialog = function () {
                $scope.vm.name = '';
                $scope.vm.description = '';
                $scope.vm.displayOrder = '';
                modalService.open($scope, '/public/views/app/admin/modals/createProfile.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.createProfile = function () {
                appService.createProfile($scope.vm.name, $scope.vm.description, $scope.vm.displayOrder).then(function () {
                    modalService.close();
                    appService.getProfiles().then(function (result) {
                        $scope.vm.profiles = result.profiles;
                        toastService.show("Profile created successfully");
                    });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
            //edit profile
            $scope.editProfileDialog = function (profile) {
                $scope.vm.name = profile.name;
                $scope.vm.description = profile.description;
                $scope.vm.displayOrder = profile.displayOrder;
                editProfileId = profile.id;
                modalService.open($scope, '/public/views/app/admin/modals/editProfile.html');
                $scope.closeForm = function () {
                    modalService.close();
                }
            };
            $scope.editProfile = function () {
                appService.editProfile(editProfileId, $scope.vm.name, $scope.vm.description, $scope.vm.displayOrder).then(function () {
                    modalService.close();
                    appService.getProfiles().then(function (result) {
                        $scope.vm.profiles = result.profiles;
                        toastService.show("Profile edited successfully");
                    });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
            //delete profile
            $scope.deleteProfileDialog = function (profile) {
                deleteProfileId = profile.id;
                modalService.askConfirmation($scope, 'Are you sure you want to delete this profile ?', 'deleteProfile()');
            };
            $scope.deleteProfile = function () {
                appService.deleteProfile(deleteProfileId).then(function () {
                    modalService.close();
                    appService.getProfiles().then(function (result) {
                        $scope.vm.profiles = result.profiles;
                        toastService.show("Profile deleted successfully");
                    });
                }, function (error) {
                    toastService.showError(error.data.message);
                });
            };
        }
    ]);;
'use strict';
angular.module('app')
    .controller('adminProfileQuestionsCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', 'modalService', '$stateParams',
        function ($scope, userService, $state, toastService, localStorageService, appService, modalService, $stateParams) {
            $scope.vm = {};
            var idToBeDeleted = '';
            $scope.vm.profileQuestions = [];
            $scope.vm.profileId = $stateParams.profileId;
            //get questions
            appService.getQuestionsForProfile($scope.vm.profileId).then(function (result) {
                $scope.vm.profileQuestions = result.data;
            });
            //add question
            $scope.addQuestion = function () {
                $state.go('app.admin.createProfileQuestion', { 'profileId': $scope.vm.profileId });
            };
            //edit question
            $scope.editQuestion = function (questionId) {
                $state.go('app.admin.editProfileQuestion', { 'profileId': $scope.vm.profileId, 'questionId': questionId });
            };
            //question details
            $scope.questionDetails = function (questionId) {
                $state.go('app.admin.profileQuestionDetails', { 'profileId': $scope.vm.profileId, 'questionId': questionId });
            };
            $scope.deleteQuestionDialog = function (questionId) {
                idToBeDeleted = questionId;
                modalService.askConfirmation($scope, 'Are you sure you want to delete this question?', 'deleteQuestion()');
            };
            $scope.deleteQuestion = function () {
                appService.deleteProfileQuestion($scope.vm.profileId, idToBeDeleted).then(function () {
                    toastService.show("Question Deleted Successfully");
                    modalService.close();
                    appService.getQuestionsForProfile($scope.vm.profileId).then(function (result) {
                        $scope.vm.profileQuestions = result.data;
                    });
                });
            };
        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminProfileQuestionDetailsCtrl', [
        '$scope', '$state', 'toastService', 'appService', '$stateParams', 'modalService',
        function ($scope, $state, toastService, appService, $stateParams, modalService) {
            $scope.vm = {};
            var profileId = $stateParams.profileId;
            var questionId = $stateParams.questionId;
            appService.getProfileQuestion(profileId, questionId).then(function (result) {
                $scope.vm.profileQuestion = result.data;
            });
            //edit question
            $scope.editQuestion = function () {
                $state.go('app.admin.editProfileQuestion', { 'profileId': profileId, 'questionId': questionId });
            };
            $scope.goToQuestions = function () {
                $state.go('app.admin.profileQuestions', { 'profileId': profileId });
            };
        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminCreateProfileQuestionCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', '$stateParams',
        function ($scope, userService, $state, toastService, localStorageService, appService, $stateParams) {
            $scope.vm = {};
            $scope.vm.profileQuestion = {};
            $scope.vm.profileQuestion.isActive = true;
            var profileId = $stateParams.profileId;
            $scope.vm.profileQuestion.options = [{ value: '', hint: '', isActive: true, displayOrder: '' }];
            appService.getQuestionDisplayTypes().then(function (result) {
                $scope.vm.questionDisplayTypes = result.values;
            });
            $scope.addOption = function () {
               /* var temp = $scope.vm.profileQuestion.options[0].value.split('\n');
                //$scope.vm.profileQuestion.options = [];
                var i = 1;
                angular.forEach(temp, function (value) {
                    $scope.vm.profileQuestion.options.push({ value: value, hint: '', displayOrder: i,isActive:true });
                    i++;
                });*/
                
                               $scope.vm.profileQuestion.options.push({ value: '', hint: '', isActive: true, displayOrder: '' });
            }
            $scope.createProfileQuestion = function () {
                appService.createProfileQuestion(profileId, $scope.vm.profileQuestion).then(function () {
                    toastService.show("Question created successfully");
                    $state.go('app.admin.profileQuestions', { 'profileId': profileId });
                }, function (err) {
                    toastService.showError(err.data.error_description);
                });
            };

        }
    ]);;
'use strict';

angular.module('app')
    .controller('adminEditProfileQuestionCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService', '$stateParams',
        function ($scope, userService, $state, toastService, localStorageService, appService, $stateParams) {
            $scope.vm = {};
            var profileId = $stateParams.profileId;
            var questionId = $stateParams.questionId;
            appService.getQuestionDisplayTypes().then(function (result) {
                $scope.vm.questionDisplayTypes = result.values;
            });
            appService.getProfileQuestion(profileId, questionId).then(function (result) {
                $scope.vm.profileQuestion = result.data;
                $scope.vm.profileQuestion.displayType = $scope.vm.profileQuestion.displayType.toString();
            });
            $scope.addOption = function () {
                //var temp = $scope.vm.profileQuestion.options[0].value.split(',');
                //$scope.vm.profileQuestion.options = [];
                //var i = 1;
                //angular.forEach(temp, function (value) {
                //    $scope.vm.profileQuestion.options.push({ value: value, hint: '', displayOrder: i, isActive: true });
                //    i++;
                //});
                $scope.vm.profileQuestion.options.push({ value: '', hint: '', isActive: true, displayOrder: '' });
            }
            //$scope.removeOption=function() {
            //    $scope.vm.profileQuestion.options.pop({ value: '', hint: '', isActive: true, displayOrder: '' });

            //}
            $scope.editProfileQuestion = function () {
                appService.editProfileQuestion(profileId, questionId, $scope.vm.profileQuestion).then(function () {
                    toastService.show("Question edited successfully");
                    $state.go('app.admin.profileQuestions', { 'profileId': profileId });
                }, function (err) {
                    toastService.showError("Please edit the profile question correctly");
                });
            };

        }
    ]);;
angular.module('app')
    .controller('adminNavCtrl', [
        '$scope', 'userService', '$state','$window',
        function($scope, userService, $state,$window) {
            $scope.vm = {};
            $scope.vm.profiles = [];
            //$scope.showProfileDashboard = function () {
            //    appService.getProfiles().then(function (result) {
            //        $scope.vm.profiles = result.profiles;
            //        $state.go('app.profileDashboard');
            //    });
            //};
            $scope.logout = function() {
                userService.logout();
                //.then(function () {
                $state.go('user.login');
//                $window.location.reload();

                //});
            };
        }
    ]);;
angular.module('app')
    .controller('adminHeaderCtrl', [
        '$scope', 'userService', '$state','$window',
        function($scope, userService, $state,$window) {
            $scope.vm = {};
            $scope.vm.toTitleCase = function (str) {
                return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
            }
            userService.getUserInfo().then(function(result) {
                $scope.vm.userInfo = result.basicProfile;
                $scope.vm.a = $scope.vm.toTitleCase($scope.vm.userInfo.firstName);
                $scope.vm.b = $scope.vm.toTitleCase($scope.vm.userInfo.lastName);

            });

            $scope.logout = function() {
                userService.logout();
                //.then(function () {
                $state.go('user.login');
                //                $state.go($state.current, {}, { reload: true });
                $window.location.reload();

            };

            $scope.openAdminNavbar = function () {
                var myE1 = angular.element(document.querySelector('#navigationbarMenu3'));
                myE1.removeClass('collapse');
                myE1.removeClass('in');
                myE1.addClass('collapse');
            };
        }
    ]);;
'use strict';

angular.module('app')
    .controller('signupTwoCtrl', [
        '$scope', 'userService', '$state', 'toastService', 'localStorageService', 'appService','$stateParams',
        function($scope, userService, $state, toastService, localStorageService, appService,$stateParams) {
            $scope.referralSources = {};

            userService.getReferralSources().then(function(result) {
                $scope.referralSources = result.values;
            });
            $scope.vm = {};
            $scope.vm.firstName = '';
            $scope.vm.lastName = '';
            $scope.vm.mobile = '';
            $scope.vm.gender = true;
            //            $scope.vm.dateOfBirth = ''; // moment('1985/01/ 01').format('YYYY/MM/DD');
            $scope.vm.dateOfBirth = '';
            $scope.vm.addressLine1 = '';
            $scope.vm.addressLine2 = '';
            $scope.vm.city = '';
            $scope.vm.state = '';
            $scope.vm.country = '';
            $scope.vm.pinCode = '';
            $scope.vm.acceptTerms = true;
            $scope.vm.referralSource = '';
            //get all countries
            appService.getCountries().then(function(result) {
                $scope.vm.countries = result.data;
            });
            //get states for country
            $scope.getStates = function() {
                appService.getStates($scope.vm.country).then(function(result) {
                    $scope.vm.states = result.states;
                });
            };
            //get cities
            $scope.getCities = function() {
                appService.getCities($scope.vm.country, $scope.vm.state).then(function(result) {
                    $scope.vm.cities = result.cities;
                });
            }
            $scope.vm.phoneVerified = localStorageService.get('phoneVerified');
            userService.getUserInfo().then(function(result) {
                $scope.vm.mobile = result.basicProfile.mobile;
//               $scope.vm.xyz= moment(result.basicProfile.dateOfBirth).format("YYYY-MM-DD");
                //                $scope.vm.b = moment().format("YYYY-MM-DD");

                $scope.vm.allowedDate = moment().subtract(15, 'years').format('YYYY-MM-DD');

            });
            $scope.signupStepTwo = function () {
                if ($scope.vm.dateOfBirth > $scope.vm.allowedDate)
                    toastService.showError('Your age must be greater than 15 to join this survey portal.');
                else {
                    userService.updateAccount($scope.vm).then(function() {
                        toastService.show('Successfully completed Registration');
                        var role = localStorageService.get('role');
                        if (role == 'panelist')
                            $state.go('app.panelist.profileDashboard');
                        else
                            $state.go('app.admin.dashboard', { 'role': role });
                    });
                }
            }
        }
    ]);
    //.directive('myDatepicker', function() {
    //        return {
    //            require: 'ngModel',
    //            templateUrl: '/public/views/app/common/signupTwo.html',
    //            link: function() {
    //                $(function() {
    //                    $('input[name="birthdate"]').daterangepicker({
    //                            singleDatePicker: true,
    //                            showDropdowns: true
    //                        },
    //                        function(start) {
    //                            var years = moment().diff(start, 'years');
    //                           // alert("You are " + years + " years old.");
    //                        });
    //                    });

    //            }
    //        }
    //    }
    //);
;
