/* Minification failed. Returning unminified contents.
(1,13): run-time error CSS1031: Expected selector, found '='
(1,13): run-time error CSS1025: Expected comma or open brace, found '='
(4,5): run-time error CSS1019: Unexpected token, found ')'
(5,20): run-time error CSS1031: Expected selector, found '='
(5,20): run-time error CSS1025: Expected comma or open brace, found '='
(64,16): run-time error CSS1030: Expected identifier, found '$'
(64,16): run-time error CSS1031: Expected selector, found '$'
(64,16): run-time error CSS1025: Expected comma or open brace, found '$'
(65,9): run-time error CSS1030: Expected identifier, found 'config('
(65,9): run-time error CSS1031: Expected selector, found 'config('
(65,9): run-time error CSS1025: Expected comma or open brace, found 'config('
(66,9): run-time error CSS1030: Expected identifier, found 'constant('
(66,9): run-time error CSS1031: Expected selector, found 'constant('
(66,9): run-time error CSS1025: Expected comma or open brace, found 'constant('
(67,9): run-time error CSS1030: Expected identifier, found 'run('
(67,9): run-time error CSS1031: Expected selector, found 'run('
(67,9): run-time error CSS1025: Expected comma or open brace, found 'run('
(96,9): run-time error CSS1030: Expected identifier, found 'constant('
(96,9): run-time error CSS1031: Expected selector, found 'constant('
(96,9): run-time error CSS1025: Expected comma or open brace, found 'constant('
(99,2): run-time error CSS1019: Unexpected token, found ')'
(100,9): run-time error CSS1030: Expected identifier, found 'constant('
(100,9): run-time error CSS1031: Expected selector, found 'constant('
(100,9): run-time error CSS1025: Expected comma or open brace, found 'constant('
(114,2): run-time error CSS1019: Unexpected token, found ')'
(115,9): run-time error CSS1030: Expected identifier, found 'constant('
(115,9): run-time error CSS1031: Expected selector, found 'constant('
(115,9): run-time error CSS1025: Expected comma or open brace, found 'constant('
(118,2): run-time error CSS1019: Unexpected token, found ')'
(120,9): run-time error CSS1030: Expected identifier, found 'value('
(120,9): run-time error CSS1031: Expected selector, found 'value('
(120,9): run-time error CSS1025: Expected comma or open brace, found 'value('
(120,76): run-time error CSS1019: Unexpected token, found ')'
(121,9): run-time error CSS1030: Expected identifier, found 'controller('
(121,9): run-time error CSS1031: Expected selector, found 'controller('
(121,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(206,9): run-time error CSS1030: Expected identifier, found 'controller('
(206,9): run-time error CSS1031: Expected selector, found 'controller('
(206,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(217,9): run-time error CSS1030: Expected identifier, found 'controller('
(217,9): run-time error CSS1031: Expected selector, found 'controller('
(217,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(287,9): run-time error CSS1030: Expected identifier, found 'controller('
(287,9): run-time error CSS1031: Expected selector, found 'controller('
(287,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(327,2): run-time error CSS1019: Unexpected token, found ')'
(333,9): run-time error CSS1030: Expected identifier, found 'controller('
(333,9): run-time error CSS1031: Expected selector, found 'controller('
(333,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(509,17): run-time error CSS1031: Expected selector, found '='
(509,17): run-time error CSS1025: Expected comma or open brace, found '='
(511,20): run-time error CSS1031: Expected selector, found '='
(511,20): run-time error CSS1025: Expected comma or open brace, found '='
(516,16): run-time error CSS1030: Expected identifier, found '$'
(516,16): run-time error CSS1031: Expected selector, found '$'
(516,16): run-time error CSS1025: Expected comma or open brace, found '$'
(517,13): run-time error CSS1030: Expected identifier, found 'config('
(517,13): run-time error CSS1031: Expected selector, found 'config('
(517,13): run-time error CSS1025: Expected comma or open brace, found 'config('
(519,13): run-time error CSS1030: Expected identifier, found 'controller('
(519,13): run-time error CSS1031: Expected selector, found 'controller('
(519,13): run-time error CSS1025: Expected comma or open brace, found 'controller('
(568,2): run-time error CSS1019: Unexpected token, found ')'
(571,13): run-time error CSS1030: Expected identifier, found 'directive('
(571,13): run-time error CSS1031: Expected selector, found 'directive('
(571,13): run-time error CSS1025: Expected comma or open brace, found 'directive('
(624,2): run-time error CSS1019: Unexpected token, found ')'
(626,13): run-time error CSS1030: Expected identifier, found 'directive('
(626,13): run-time error CSS1031: Expected selector, found 'directive('
(626,13): run-time error CSS1025: Expected comma or open brace, found 'directive('
(648,2): run-time error CSS1019: Unexpected token, found ')'
(650,13): run-time error CSS1030: Expected identifier, found 'factory('
(650,13): run-time error CSS1031: Expected selector, found 'factory('
(650,13): run-time error CSS1025: Expected comma or open brace, found 'factory('
(673,9): run-time error CSS1030: Expected identifier, found 'controller('
(673,9): run-time error CSS1031: Expected selector, found 'controller('
(673,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(743,2): run-time error CSS1019: Unexpected token, found ')'
(744,9): run-time error CSS1030: Expected identifier, found 'controller('
(744,9): run-time error CSS1031: Expected selector, found 'controller('
(744,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(757,9): run-time error CSS1030: Expected identifier, found 'controller('
(757,9): run-time error CSS1031: Expected selector, found 'controller('
(757,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(1370,9): run-time error CSS1030: Expected identifier, found 'controller('
(1370,9): run-time error CSS1031: Expected selector, found 'controller('
(1370,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(1543,9): run-time error CSS1030: Expected identifier, found 'controller('
(1543,9): run-time error CSS1031: Expected selector, found 'controller('
(1543,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(1544,28): run-time error CSS1030: Expected identifier, found '$'
(1544,28): run-time error CSS1031: Expected selector, found '$'
(1544,28): run-time error CSS1025: Expected comma or open brace, found '$'
(1546,10): run-time error CSS1031: Expected selector, found 'surveyStatisticsController('
(1546,10): run-time error CSS1025: Expected comma or open brace, found 'surveyStatisticsController('
(1681,9): run-time error CSS1030: Expected identifier, found 'controller('
(1681,9): run-time error CSS1031: Expected selector, found 'controller('
(1681,9): run-time error CSS1025: Expected comma or open brace, found 'controller('
(1699,9): run-time error CSS1030: Expected identifier, found 'directive('
(1699,9): run-time error CSS1031: Expected selector, found 'directive('
(1699,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(1714,2): run-time error CSS1019: Unexpected token, found ')'
(1716,9): run-time error CSS1030: Expected identifier, found 'directive('
(1716,9): run-time error CSS1031: Expected selector, found 'directive('
(1716,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(1734,9): run-time error CSS1030: Expected identifier, found 'directive('
(1734,9): run-time error CSS1031: Expected selector, found 'directive('
(1734,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(1792,3): run-time error CSS1019: Unexpected token, found ')'
(1794,9): run-time error CSS1030: Expected identifier, found 'filter('
(1794,9): run-time error CSS1031: Expected selector, found 'filter('
(1794,9): run-time error CSS1025: Expected comma or open brace, found 'filter('
(1814,9): run-time error CSS1030: Expected identifier, found 'directive('
(1814,9): run-time error CSS1031: Expected selector, found 'directive('
(1814,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(1848,2): run-time error CSS1019: Unexpected token, found ')'
(1851,9): run-time error CSS1030: Expected identifier, found 'directive('
(1851,9): run-time error CSS1031: Expected selector, found 'directive('
(1851,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(1860,2): run-time error CSS1019: Unexpected token, found ')'
(1862,9): run-time error CSS1030: Expected identifier, found 'directive('
(1862,9): run-time error CSS1031: Expected selector, found 'directive('
(1862,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(1897,2): run-time error CSS1019: Unexpected token, found ')'
(1898,9): run-time error CSS1030: Expected identifier, found 'filter('
(1898,9): run-time error CSS1031: Expected selector, found 'filter('
(1898,9): run-time error CSS1025: Expected comma or open brace, found 'filter('
(1903,2): run-time error CSS1019: Unexpected token, found ')'
(1905,9): run-time error CSS1030: Expected identifier, found 'directive('
(1905,9): run-time error CSS1031: Expected selector, found 'directive('
(1905,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(1958,2): run-time error CSS1019: Unexpected token, found ')'
(1960,9): run-time error CSS1030: Expected identifier, found 'directive('
(1960,9): run-time error CSS1031: Expected selector, found 'directive('
(1960,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(1982,2): run-time error CSS1019: Unexpected token, found ')'
(1984,9): run-time error CSS1030: Expected identifier, found 'directive('
(1984,9): run-time error CSS1031: Expected selector, found 'directive('
(1984,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(1998,2): run-time error CSS1019: Unexpected token, found ')'
(1999,9): run-time error CSS1030: Expected identifier, found 'directive('
(1999,9): run-time error CSS1031: Expected selector, found 'directive('
(1999,9): run-time error CSS1025: Expected comma or open brace, found 'directive('
(2000,30): run-time error CSS1030: Expected identifier, found '$'
(2000,30): run-time error CSS1031: Expected selector, found '$'
(2000,30): run-time error CSS1025: Expected comma or open brace, found '$'
(2002,14): run-time error CSS1031: Expected selector, found 'requestVerificationToken('
(2002,14): run-time error CSS1025: Expected comma or open brace, found 'requestVerificationToken('
(2009,9): run-time error CSS1030: Expected identifier, found 'factory('
(2009,9): run-time error CSS1031: Expected selector, found 'factory('
(2009,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2030,9): run-time error CSS1030: Expected identifier, found 'factory('
(2030,9): run-time error CSS1031: Expected selector, found 'factory('
(2030,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2052,9): run-time error CSS1030: Expected identifier, found 'factory('
(2052,9): run-time error CSS1031: Expected selector, found 'factory('
(2052,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2107,9): run-time error CSS1030: Expected identifier, found 'factory('
(2107,9): run-time error CSS1031: Expected selector, found 'factory('
(2107,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2175,9): run-time error CSS1030: Expected identifier, found 'factory('
(2175,9): run-time error CSS1031: Expected selector, found 'factory('
(2175,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2232,9): run-time error CSS1030: Expected identifier, found 'factory('
(2232,9): run-time error CSS1031: Expected selector, found 'factory('
(2232,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2258,9): run-time error CSS1030: Expected identifier, found 'factory('
(2258,9): run-time error CSS1031: Expected selector, found 'factory('
(2258,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2298,9): run-time error CSS1030: Expected identifier, found 'factory('
(2298,9): run-time error CSS1031: Expected selector, found 'factory('
(2298,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2323,9): run-time error CSS1030: Expected identifier, found 'factory('
(2323,9): run-time error CSS1031: Expected selector, found 'factory('
(2323,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2324,23): run-time error CSS1030: Expected identifier, found '$'
(2324,23): run-time error CSS1031: Expected selector, found '$'
(2324,23): run-time error CSS1025: Expected comma or open brace, found '$'
(2347,9): run-time error CSS1030: Expected identifier, found 'factory('
(2347,9): run-time error CSS1031: Expected selector, found 'factory('
(2347,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2371,9): run-time error CSS1030: Expected identifier, found 'factory('
(2371,9): run-time error CSS1031: Expected selector, found 'factory('
(2371,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(2668,9): run-time error CSS1030: Expected identifier, found 'factory('
(2668,9): run-time error CSS1031: Expected selector, found 'factory('
(2668,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(3021,9): run-time error CSS1030: Expected identifier, found 'factory('
(3021,9): run-time error CSS1031: Expected selector, found 'factory('
(3021,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(3022,25): run-time error CSS1030: Expected identifier, found '$'
(3022,25): run-time error CSS1031: Expected selector, found '$'
(3022,25): run-time error CSS1025: Expected comma or open brace, found '$'
(3088,9): run-time error CSS1030: Expected identifier, found 'factory('
(3088,9): run-time error CSS1031: Expected selector, found 'factory('
(3088,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(3114,9): run-time error CSS1030: Expected identifier, found 'factory('
(3114,9): run-time error CSS1031: Expected selector, found 'factory('
(3114,9): run-time error CSS1025: Expected comma or open brace, found 'factory('
(3115,20): run-time error CSS1030: Expected identifier, found '$'
(3115,20): run-time error CSS1031: Expected selector, found '$'
(3115,20): run-time error CSS1025: Expected comma or open brace, found '$'
(3116,10): run-time error CSS1031: Expected selector, found 'messageInterceptor('
(3116,10): run-time error CSS1025: Expected comma or open brace, found 'messageInterceptor('
 */
var mainApp = angular.module('mainApp', ['angularUtils.directives.dirPagination', 'ui.router', 'ngRoute', 'ngBootbox', 'ui.bootstrap', 'nouislider',
   'ngStorage']).config(function () {

   });
var configFunction = function ($stateProvider, $httpProvider, $locationProvider, $urlRouterProvider, ngBootbox, $breadcrumbProvider) {
    $httpProvider.defaults.cache = false;
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};
    }
    // disable IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
    $stateProvider

        .state('Error', {
            url: '/Error',
            data: { pageTitle: 'Error Page', displayName: 'Error Page' },
            views: {
                "MainMenu": {
                    templateUrl: '/Dashboard/Error'
                }
            }
        })
        
    .state('fillsurvey', {
        url: '/fillsurvey/{surveyID}/{firmContactID}',
        params: {
            firmContactID: { squash: true, value: null }
        },
        data: { pageTitle: 'Fill Survey', parent: ['surveyStatisticsList', 'moderatorSurveyData', 'surveyCalendar', 'Dashboard'], parentOfParent: 'moderatorSurveyList' },
        views: {
            "MainMenu": {
                templateUrl: '/SurveyPreview/Get'
            }
        }
    })
   
      .state('thankyou', {
          url: '/thankyou/{isAnonymous}',
          params: {
              isAnonymous: { value: null }
          },
          data: { pageTitle: 'Thank You', parent: 'fillsurvey' },
          views: {
              "MainMenu": {
                  templateUrl: '/SurveyPreview/ThankYou'
              }
          }
      })


         .state('unauthorized', {
             url: '/unauthorized/',
             data: { pageTitle: 'Unauthozied' },
             views: {
                 "MainMenu": {
                     templateUrl: '/SurveyPreview/Error'
                 }
             }
         });

    $urlRouterProvider.otherwise('/fillsurvey/');
    $httpProvider.interceptors.push("messageInterceptor");
};
configFunction.$inject = ['$stateProvider', '$httpProvider', '$locationProvider', '$urlRouterProvider'];
mainApp.config(configFunction);
mainApp.constant('surveyUrl', 'firmSurveyPreview');
mainApp.run(['$rootScope', '$state', '$stateParams', '$location', '$window', '$localStorage', '$sessionStorage',
function ($rootScope, $state, $stateParams, $location, $window, $localStorage, $sessionStorage) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if (toState.url == "/pending" || toState.url == "/reviewed") {
            $stateParams.status = toState.data.status;
            $rootScope.status = $stateParams.status;
        }
        $rootScope.$prevState = fromState;
        if ($rootScope.$prevState.name != undefined && $rootScope.$prevState.name != "") {
            $sessionStorage.prevStateName = $rootScope.$prevState.name;
        }
        else {
            $sessionStorage.prevStateName = $location.path().split('/')[1];
        }
        //console.log($rootScope.$prevState);
    });

    //$rootScope.$on("$locationChangeStart", function (event, next, current) {
    //    var fullUrl = next;
    //    if ((fullUrl.indexOf('/Survey/FillSurvey') !== -1) && (fullUrl.indexOf('#/fillsurvey/') == -1)
    //        && (fullUrl.indexOf('#/thankyou') == -1) && (fullUrl.indexOf('#/unauthorized/') == -1)) {
    //        $window.location.href = 'http://' + location.host;
    //    }
    //});

}]);
mainApp.constant('GlobalConfig', {
    SurveyURI: '/fillsurvey/',
    SurveyInfoURI: '/surveyinfo/'
});
mainApp.constant('GlobalQuestionType', {
    Sum: 29,
    Total: 30,
    Horizontal: 21,
    HorizontalNew: 34,
    Vertical: 22,
    Dynamic: 32,
    DynamicShell: 33,
    MultiChoice: 14,
    OpenTextSingleLine: 17,
    OpenTextMultiLine: 16,
    ContactNumber: 1,
    Date: 5,
    Information: 13
});
mainApp.constant('SurveyResult', {
    Success: 1,
    NotAuthrized: 2,
});

mainApp.value('yaNoUiSliderConfig', { step: 1, range: { min: 0, max: 10 } })
mainApp.controller("DashboardController", ['$scope', '$state', '$http', '$rootScope', '$location', '$stateParams', '$routeParams', '$ngBootbox', 'FirmFactory', 'SectionPreviewFactory', 'FirmSurveyFactory', 'GlobalConfig', 'DashboardFactory', '$sessionStorage', 'ScrollFactory',
    function ($scope, $state, $http, $rootScope, $location, $stateParams, $routeParams, $ngBootbox, FirmFactory, SectionPreviewFactory, FirmSurveyFactory, GlobalConfig, DashboardFactory, $sessionStorage, ScrollFactory) {
        $scope.title="Section Questions List"
        $scope.active = false;
        $scope.active1 = false;
        $scope.SectionPreview = null;
        $scope.SurveyDetails = null;
        $scope.FirmSurveyQuickStatus = null;
        $scope.SurveyDetailsTop3 = null;
        $scope.IsLoading = false;
        $scope.IsSurveyLoading = false;
        delete $sessionStorage.returnURL;
        $scope.NewSurvey = function (id) {
            $location.path('/SectionPreview/' + id);
            SetEditSurveyTealiumValuesForSurveyPortal($scope.Details.UserId, $scope.Details.SiteCode, $scope.Details.SiteName);
        }
        $scope.GetFirmsByID = function ()
        {
            FirmFactory.GetByID().then(function (d) {
                $scope.FirmList= d;
            });
            DashboardFactory.GetInfo().then(function (d) {
                $scope.Details = d;                
            });
        }
        $scope.GetFirmsByID();
       
        $scope.initialize = function () {
            $scope.IsLoading = true;
            SectionPreviewFactory.GetSection().then(function (modal) {
               
                $scope.SectionPreview = modal;
                $scope.IsLoading = false;
                //console.log("$scope.SectionPreview", $scope.SectionPreview);
            },
            function ( error )
            {
                $scope.IsLoading = false;
            } );
           
            //FirmSurveyFactory.GetSurveyByFirmId($rootScope.FirmId).then( function (model)
            //{
                
            //    $scope.SurveyDetails = model;
            //    console.log( '$scope.SurveyDetails =', $scope.SurveyDetails );
            //});
            $scope.IsSurveyLoading = true;
            //debugger;
            FirmSurveyFactory.GetOngoingSurveyDashboard({}).then(function (model) {
                $scope.SurveyDetails = model;
                $scope.IsSurveyLoading = false;
                ScrollFactory.ApplyScroll('dashboardListScroll', '', '4px');
                //console.log( '$scope.SurveyDetails =', $scope.SurveyDetails );
            },
            function (error) {
                $scope.IsSurveyLoading = false;
            });

            FirmSurveyFactory.GetFirmSurveyQuickStatus().then(function (model)
            {
                $scope.FirmSurveyQuickStatus = model;
                //console.log( '$scope.FirmSurveyQuickStatus =', $scope.FirmSurveyQuickStatus );
            });


        }
        $scope.initialize();
       

        $scope.OpenSurvey = function ( surveyId )
        {
            $sessionStorage.returnURL = $location.path();
			$rootScope.statusCode = "COM";
            var surveyURL = GlobalConfig.SurveyURI;
            $location.path(surveyURL + surveyId);
            SetTakeSurveyTealiumValuesForSurveyPortal($scope.Details.UserId, $scope.Details.SiteCode, $scope.Details.SiteName);
        }

        $scope.OpenLocationSection = function ()
        {
            $location.path( "/location" );
        }
    }]);


mainApp.controller("DashboardReturnController", ['$scope', '$state', '$http', '$rootScope', '$location', '$stateParams', '$routeParams', '$ngBootbox', '$templateCache',
    function ($scope, $state, $http, $rootScope, $location, $stateParams, $routeParams, $ngBootbox, $templateCache) {
        $templateCache.remove("/Dashboard/Dashboard");
        $scope.Return = function () {
            var returnURL = $("#hdnReturnURL").val();            
            window.location.href = "#/"+returnURL;
        }

        $scope.Return();

    }] );
mainApp.controller("HeaderbarController", ['$scope', '$state', '$http', '$rootScope', '$location', '$stateParams', 'masterFactory', '$routeParams', '$ngBootbox', 'ApplicationLanguageFactory', 'SurveyFactory', 'RespondentFactory',
function ($scope, $state, $http, $rootScope, $location, $stateParams, masterFactory, $routeParams, $ngBootbox, ApplicationLanguageFactory, SurveyFactory, RespondentFactory)
{
    $scope.ApplicationLanguageCode = "ENGLISH";
    $rootScope.ApplicationLanguageCode = "ENGLISH";

    

    $scope.initialize = function (isArabic, maxFileSizeInKB, validFileExtentions) {
        $rootScope.IsArabic = isArabic == "True" ? true : false;
        $rootScope.Lang = isArabic == "True" ? "ar" : "en";

        $rootScope.MaxFileSizeInKB = maxFileSizeInKB;
        if (validFileExtentions != '') {
            $rootScope.ValidFileExtentions = validFileExtentions.split(',');
        }

        $scope.EncryptedSurveyID = window.location.search;
        $scope.EncryptedSurveyID = $scope.EncryptedSurveyID.replace("?syd=", "");
        $ngBootbox.setLocale($rootScope.Lang);
        if ($scope.EncryptedSurveyID) {
            SurveyFactory.GetByEncryptedID($scope.EncryptedSurveyID).then(function (survey) {
                $rootScope.ThemeURL = survey.ThemeFolderName;
                
            });

            //RespondentFactory.SwitchLanguage('en').then(function (data) {

            //});
        }
       

        //ApplicationLanguageFactory.Get().then(function (languageList) {
        //    $scope.AppLanguages = languageList;
        //});
    }


    $scope.SwitchToEnglish = function () {
        window.location.href = "/RespondentAuthentication/SwitchLanguage/?selLang=en&currentState=" + window.location.href;
    }

    $scope.SwitchToArabic = function () {
        window.location.href = "/RespondentAuthentication/SwitchLanguage/?selLang=ar&currentState=" + window.location.href;
    }
    //$scope.initialize();


    $scope.OnLanguageChange = function () {
        if ($rootScope.ApplicationLanguageCode == "ENGLISH")
        {
            $scope.ApplicationLanguageCode = 'ARABIC';
            $rootScope.ApplicationLanguageCode = 'ARABIC';

            RespondentFactory.SwitchLanguage('ar').then(function (data) {

            });
        }
        else {
            $scope.ApplicationLanguageCode = 'ENGLISH';
            $rootScope.ApplicationLanguageCode = 'ENGLISH';

            RespondentFactory.SwitchLanguage('en').then(function (data) {

            });
        }

    }

}] );
mainApp.controller("LoginController", function ($scope, $http) {
    $scope.forgotPassword = function () {
        sendPassword($http);
    }

    function sendPassword($http) {
        var email_txt = $('.email_txt').val();
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        var validationSuccess = true;
        var isrivaledge = "n";
        var isLegalIntel = "n";
        if ((email_txt == "") || (!emailReg.test(email_txt))) {
            validationSuccess = false;
            if (validationSuccess == false) {
                $.alert("Please correct your email address.", "");
            }
        } else {
            var dataString = "";
            var urlForForgotPassword = '/api/User/SendPasswordResetLink?email=' + email_txt;
            startLoading("Sending reset password link");
            Request($http, urlForForgotPassword, "get", "",
                function (data, status, headers, config) {
                    stopLoading();
                    $.alert('An email has been sent to the address above with information on how to reset your password', '');
                },
            function (data, status, headers, config) {
                if (textStatus == 'timeout') {
                    stopLoading();
                    $.alert('The server did not respond in a timely fashion - please try again', 'Error');
                }
                else {
                    stopLoading();
                    $.alert('Email address not found - please try again with valid email', 'Error');
                }
            }
         );
        }
    }


});





mainApp.controller("MenuBarController", ['$scope', '$rootScope', '$location', '$state', 'SiteMenusFactory', 'masterFactory', '$filter', '$localStorage', '$sessionStorage', '$ngBootbox', '$uibModal', 
function ($scope, $rootScope, $location, $state, SiteMenusFactory, masterFactory, $filter, $localStorage, $sessionStorage, $ngBootbox, $uibModal) {
    $scope.menuList = null;
    $scope.GetMenuList = function () {
        SiteMenusFactory.GetMenuList().then(function (data) {
            if (data != null) {
                $scope.menuList = $filter("orderBy")(data, "Sequence");
            }
        });
    }    
    if ($("#OrgnizationID")) {
        $rootScope.OrgnizationID = $("#OrgnizationID").val();
        $scope.OrgnizationID = $("#OrgnizationID").val();
    }

    $scope.logOff = function () {
        try {
            var form = angular.element('#SurveyPreviewController').scope().$$childTail.surveyPreviewForm;
        }
        catch (error) {
        }
        if (form && form.$dirty) {
            var options = {
                message: "Your latest changes have not been saved. Do you still want to leave the page?",
                title: 'Do you want to leave this page?',
                className: 'custom-dialog',
                buttons: {
                    warning: {
                        label: "Leave",
                        className: "btn-default",
                        callback: function () {
                            masterFactory.LogOff().then(function (d) {
                                window.location = "/";
                            });
                        }
                    },
                    success: {
                        label: "Stay",
                        className: "btn-default",
                        callback: function () { }
                    }
                }
            };
            $ngBootbox.customDialog(options);
        }
        else {
            masterFactory.LogOff().then(function (d) {
                window.location = "/";
            });
        }
    }

    $scope.GetSiteInfo = function () {
        masterFactory.GetSiteInfo().then(function (d) {
            $rootScope.SiteId = d.ID;
            $rootScope.SiteName = d.SiteName;
            $rootScope.SiteHostName = d.SiteHostName;
        });
    }

    $scope.isActive = function (url) {
        var result = false;
        /*This condition is for no hierarchy of menu*/
        if (isActive(url)) {
            result = true;
            $rootScope.currentMenu = result;
        }
        /*This condition is for multiple level hierarchy of menu*/
        else {
            /*getting current path*/
            var currentPath = $location.path();
            var exactCurrentPath = "/" + currentPath.split('/')[1];
            /*extracting actual path*/
            if (exactCurrentPath.indexOf("#") != -1) {
                exactCurrentPath = exactCurrentPath.split('#')[0];
            }
            /*extracting getting current state*/
            var currentMenuList = $filter("filter")($state.get(), { url: exactCurrentPath });
            /*checking if state is exist*/
            if (currentMenuList != null && currentMenuList != undefined && currentMenuList.length > 0) {
                var currentMenu = currentMenuList[0];
                /*getting parent of current state*/
                if (currentMenu.data != undefined && currentMenu.data.parent != undefined && currentMenu.data.parent != '') {
                    var exactParentURL = "";
                    var parentUrl = "";
                    /*checking type of parent whether it is string or list*/
                    var type = typeof (currentMenu.data.parent);
                    /*This condition is for single level hierarchy of menu*/
                    if (type == "string") {
                        if ($sessionStorage.returnURL != undefined && $sessionStorage.returnURL != "") {
                            var exactReturnURL = "/"+$sessionStorage.returnURL.split('/')[1];
                            var returnStateList = $filter("filter")($state.get(), { url: exactReturnURL });
                            if (returnStateList.length > 0 && returnStateList[0].data && returnStateList[0].data.parent != undefined && returnStateList[0].data.parent != "") {
                                parentUrl = $state.get(returnStateList[0].data.parent).url;
                            }
                            else {
                                parentUrl = $sessionStorage.returnURL;
                            }
                        }
                        else {
                            parentUrl = $state.get(currentMenu.data.parent).url;
                        }
                    }
                    /*This condition is for if parent menus are multiple*/
                    else if (type == "object") {
                        var parentList = currentMenu.data.parent;
                        /*getting parent of parent for current path*/
                        var parentOfParent = currentMenu.data.parentOfParent;
                        /*checking prevstate is exist in parent of current menu*/
                        var exactParent = $filter("filter")(parentList, $sessionStorage.prevStateName);
                        if (exactParent.length > 0) {
                            objParent = exactParent[0];
                            /*checking if parent of parent for current menu is exist*/
                            if (parentOfParent != undefined && parentOfParent != '') {
                                /*getting parent of state which is mentioned in parent list of current menu*/
                                var objParentParent = $state.get(objParent).data.parent;
                                /*This condition is for two level hierarchy of menu*/
                                if (objParentParent != undefined && objParentParent != null && objParentParent != ''
                                    && objParentParent.toLowerCase() == parentOfParent.toLowerCase()) {
                                    parentUrl = $state.get(objParentParent).url;
                                }
                                    /*getting parent url on basis of parent list mentioned in current menu*/
                                else {
                                    parentUrl = $state.get(objParent).url;
                                }
                            }
                                /*getting parent url on basis of parent list mentioned in current menu*/
                            else {
                                parentUrl = $state.get(objParent).url;
                            }
                        }
                    }
                    if (parentUrl.indexOf("/") > -1) {
                        exactParentURL = "/" + parentUrl.split('/')[1];
                    }
                    var exactUrl = "/" + url.split('/')[1];
                    /*comparision between prev and current url*/
                    if (exactUrl.toLowerCase() == parentUrl.toLowerCase()) {
                        result = true;
                        $rootScope.currentMenu = result;
                    }
                }
            }
        }
        return result;
    }

    $scope.MannuallyResetPassword = function () {
        $scope.isForcedToResetPassword = false;
        $scope.ErrorMessage = "";
        $scope.Title = "Reset Password";
        $scope.isFormInvalid = false;
        $scope.showme = false;
        $scope.isNewUser = true;
        var modalInstance = $uibModal.open({
            backdrop: 'static',
            keyboard: false,
            templateUrl: '/RespondentAuthentication/ResetPassword',
            controller: 'ResetPasswordController',
            scope: $scope,
            windowClass: 'center-modal',
            resolve: {
            }
        });
        modalInstance.result.then(function () {
        }, function () {
        });
    }
    
    function isActive(destination) {
        return destination === $location.path();
    }

    $scope.GetSiteInfo();

}]);
var passwordApp = angular.module('passwordApp', ['angularUtils.directives.dirPagination', 'ui.router', 'ui.bootstrap', 'ngRoute', 'ngBootbox']);

var configFunction = function ($stateProvider, $httpProvider, $locationProvider, $urlRouterProvider, $urlMatcherFactory, ngBootbox) {
    $urlMatcherFactory.caseInsensitive(true);
    $urlMatcherFactory.strictMode(false);
};

configFunction.$inject = ['$stateProvider', '$httpProvider', '$locationProvider', '$urlRouterProvider', '$urlMatcherFactoryProvider'];
passwordApp.config(configFunction);

passwordApp.controller('mainController', function ($scope, $ngBootbox, PasswordFactory) {
    $scope.IsLoading = false;
    $scope.IsLoadingSave = false;
    $scope.newUser = {
        FirstName: '',
        LastName: '',
        Email: '',
        OldPassword: '',
        NewPassword: '',
        ConfirmPassword: '',
        Password: ''
    }
    $scope.incorrectPassword = false;

    $scope.initialize = function () {

    }

    $scope.initialize();

    $scope.Save = function (form) {
        $scope.IsLoadingSave = true;
        if (form.$valid) {
            $scope.newUser.Password = $scope.newUser.NewPassword;
            PasswordFactory.ResetPassword($scope.newUser).then(function (d) {
                if (d) {
                    $ngBootbox.alert("Your password is changed successfully, Please try login with new credentials.")
                    .then(function () {
                        window.location = '/login';
                    });
                }
                else {
                    $ngBootbox.alert("Invalid Credentials, Please try again!!")
                     .then(function () {
                         window.location = '/login';
                     });
                }
                $scope.IsLoadingSave = false;
            });
        }
        else {
            $scope.isFormInvalid = true;
            $scope.IsLoadingSave = false;
        }
    }

    $scope.Close = function () {
        $scope.showme = false;
    };
});


passwordApp.directive('strongPasswordMeter', function () {
    return {
        require: 'ngModel',
        link: function ($scope, $element, $attrs, ngModelCtrl) {
            $element.on('blur change keydown', function (evt) {
                $scope.$evalAsync(function ($scope) {
                    var pwd = $element.val();
                    $scope.passwordStrengthColor = "";

                    var hasUpperCase = /[A-Z]/.test(pwd);
                    var hasLowerCase = /[a-z]/.test(pwd);
                    var hasNumbers = /\d/.test(pwd);
                    var hasNonalphas = /\W/.test(pwd);
                    var characterGroupCount = hasUpperCase + hasLowerCase + hasNumbers + hasNonalphas;
                    if (characterGroupCount == 0) {
                        $scope.passwordStrength = '0%';
                        $scope.passwordStrengthColor = "#f5f5f5";
                    }
                    if (characterGroupCount == 1) {
                        $scope.passwordStrength = '25%';
                        $scope.passwordStrengthColor = "#dd4b39";
                    }
                    if (characterGroupCount == 2) {
                        $scope.passwordStrength = '50%';
                        $scope.passwordStrengthColor = "#f39c12";
                    }
                    if (characterGroupCount == 3) {
                        $scope.passwordStrength = '75%';
                        $scope.passwordStrengthColor = "#00c0ef";
                    }
                    if (characterGroupCount >= 4) {
                        if (pwd.length >= 8) {
                            $scope.passwordStrength = '100%';
                            $scope.passwordStrengthColor = "#00a65a";
                        }
                        else {
                            $scope.passwordStrength = '75%';
                            $scope.passwordStrengthColor = "#00c0ef";
                        }
                    }

                    if ((pwd.length >= 8) && (characterGroupCount >= 4)) {
                        ngModelCtrl.$setValidity('complexity', true);
                        return pwd;
                    }
                    else {
                        ngModelCtrl.$setValidity('complexity', false);
                        return undefined;
                    }
                });
            });
        }
    };
});

passwordApp.directive('passwordVerify', function () {
    return {
        require: 'ngModel',
        link: function ($scope, $element, $attrs, ngModelCtrl) {
            $element.on('blur change keydown', function (evt) {
                $scope.$evalAsync(function ($scope) {
                    var pwdA = $element.val();
                    var pwdB = $scope.$eval($attrs.passwordVerify);
                    if (pwdA == pwdB) {
                        $scope.resetPasswordForm.ConfirmPassword.$setValidity('pwdcomparison', true);
                        $scope.resetPasswordForm.NewPassword.$setValidity('pwdcomparison', true);
                        return pwdA;
                    }
                    else {
                        $scope.resetPasswordForm.ConfirmPassword.$setValidity('pwdcomparison', false);
                        $scope.resetPasswordForm.NewPassword.$setValidity('pwdcomparison', false);
                        return undefined;
                    }
                });
            });
        }
    };
});

passwordApp.factory('PasswordFactory', ['$http', '$q', function ($http, $q) {
    var PasswordFactory = {};

    PasswordFactory.ResetPassword = function (user) {
        var defer = $q.defer();
        $http.post('/api/Respondent/ResetForgottenPassword',
               JSON.stringify(user),
               {
                   headers: {
                       'Content-Type': 'application/json',
                   }
               }
           ).success(function (data) {
               defer.resolve(data);
           }).error(function (e) {
               defer.reject(e);
           });
        return defer.promise;
    }

    return PasswordFactory;

}]);
mainApp.controller('ResetPasswordController', function ($uibModal, $scope, $uibModalInstance, $rootScope, $stateParams, $ngBootbox, $filter, RespondentFactory) {
    $scope.IsLoading = false;
    $scope.IsLoadingSave = false;
    $scope.newUser = {
        FirstName: '',
        LastName: '',
        Email: '',
        OldPassword: '',
        NewPassword: '',
        ConfirmPassword: '',
        Password: ''
    }
    $scope.incorrectPassword = false;
    $scope.isPasswordChanged = false;

    $scope.initialize = function () {

    }

    $scope.initialize();

    $scope.Save = function (form) {
        $scope.IsLoadingSave = true;
        if (form.$valid) {
            RespondentFactory.ValidatePassword($scope.newUser.OldPassword)
            .then(function (d) {
                if (d) {
                    $scope.newUser.Password = $scope.newUser.NewPassword;
                    RespondentFactory.ResetPassword($scope.newUser).then(function (d) {
                        if (d) {
                            $scope.isPasswordChanged = d;
                        }
                        else {
                            $scope.ErrorMessage = "old password is incorrect!";
                        }
                        $scope.IsLoadingSave = false;
                    });
                }
                else {
                    $scope.isFormInvalid = true;
                    $scope.incorrectPassword = true;
                    $scope.IsLoadingSave = false;
                    $scope.ErrorMessage = "old password is incorrect!";
                }

            }, function () {
                $scope.IsLoadingSave = false;
            });
        }
        else {
            $scope.isFormInvalid = true;
            $scope.IsLoadingSave = false;
        }
    }

    $scope.Close = function () {
        $scope.showme = false;
        $uibModalInstance.dismiss('cancel');
    };

    $scope.CloseLogOut = function () {
        $scope.logOff();
        //$ngBootbox.confirm("Are you sure? Closing this will land you to the login page again.")
        //                    .then(function () {
        //                        $scope.logOff();
        //                    }, function () {
        //                        //on cancel
        //                    }
        //                    );
    };
});
mainApp.controller("SurveyErrorController", ['$scope', 'SurveyPreviewFactory', '$stateParams', 'DashboardFactory', 'QuestionTypeFactory', '$location', '$timeout', '$rootScope', function ($scope, SurveyPreviewFactory, $stateParams, DashboardFactory, QuestionTypeFactory, $location, $timeout, $rootScope) {
    $scope.ErrorMessage = "";
    $scope.Initialize = function () {
        $scope.IsLinkVisible = $rootScope.IsLinkVisibleOnError != undefined && $rootScope.IsLinkVisibleOnError != null ? $rootScope.IsLinkVisibleOnError : false;
        $scope.ErrorMessage = $rootScope.ErrorMessage;
        $rootScope.ErrorMessage = "";
        $rootScope.IsLinkVisibleOnError = undefined;
    }

   
}]);


mainApp.controller("SurveyPreviewController", ['$scope', '$location', '$ngBootbox', '$state', '$stateParams', 'DashboardFactory', 'SurveyPreviewFactory', 'QuestionTypeFactory', 'GlobalQuestionType', 'DashboardFactory', 'SurveyResult', '$rootScope', '$state',
function ($scope, $location, $ngBootbox, $state, $stateParams, DashboardFactory, SurveyPreviewFactory, QuestionTypeFactory,  GlobalQuestionType, DashboardFactory, SurveyResult, $rootScope, $state)
{
    $scope.SurveyPreview = null;
   
    $rootScope.loaderColor = 'white';
    $scope.QuestionTypeList = null;
    $scope.SelectedPageIndex = 0;
    $scope.PercentageCompelete = 0;
    $scope.IsLoading = false;
    $scope.IsInitialized = false;
    $scope.surveyTokenID = '';
    $scope.DynamicQuestionType = '';
    $scope.IsPermitToNavigate = false;
    $scope.DynamicQuestionTypeID = GlobalQuestionType.Dynamic;
    $scope.DynamicShellQuestionTypeID = GlobalQuestionType.DynamicShell;
    $scope.VerticalGridQuestionType = GlobalQuestionType.Vertical;
    $scope.HorizontalGridQuestionType = GlobalQuestionType.Horizontal;
    $scope.HorizontalNewGridQuestionType = GlobalQuestionType.HorizontalNew;
    $scope.GlobalQuestionType = GlobalQuestionType;
    $scope.lastQuestionNumber = 0;
    $scope.PreviousQuestionNumber = 0;
    $scope.SetTealiumValues = function (pageName) {
        //DashboardFactory.GetInfo().then(function (d) {
        //    $scope.Details = d;
        //    SetTealiumValuesForSurveyPortal($scope.Details.UserId, $scope.Details.SiteCode, $scope.Details.SiteName, pageName);
        //});
    }

    $scope.SwitchToEnglish = function () {
        window.location.href = "/RespondentAuthentication/SwitchLanguage/?selLang=en&currentState=" + window.location.href;
    }

    $scope.SwitchToArabic = function () {
        window.location.href = "/RespondentAuthentication/SwitchLanguage/?selLang=ar&currentState=" + window.location.href;
    }

    $scope.initialize = function (currentLang)
    {
        
        $scope.IsInitialized = false;
        $scope.PreviousQuestionNumber = 0;
        $scope.surveyID = $stateParams.surveyID;
        $scope.IsInitializing = true;
        $scope.DigitalFileUploadPath = '/SurveyPreview/GetDigitalFile?fileLocation=' + $("#hdnDFU").val();
        if (currentLang.length > 0) {
            $ngBootbox.setLocale(currentLang);
        }
        //SurveyPreviewFactory.GetImageDimensions().then(function (imgDimensions) {
        //    $scope.ImageDimension = imgDimensions;
        //    $rootScope.ImageDimension = imgDimensions;
           
        //});

        if ($scope.surveyID == null || $scope.surveyID == undefined || $scope.surveyID =='') {
            $scope.surveyID = $("#encryptedSurveyID").val();
            $scope.surveyTokenID = $("#encryptedSurveyTokenID").val();
            if ($scope.surveyTokenID == null || $scope.surveyTokenID == undefined || $scope.surveyTokenID == '') {
                $scope.surveyTokenID = '';
            }
        }
        $scope.IsPreview = $("#isPreviewID").val();
        $scope.IsProtectedSurvey = $("#isProtectedSurveyID").val();


        $scope.departmentRespondentID = $stateParams.departmentRespondentID;
        if ($scope.departmentRespondentID == null || $scope.departmentRespondentID == undefined || $scope.departmentRespondentID == '') {
            $scope.departmentRespondentID = "";
        }

        try{
            //$scope.SetTealiumValues("fill survey"); already called a Tealium
            SurveyPreviewFactory.GetByID($scope.surveyID, $scope.departmentRespondentID, $scope.IsPreview, $scope.IsProtectedSurvey).then(function (surveyData) {
                $scope.SurveyPreview = surveyData;
                $("#dvstyle").html($scope.SurveyPreview.survey.CssStype);
                $rootScope.LanguageCode = $scope.SurveyPreview.survey.LanguageCode;
                if ($scope.SurveyPreview && $scope.SurveyPreview.survey && $scope.SurveyPreview.survey.LogoUrl) {
                    $scope.SurveyPreview.survey.LogoUrl = '/SurveyPreview/GetDigitalFile?fileLocation=' + $scope.SurveyPreview.survey.LogoUrl
                    $rootScope.SurveyLogoUrl = $scope.SurveyPreview.survey.LogoUrl;
                }
                
                $rootScope.CultureDepartmentName = $scope.SurveyPreview.DepartmentName;
                $rootScope.CultureDepartmentLogo = $scope.SurveyPreview.DepartmentLogo;
                $rootScope.CultureDepartmentHeaderText = $scope.SurveyPreview.DepartmentHeaderText;
                $rootScope.CultureDepartmentFooterText = $scope.SurveyPreview.DepartmentFooterText;
               
                if ($scope.SurveyPreview.Result == SurveyResult.NotAuthrized) {
                    $rootScope.ErrorMessage = $scope.SurveyPreview.ErrorMessage;
                    $location.path('/unauthorized/');
                }
                else if ($scope.SurveyPreview.FirmSurveyStatus == 2) {
                    $scope.IsInitializing = false;
                    $rootScope.ErrorMessage = "Survey response has been submitted.";
                    $location.path('/unauthorized/');
                    //$location.path('/surveyinfo/' + $scope.surveyID);
                }
                else if ($scope.SurveyPreview.FirmSurveyStatus == 4) {
                    $scope.IsInitializing = false;
                    $rootScope.ErrorMessage = "Survey response has been approved.";
                    //$location.path('/surveyinfo/' + $scope.surveyID);
                    $location.path('/unauthorized/');
                }
                else if ($scope.SurveyPreview.FirmSurveyStatus == 3) {
                    $scope.IsInitializing = false;
                    $rootScope.ErrorMessage = "Survey is expired.";
                    //$location.path('/surveyStatisticsList');
                    $location.path('/unauthorized/');
                }
                else if ($scope.SurveyPreview.FirmSurveyStatus == 99) {
                    $scope.IsInitializing = false;
                    $rootScope.ErrorMessage = "Unable to process your request, please contact to admin.";
                    //$location.path('/surveyStatisticsList');
                    $location.path('/unauthorized/');
                }
                $scope.surveyTokenID = $scope.SurveyPreview.SurveyTokenDetail.Token;
                $rootScope.ThemeID = $scope.SurveyPreview.survey.ThemeID;
                $rootScope.ThemeURL = $scope.SurveyPreview.survey.ThemeFolderName;

                //alert($scope.SurveyPreview.survey.ThemeFolderName.indexOf("DubaiPolice_Green"))
                if ($scope.SurveyPreview.survey.ThemeFolderName.indexOf("DubaiPolice_Green") > -1) {
                    $rootScope.isDPTheme = true;
                }
                else {
                    $rootScope.isDPTheme = false;
                }

                $("#surveyLogoElement").attr("src", $scope.SurveyPreview.survey.LogoUrl);
                $("#SurveyNameElement").text($scope.SurveyPreview.survey.SurveyName);
                $scope.SelectedPageIndex = 0;
                QuestionTypeFactory.GetFillList().then(function (data) {
                    $scope.QuestionTypeList = data;
                    $scope.DynamicQuestionType = $scope.QuestionTypeList.filter(function (element) {
                        return element.ID == $scope.DynamicShellQuestionTypeID;
                    });
                    $scope.DynamicQuestionType = $scope.DynamicQuestionType[0];
                    $scope.IsInitializing = false;
                    UpdateDynamicHTML();
                    $scope.UpdateNextPageQuestionNumber();
                    $scope.IsInitialized = true;
                    //QuestionTypeFactory.GetDynamicQuestionTypeShell().then(function (data) {
                    //    $scope.DynamicQuestionType = data;
                       
                    //});
                   
                },
                function () {
                    $scope.IsInitializing = false;
                    $location.path('/Dashboard');
                    $scope.IsInitialized = true;
                });
                SurveyPreviewFactory.GetSurveyProgress($scope.SurveyPreview.survey.ID, $scope.SurveyPreview.SurveyPagePreviewList[0].Page.ID).then(function (data) {
                    $scope.PercentageCompelete = data;
                    $scope.PercentageCompelete = Math.round($scope.PercentageCompelete);

                });

            },
            function () {
                $scope.IsInitializing = false;
                $location.path('/unauthorized');
            });
            
        }
        catch (error) {
            console.log('Please resolve the error: ', error);
            $scope.IsInitialized = true;
        }
    }

    $scope.PreviousPage = function ()
    {
        $scope.IsLoading = true;
        $scope.SurveyPreview.FirmContactIDEncrypted = $scope.departmentRespondentID;
        SurveyPreviewFactory.GetPreviousPage($scope.SurveyPreview, $scope.SurveyPreview.SurveyTokenDetail.Token).then(function (data)
        {
            $scope.SurveyPreview = data;
            if ($scope.SurveyPreview.survey.Result == SurveyResult.NotAuthrized) {
                $location.path('/unauthorized/');
            }
            UpdateDynamicHTML();
            $scope.UpdatePreviousPageQuestionNumber();
            SurveyPreviewFactory.GetSurveyProgress( $scope.SurveyPreview.survey.ID, $scope.SurveyPreview.SurveyPagePreviewList[0].Page.ID ).then( function ( data )
            {
                $scope.PercentageCompelete = data;
                $scope.IsLoading = false;
                $scope.PercentageCompelete = Math.round( $scope.PercentageCompelete );
                
            },
            function ( error )
            {
                $scope.IsLoading = false;
            } );
        },
        function ( error )
        {
            $scope.IsLoading = false;
        } );
    }

    $scope.NextPage = function ( form )
    {
        $scope.IsFormInvalid = false;
        if ( form.$valid )
        {
            $scope.IsLoading = true;
            form.$setPristine();
            $scope.SurveyPreview.FirmContactIDEncrypted = $scope.departmentRespondentID;
            SurveyPreviewFactory.Save($scope.SurveyPreview, $scope.SurveyPreview.SurveyTokenDetail.Token).then(function (data)
            {
                $scope.SurveyPreview = data;
                $scope.PreviousQuestionNumber = $scope.lastQuestionNumber;
                if ($scope.SurveyPreview.survey.Result == SurveyResult.NotAuthrized) {
                    $location.path('/unauthorized/');
                }
                try{
                    SetTakeSurveyTealiumValuesForSurveyPortal($scope.Details.UserId, $scope.Details.SiteCode, $scope.Details.SiteName);
                }
                catch (error) {

                }
                UpdateDynamicHTML();
                $scope.UpdateNextPageQuestionNumber();
                SurveyPreviewFactory.GetSurveyProgress( $scope.SurveyPreview.survey.ID, $scope.SurveyPreview.SurveyPagePreviewList[0].Page.ID ).then( function ( data )
                {
                    $scope.PercentageCompelete = data;
                    $scope.IsLoading = false;
                    $scope.PercentageCompelete = Math.round( $scope.PercentageCompelete );

                    if ( $scope.SurveyPreview.ProfileStats != null )
                    {
                        $scope.SurveyPreview.ProfileStats.Percentage = Math.round( $scope.SurveyPreview.ProfileStats.Percentage );
                    }
                   
                    
                },
                function ( error )
                {
                    $scope.IsLoading = false;
                } );

            },
            function (error)
            {
                $scope.IsLoading = false;
            } );
        }
        else
        {
            $scope.IsFormInvalid = true;
        }
      
    }

    $scope.SubmitPage = function (form)
    {
        $scope.IsLoading = false;
        $scope.IsFormInvalid = false;
        if ( form.$valid )
        {
            
            $ngBootbox.confirm($scope.PageMessage.AfterSubmitResponseChange)
            .then( function ()
            {
                $scope.IsLoading = true;
                $scope.SurveyPreview.FirmContactIDEncrypted = $scope.departmentRespondentID;
                SurveyPreviewFactory.Save($scope.SurveyPreview, $scope.surveyTokenID).then(function (data)
                {
                    SurveyPreviewFactory.SubmitSurvey($scope.SurveyPreview.survey.ID, $scope.surveyTokenID, $scope.departmentRespondentID, $scope.SurveyPreview.survey.SurveyName).then(function (data)
                    {
                        //$location.path( '/thankyou' );  
                        var param = {};
                        if ($scope.surveyTokenID != undefined && $scope.surveyTokenID != '')
                        {
                            param.isAnonymous = true;

                        }
                        else {
                            param.isAnonymous = false;
                        }
                        SurveyPreviewFactory.Logout().then(function (page) {
                            console.log(page);
                        });
                        $scope.IsLoading = false;
                        $state.go("thankyou", param);
                    },
                    function (error) {
                        $ngBootbox.alert("Server error, please try again later.");
                        $scope.IsLoading = false;
                    });
                },
                function () {
                    $scope.IsLoading = false;
                });
            },
            function ()
            {
                $scope.IsLoading = false;
                //on cancel
            } );
        }
        else
        {
            $scope.IsFormInvalid = true;
        }

    }

    $scope.AddGridRow = function ( surveyQuestionPreview )
    {
        var horizontalQuestionId = surveyQuestionPreview.QuestionDetail.ID;
        SurveyPreviewFactory.GetHorizontalQuestionMatrix( horizontalQuestionId ).then( function ( matrix )
        {
            surveyQuestionPreview.GridChildQuestionMatrix.push( matrix[0] );
            UpdateDynamicHtmlMaster( surveyQuestionPreview, "item.Answer" );
        } );
    }

    $scope.IsOptionsRequired = function ( answerChoiceList )
    {
        return !answerChoiceList.some( function ( options )
        {
            return options.IsSelected;
        } );
    }

    $scope.CalculateTotal = function ( gridChildQuestionList )
    {
        var total = 0;
        var totalQuestionIndex = null;
        if ( gridChildQuestionList != null && gridChildQuestionList.length > 0 )
        {
            for ( var i = 0; i < gridChildQuestionList.length; i++ )
            {
                if ( gridChildQuestionList[i].QuestionDetail.QuestionTypeId == GlobalQuestionType.Sum )
                {
                    var answer = parseInt( gridChildQuestionList[i].Answer );
                    if ( answer != undefined && answer != null && answer > 0 )
                    {
                        total += answer;
                    }

                }
                if ( gridChildQuestionList[i].QuestionDetail.QuestionTypeId == GlobalQuestionType.Total )
                {
                    totalQuestionIndex = i;
                }
            }

            if ( totalQuestionIndex != null )
            {
                gridChildQuestionList[totalQuestionIndex].Answer = total;
            }
        }
    }

    $scope.BrowseFile = function ( files, item )
    {
        var questionId = item.QuestionDetail.ID;
        $scope.UploadingAttachments = true;
        //$scope.BrowseFiles = files;
        fname = files[0].name;
        var fsize = files[0].size;
        $scope.isValidSize = false;
        var currentfileExtension = fname.substring( fname.indexOf( '.' ) ).toLowerCase().trim();

        if ($rootScope.ValidFileExtentions.indexOf(currentfileExtension) < 0) 
        {
            $ngBootbox.alert($scope.PageMessage.InvalidExcelFile);
            $scope.BrowseFiles = '';
            return;
        }
        if (!CheckSize(files[0], $rootScope.MaxFileSizeInKB)) {
            var msg = $scope.PageMessage.FileSizeNotMoreThan + $rootScope.MaxFileSizeInKB
            $ngBootbox.alert(msg);
            $scope.BrowseFiles = '';
            $scope.$apply();
            files = null;
            return;
        }
        else
        {
            SurveyPreviewFactory.UploadFile(files, questionId).then(function (result)
            {
                if (result != null && result != undefined) {
                    if (!(result.IsValidFileExtension != undefined && result.IsValidFileExtension)) {
                        $ngBootbox.alert($scope.PageMessage.InvalidExcelFile);
                        return;
                    }

                    if (!(result.IsValidFileSize != undefined && result.IsValidFileSize)) {
                        var msg = $scope.PageMessage.FileSizeNotMoreThan + $rootScope.MaxFileSizeInKB
                        $ngBootbox.alert(msg);
                        return;
                    }
                    var data = result.Data;
                    if (data != null && data.length > 0) {
                        item.GridChildQuestionMatrix = item.GridChildQuestionMatrix.concat(data);
                        UpdateDynamicHtmlMaster(item, "item.Answer");
                    }
                }
            } );

        }
    }

    $scope.DownloadSampleExcel = function ( id )
    {
        window.location = '/SurveyPreview/DownloadExcel?id=' + id;
    }

    $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        // do something
        if (!$scope.IsPermitToNavigate) {
            event.preventDefault();
            if (fromState.name == 'fillsurvey' && $scope.$$childTail.surveyPreviewForm.$dirty && !$scope.IsPermitToNavigate) {
                var options = {
                    message: "Your latest changes have not been saved. Do you still want to leave the page?",
                    title: 'Do you want to leave this page?',
                    className: 'custom-dialog',
                    buttons: {
                        warning: {
                            label: "Leave",
                            className: "btn-default",
                            callback: function () {
                                $scope.IsPermitToNavigate = true;
                                $state.go(toState.name)
                            }
                        },
                        success: {
                            label: "Stay",
                            className: "btn-default",
                            callback: function () { }
                        }
                    }
                };
                $ngBootbox.customDialog(options);

            }
            else {
                $scope.IsPermitToNavigate = true;
                $state.go(toState.name)
            }
        }

    })

    $scope.SetOtherDropDownFlag = function (item, model) {
        choice = item.AnswerChoiceList.filter(function (elem) {
            return elem.ID == model;
        })
        if (choice != null && choice.length > 0 && choice[0].IsOtherChoice) {
            item.IsOtherChoiceText = true;
        }
        else {
            item.IsOtherChoiceText = false;
            item.OtherChoiceText = '';
        }
    }

    /////////////////////////////////Private functions//////////////////////////
    function UpdateDynamicHTML()
    {
        for ( var j = 0 ; j < $scope.SurveyPreview.SurveyPagePreviewList.length; j++ )
        {
            var list = $scope.SurveyPreview.SurveyPagePreviewList[j];
            for ( var i = 0; i < list.QuestionDetailList.length; i++ )
            {
                UpdateDynamicHtmlMaster( list.QuestionDetailList[i], "item.Answer" );
            }
        }

    }

    function UpdateDynamicHtmlMaster( questionObj, answerKey, isGridSubQuestion )
    {
        
        var questionType = $scope.QuestionTypeList.filter( function ( questionType )
        {
            return questionType.ID == questionObj.QuestionDetail.QuestionTypeId;
        } );

        if (questionType[0].ID == $scope.VerticalGridQuestionType || questionType[0].ID == $scope.HorizontalGridQuestionType || questionType[0].ID == $scope.HorizontalNewGridQuestionType)
        {
            var matrix = questionObj.GridChildQuestionMatrix;
            if ( matrix != null && matrix.length > 0 )
            {
                for ( var p = 0; p < matrix.length; p++ )
                {
                    if ( matrix[p].GridChildQuestionList != null && matrix[p].GridChildQuestionList.length > 0 )
                    {
                        for ( var q = 0; q < matrix[p].GridChildQuestionList.length; q++ )
                        {
                            UpdateDynamicHtmlMaster( matrix[p].GridChildQuestionList[q], "col.Answer", true );
                            matrix[p].GridChildQuestionList[q].DynamicHTML = matrix[p].GridChildQuestionList[q].DynamicHTML.replace( /item/g, "col" );
                            matrix[p].GridChildQuestionList[q].DynamicHTML = matrix[p].GridChildQuestionList[q].DynamicHTML.replace(/#pipe#/g, "item");
                            matrix[p].GridChildQuestionList[q].DynamicHTML = matrix[p].GridChildQuestionList[q].DynamicHTML.replace(/col.IsMandatory/g, "item.IsMandatory");
                            matrix[p].GridChildQuestionList[q].DynamicHTML = matrix[p].GridChildQuestionList[q].DynamicHTML.replace(/col.SurveyQuestionId/g, "item.QuestionDetail.ID");
                            matrix[p].GridChildQuestionList[q].DynamicHTML = matrix[p].GridChildQuestionList[q].DynamicHTML.replace(/col.QuestionDetail.ValidationMessage/g, "item.QuestionDetail.ValidationMessage");
                            

                            //Arabic language work
                            matrix[p].GridChildQuestionList[q].DynamicHTMLArabic = matrix[p].GridChildQuestionList[q].DynamicHTMLArabic.replace(/item/g, "col");
                            matrix[p].GridChildQuestionList[q].DynamicHTMLArabic = matrix[p].GridChildQuestionList[q].DynamicHTMLArabic.replace(/#pipe#/g, "item");
                            matrix[p].GridChildQuestionList[q].DynamicHTMLArabic = matrix[p].GridChildQuestionList[q].DynamicHTMLArabic.replace(/col.IsMandatory/g, "item.IsMandatory");
                            matrix[p].GridChildQuestionList[q].DynamicHTMLArabic = matrix[p].GridChildQuestionList[q].DynamicHTMLArabic.replace(/col.SurveyQuestionId/g, "item.QuestionDetail.ID");
                            matrix[p].GridChildQuestionList[q].DynamicHTMLArabic = matrix[p].GridChildQuestionList[q].DynamicHTMLArabic.replace(/col.QuestionDetail.ValidationMessageArabic/g, "item.QuestionDetail.ValidationMessageArabic");
                        }
                    }
                }
            }
        }
        
        var html = "";
        var htmlArabic = "";
        var IsInformational = false;
        if ( questionType != null && questionType != undefined && questionType.length > 0 )
        {
            html = questionType[0].ControlExpression ? questionType[0].ControlExpression : "";
            htmlArabic = questionType[0].ControlExpressionArabic ? questionType[0].ControlExpressionArabic : "";

            IsInformational = questionType[0].IsInformational;
            questionObj.HasAnswerChoice = questionType[0].HasAnswerChoice;
        }
        if ( questionObj.HasAnswerChoice )
        {
            questionObj.Answer = Number( questionObj.Answer );
        }
        if ( questionObj.Answer == null || questionObj.Answer == undefined || questionObj.Answer == '' || questionObj.Answer == NaN )
        {
            questionObj.Answer = null;
        }

        html = html.replace(/#value#/g, answerKey);
        htmlArabic = htmlArabic.replace(/#value#/g, answerKey);
        if (!isGridSubQuestion) {
            html = html.replace(/#pipe#.PipeGridSubQuestionId == col.QuestionDetail.ID/g, "false");
            htmlArabic = htmlArabic.replace(/#pipe#.PipeGridSubQuestionId == col.QuestionDetail.ID/g, "false");
        }
        
        questionObj.DynamicHTML = html;
        questionObj.DynamicHTMLArabic = htmlArabic;
        questionObj.IsInformational = IsInformational;

        questionObj.IsInformational = IsInformational;
        if (questionType != null && questionType != undefined && questionType.length > 0
            && questionType[0].ID != $scope.DynamicQuestionTypeID
            && questionObj.IsMaskingEnabled == true) {
            var controlExpression = $scope.DynamicQuestionType.ControlExpression ? $scope.DynamicQuestionType.ControlExpression : "";
            questionObj.DynamicHTML = questionObj.DynamicHTML.replace(/item.Answer/g, "answer.AnswerChoiceText");
            controlExpression = controlExpression.replace('#ControlType#', questionObj.DynamicHTML);
            questionObj.DynamicHTML = controlExpression;

            // Arabic work
            var controlExpressionArabic = $scope.DynamicQuestionType.ControlExpressionArabic ? $scope.DynamicQuestionType.ControlExpressionArabic : "";
            questionObj.DynamicHTMLArabic = questionObj.DynamicHTMLArabic.replace(/item.Answer/g, "answer.AnswerChoiceText");
            controlExpressionArabic = controlExpressionArabic.replace('#ControlType#', questionObj.DynamicHTMLArabic);
            questionObj.DynamicHTMLArabic = controlExpressionArabic;
        }

    }

    $scope.UpdateNextPageQuestionNumber = function () {
        try{
            var questionList = $scope.SurveyPreview.SurveyPagePreviewList[0].QuestionDetailList;

            if (questionList && questionList.length > 0) {
                var count = 1;
                for (index in questionList)
                {
                    if (questionList[index].QuestionDetail.QuestionTypeId != $scope.GlobalQuestionType.Information) {
                        
                        questionList[index].QuestionNumber = $scope.PreviousQuestionNumber + count++;
                        $scope.lastQuestionNumber = questionList[index].QuestionNumber;
                    }

                };
            }
        }
        catch (erro) {
            // digest error
        }
        return 0;
    }

    $scope.UpdatePreviousPageQuestionNumber = function () {
        try {
            var questionList = $scope.SurveyPreview.SurveyPagePreviewList[0].QuestionDetailList.filter(function (elem) {
                return elem.QuestionDetail.QuestionTypeId != $scope.GlobalQuestionType.Information
            });

            if (questionList && questionList.length > 0) {
                $scope.PreviousQuestionNumber = $scope.PreviousQuestionNumber - questionList.length;
                var count = 1;
                for (index in questionList) {
                    
                    if (questionList[index].QuestionDetail.QuestionTypeId != $scope.GlobalQuestionType.Information) {
                        
                        questionList[index].QuestionNumber = $scope.PreviousQuestionNumber + count++;
                        $scope.lastQuestionNumber = questionList[index].QuestionNumber;
                    }

                };


            }
        }
        catch (erro) {
            // digest error
        }
        return 0;
    }
}] );

mainApp.controller("SurveyResponseController", ['$scope', 'SurveyPreviewFactory', '$stateParams', 'DashboardFactory', 'QuestionTypeFactory', '$location', '$timeout','$sessionStorage', 'GlobalQuestionType',
    function ($scope, SurveyPreviewFactory, $stateParams, DashboardFactory, QuestionTypeFactory, $location, $timeout, $sessionStorage, GlobalQuestionType)
{
    $scope.isDownloading = false;
    $scope.surveyTokenID = '';
    $scope.IsLoading = true;
    $scope.DynamicQuestionType = '';
    $scope.DynamicQuestionTypeID = GlobalQuestionType.Dynamic;
    $scope.IsInitializing = false;
    $scope.SetTealiumValues = function (pageName) {
        DashboardFactory.GetInfo().then(function (d) {
            $scope.Details = d;
            SetTealiumValuesForSurveyPortal($scope.Details.UserId, $scope.Details.SiteCode, $scope.Details.SiteName, pageName);
        });
    }

    $scope.initialize = function () {
        $scope.IsInitializing = true;
        $scope.surveyID = $stateParams.surveyID;
        $scope.surveyTokenID = $stateParams.tokenID;
        $scope.FirmContactId = $stateParams.FirmContactId;
        if ($scope.surveyTokenID == null || $scope.surveyTokenID == undefined || $scope.surveyTokenID == '') {
            $scope.surveyTokenID = $scope.surveyTokenID = $( "#encryptedSurveyTokenID" ).val() ? $scope.surveyTokenID = $("#encryptedSurveyTokenID").val() : '';                
        }
        if ($scope.FirmContactId == null || $scope.FirmContactId == undefined || $scope.FirmContactId == '') {
            $scope.FirmContactId = "";
        }
        SurveyPreviewFactory.GetAllPage($scope.surveyID, $scope.surveyTokenID, $scope.FirmContactId).then(function (surveyData) {

            $scope.SetTealiumValues("view survey response");
            $scope.SurveyPreview = surveyData;
            $scope.IsLoading = false;
            $( "#surveyLogoElement" ).attr( "src", $scope.SurveyPreview.survey.LogoUrl );
            $( "#SurveyNameElement" ).text( $scope.SurveyPreview.survey.SurveyName );
            QuestionTypeFactory.Get().then(function (data) {
                $scope.QuestionTypeList = data;
                QuestionTypeFactory.GetDynamicQuestionTypeShell().then(function (data) {
                    $scope.DynamicQuestionType = data;
                    UpdateDynamicHTML();
                    $scope.IsLoading = false;
                    $scope.IsInitializing = false;
                },
                function (error) {
                    $scope.IsInitializing = false;
                });
                
            },
            function () {
                $scope.IsInitializing = false;
            });
        });
    }

    $scope.Cancel = function () {
        if ($sessionStorage.returnURL != undefined) {
            $location.path($sessionStorage.returnURL);
        }
        else { 
            $location.path('/surveyStatisticsList');
        }        
    }


    $scope.Print = function () {
        $scope.isDownloading = true;
        try {
            var checkboxeList = $("input[type=checkbox]:checked");
            if (checkboxeList && checkboxeList.length > 0) {
                checkboxeList.each(function (checkbox) {
                    $(this).attr("checked", "checked");
                });
            }

            var radiokboxeList = $("input[type=radio]:checked");
            if (radiokboxeList && radiokboxeList.length > 0) {
                radiokboxeList.each(function (radio) {
                    $(this).attr("checked", "checked");
                });
            }
        }
        catch (error) {

        }
        var source = window.document.getElementById("responseDiv").innerHTML;
        var doc = document.createElement('div');
        document.getElementById('forPrint').innerHTML = source;
        $('#forPrint .removeQuestion').addClass('removeTheseQuestion');
        $(".removeTheseQuestion").remove();
        source = document.getElementById("forPrint").innerHTML;
        SurveyPreviewFactory.GeneratePDF(source).then(function (data) {
            var link = document.createElement("a");
            link.setAttribute("href", data);
            link.setAttribute("target", "_blank");
            link.setAttribute("download", $scope.SurveyPreview.survey.SurveyName + '.pdf');
            document.body.appendChild(link); // Required for FF
            link.click();
            $scope.isDownloading = false;
            document.getElementById("forPrint").innerHTML = "";
        });
    }

    $scope.PrintAndInitialize = function () {
        $scope.isDownloading = true;
        $scope.surveyID = $stateParams.surveyID;
        SurveyPreviewFactory.GetAllPage($scope.surveyID).then(function (surveyData) {
            $scope.SurveyPreview = surveyData;
            $("#surveyLogoElement").attr("src", $scope.SurveyPreview.survey.LogoUrl);
            $("#SurveyNameElement").text($scope.SurveyPreview.survey.SurveyName);
            QuestionTypeFactory.Get().then(function (data) {
                $scope.QuestionTypeList = data;
                UpdateDynamicHTML();
                $timeout($scope.Print, 1500);

            });
        });
    }
    /////////////////////////////////Private functions//////////////////////////
    function UpdateDynamicHTML() {
        for (var j = 0 ; j < $scope.SurveyPreview.SurveyPagePreviewList.length; j++) {
            var list = $scope.SurveyPreview.SurveyPagePreviewList[j];
            for (var i = 0; i < list.QuestionDetailList.length; i++) {
                UpdateDynamicHtmlMaster(list.QuestionDetailList[i], "item.Answer");
            }
        }

    }

    function UpdateDynamicHtmlMaster(questionObj, answerKey) {
        var questionType = $scope.QuestionTypeList.filter(function (questionType) {
            return questionType.ID == questionObj.QuestionDetail.QuestionTypeId;
        });

        if (questionType[0].ID == 21 || questionType[0].ID == 22) {
            var matrix = questionObj.GridChildQuestionMatrix;
            if (matrix != null && matrix.length > 0) {
                for (var p = 0; p < matrix.length; p++) {
                    if (matrix[p].GridChildQuestionList != null && matrix[p].GridChildQuestionList.length > 0) {
                        for (var q = 0; q < matrix[p].GridChildQuestionList.length; q++) {
                            UpdateDynamicHtmlMaster(matrix[p].GridChildQuestionList[q], "col.Answer");
                            matrix[p].GridChildQuestionList[q].DynamicHTML = matrix[p].GridChildQuestionList[q].DynamicHTML.replace("item", "col");

                        }
                    }
                }
            }
        }
        var html = "";
        var IsInformational = false;
        if (questionType != null && questionType != undefined && questionType.length > 0 && questionType[0].ControlExpressionReadonly != null) {
            html = questionType[0].ControlExpressionReadonly;
            IsInformational = questionType[0].IsInformational;
            questionObj.HasAnswerChoice = questionType[0].HasAnswerChoice;
        }
        if (questionObj.HasAnswerChoice) {
            questionObj.Answer = Number(questionObj.Answer);
        }
        html = html.replace("#value#", answerKey);
        questionObj.DynamicHTML = html;
        questionObj.IsInformational = IsInformational;
        if (questionType != null && questionType != undefined && questionType.length > 0
           && questionType[0].ID != $scope.DynamicQuestionTypeID
           && questionObj.IsMaskingEnabled == true) {
            var controlExpression = $scope.DynamicQuestionType.ControlExpression;
            questionObj.DynamicHTML = questionObj.DynamicHTML.replace(/item.Answer/g, "answer.AnswerChoiceText");
            controlExpression = controlExpression.replace('#ControlType#', questionObj.DynamicHTML);
            questionObj.DynamicHTML = controlExpression;
        }
    }


}]);


mainApp.controller("surveyStatisticsCtrl", surveyStatisticsController);
surveyStatisticsController.$inject = ['$scope', '$state', '$http', '$rootScope', '$location', '$stateParams', '$routeParams', '$ngBootbox', 'surveyStatisticsFactory'
    , 'GlobalConfig', 'SurveyMatrixStatusCountFactory', 'DashboardFactory', '$sessionStorage', '$localStorage'];
function surveyStatisticsController($scope, $state, $http, $rootScope, $location, $stateParams, $routeParams, $ngBootbox, surveyStatisticsFactory, GlobalConfig
    , SurveyMatrixStatusCountFactory, DashboardFactory,$sessionStorage, $localStorage)
{
    $scope.surveyStatisticsList = [];
    $scope.initialize = initialize;
    $scope.setActive = setActive;
    $scope.selectedIndex = 0;
    $scope.sideNavList = [];
    $scope.filter = '1';
    $scope.code = "ONG";
    $scope.IsLoading = false;
    $scope.surveyName = "";
    
    $scope.FillSurvey = function (surveyUniqueID) {
        setSessionStorage();
        var surveyURL = GlobalConfig.SurveyURI;
        $location.path( surveyURL + surveyUniqueID );
    }

    $scope.SurveyInfo = function ( surveyUniqueID )
    {
        setSessionStorage();
        var surveyURL = GlobalConfig.SurveyInfoURI;
        $location.path( surveyURL + surveyUniqueID );
    }

    function setActive( index,code )
    {
        $scope.filter = '1';
        $scope.code = code;
        delete $sessionStorage.statusCode;
        $scope.selectedIndex = index;
        GetSurveyStatistics( $scope.code, $scope.filter );
    }
    function GetSurveyStatistics(status, filter)
    {
        $scope.IsLoading = true;
        surveyStatisticsFactory.GetSurveyStatisticsByFilter( status, filter ).then( 
            function ( data )
            {
                $scope.surveyStatisticsList = [];
                $scope.surveyStatisticsList = data;
                $scope.IsLoading = false;
            },
            function ( error )
            {
                $scope.IsLoading = false;
            });
    }
    $scope.GetSurveyStatusCount = function(){
        SurveyMatrixStatusCountFactory.Get().then( function ( data )
        {
            $scope.sideNavList = data;
        } );
    }
    $scope.isActive = function (index, code)
    {
        if (index == $scope.selectedIndex) {
            return true;
        }
        else if (code == $scope.code) {
            return true;
        }
        return false;
    }
    function initialize()
    {
        restoreSessionState();
        GetSurveyStatistics($scope.code, $scope.filter);
        $scope.GetSurveyStatusCount();        
        //var menu = {};
        //menu.itemname = "New & Ongoing Surveys()";
        //menu.status = "ong";
        //$scope.sideNavList.push(menu);

        //menu = {};
        //menu.itemname = "Submitted()";
        //menu.status = "com";
        //$scope.sideNavList.push(menu);

        //menu = {};
        //menu.itemname = "Expired()";
        //menu.status = "exp";
        //$scope.sideNavList.push(menu);
        DashboardFactory.GetInfo().then(function (d) {
            $scope.Details = d;
            SetSurveysTealiumValuesForSurveyPortal( $scope.Details.UserId, $scope.Details.SiteCode, $scope.Details.SiteName );
            
        },
        function (error)
        {
            
        } );
    }
    function setSessionStorage() {
        $sessionStorage.returnURL = $location.path();
        $sessionStorage.surveyStatistics = {};
        $sessionStorage.surveyStatistics.statusCode = $scope.code;
        $sessionStorage.surveyStatistics.surveyName = $scope.surveyName;
        $sessionStorage.surveyStatistics.filter = $scope.filter;
    }
    function getSessionStorage() {
        if ($sessionStorage.surveyStatistics != undefined) {
            $scope.code = $sessionStorage.surveyStatistics.statusCode;
            $scope.surveyName = $sessionStorage.surveyStatistics.surveyName;
            $scope.filter = $sessionStorage.surveyStatistics.filter;
        }
    }
    function removeSessionStorage() {
        if ($sessionStorage.surveyStatistics != undefined)
        {
            delete $sessionStorage.surveyStatistics;
        }
        if ($sessionStorage.returnURL != undefined)
        {
            delete $sessionStorage.returnURL;
        }
    }
    function restoreSessionState() {
        if ($sessionStorage.prevStateName != undefined && ($sessionStorage.prevStateName.toLowerCase() == "thankyou"
            || $sessionStorage.prevStateName.toLowerCase() == "surveyinfo" || $sessionStorage.prevStateName.toLowerCase() == "surveyinfobycontact"
            || $sessionStorage.prevStateName.toLowerCase() == "surveytoken")) {
            if ($sessionStorage.surveyStatistics != undefined && $sessionStorage.surveyStatistics.statusCode != undefined) {
                getSessionStorage();
                if ($sessionStorage.prevStateName.toLowerCase() == "thankyou") {
                    $scope.code = "COM";
                }
                $scope.selectedIndex = -1;
                removeSessionStorage();
            }
        }
    }
    $scope.initialize();

}
mainApp.controller( "ThankYouController", ['$scope', '$location', '$ngBootbox', '$stateParams','$sessionStorage',
function ($scope, $location, $ngBootbox, $stateParams, $sessionStorage)
{
    if ($sessionStorage.returnURL != undefined) {
        $scope.returnURL = $sessionStorage.returnURL;
    }
    else {
        $scope.returnURL = '/surveyStatisticsList';
    }
    
    if ($stateParams.isAnonymous != undefined && $stateParams.isAnonymous != null && $stateParams.isAnonymous == "true") {
        $scope.isAnonymous = true;
    }
    else {
        $scope.isAnonymous = false;
    }
}]);

mainApp.directive( 'dynamic', function ( $compile )
{
    return {
        restrict: 'A',
        replace: true,
        link: function ( scope, ele, attrs )
        {
            scope.$watch( attrs.dynamic, function ( html )
            {
                ele.html(html);
                //console.log(html);
                $compile( ele.contents() )( scope );
            } );
        }
    };
});

mainApp.directive('loading', ['$http', function ($http) {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            scope.isLoading = function () {
                return $http.pendingRequests.length > 0;
            };
            scope.$watch(scope.isLoading, function (v) {
                if (v) {
                    elm.show();
                } else {
                    elm.hide();
                }
            });
        }
    };
}] );

mainApp.directive( "datepicker", function ( $parse, $filter )
{
    return {
        transclude: true,
        restrict: "A",
        require: "ngModel",
        link: function ( scope, elem, attrs, ngModelCtrl )
        {
            var modelAccessor = $parse( attrs.ngModel );
            var dateFormat = 'mm/dd/yyyy';

            var updateModel = function ( dateText )
            {
                // alert( dateText );
                scope.$apply( function ()
                {
                    ngModelCtrl.$setViewValue( dateText );
                    $( elem ).datepicker( "hide" );

                } );
            };

            var options = {
                dateFormat: "mm/dd/yy",
                changeMonth: true,
                changeYear: true,
                yearRange: "-30:+20",
                onSelect: function ( dateText )
                {
                    updateModel( dateText );

                }
            };
            elem.datepicker( options ).keydown( function ( e )
            {
                if ( e.keyCode == 8 || e.keyCode == 46 )
                {
                    $.datepicker._clearDate( this );
                }
            } );

            // $(elem).datepicker(options);

            scope.$watch( modelAccessor, function ( val )
            {
                //alert(val)

                if ( val != null && val != "" && val != undefined )
                {
                    //var date = new Date(val);
                    elem.datepicker( "setDate", new Date( Date.parse( val ) ) );
                }
                //else {
                //    elem.datepicker("setDate", null);
                //}
            } );
        }
    }
} );

mainApp.filter( 'monthName', [function ()
{
    return function ( monthNumber )
    { //1 = January
        var monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'];

        if ( monthNumber != null && monthNumber != "" )
        {
            return monthNames[monthNumber - 1];
        }
        else
        {
            return "N/A";
        }


    }
}]);

mainApp.directive('numbersOnly', function () {
    return {
        require: '?ngModel',
        link: function ( scope, element, attrs, ngModelCtrl )
        {
            if ( !ngModelCtrl )
            {
                return;
            }

            ngModelCtrl.$parsers.push( function ( val )
            {
                if ( angular.isUndefined( val ) )
                {
                    var val = '';
                }
                var clean = val.replace( /[^0-9]+/g, '' );
                if ( val !== clean )
                {
                    ngModelCtrl.$setViewValue( clean );
                    ngModelCtrl.$render();
                }
                return clean;
            } );

            element.bind( 'keypress', function ( event )
            {
                if ( event.keyCode === 32 )
                {
                    event.preventDefault();
                }
            } );
        }
    };
});


mainApp.directive("repeatEnd", function () {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            if (scope.$last) {
                scope.$eval(attrs.repeatEnd);
            }
        }
    };
});

mainApp.directive( 'digitsOnly', function ()
{
    return {
        require: '?ngModel',
        link: function ( scope, element, attrs, ngModelCtrl )
        {
            if ( !ngModelCtrl )
            {
                return;
            }

            ngModelCtrl.$parsers.push( function ( val )
            {
                if ( angular.isUndefined( val ) )
                {
                    var val = '';
                }
                var clean = val.replace( /[^0-9]+/g, '' );
                if ( val !== clean )
                {
                    ngModelCtrl.$setViewValue( clean );
                    ngModelCtrl.$render();
                }
                return clean;
            } );

            element.bind( 'keypress', function ( event )
            {
                if ( event.keyCode === 32 )
                {
                    event.preventDefault();
                }
            } );
        }
    };
});
mainApp.filter('pagination', function () {
    return function (input, start) {
        start = +start;
        return input.slice(start);
    };
});

mainApp.directive('strongPasswordMeter', function () {
    return {
        require: 'ngModel',
        link: function ($scope, $element, $attrs, ngModelCtrl) {
            $element.on('blur change keydown', function (evt) {
                $scope.$evalAsync(function ($scope) {
                    var pwd = $element.val();
                    $scope.passwordStrengthColor = "";

                    var hasUpperCase = /[A-Z]/.test(pwd);
                    var hasLowerCase = /[a-z]/.test(pwd);
                    var hasNumbers = /\d/.test(pwd);
                    var hasNonalphas = /\W/.test(pwd);
                    var characterGroupCount = hasUpperCase + hasLowerCase + hasNumbers + hasNonalphas;
                    if (characterGroupCount == 0) {
                        $scope.passwordStrength = '0%';
                        $scope.passwordStrengthColor = "#f5f5f5";
                    }
                    if (characterGroupCount == 1) {
                        $scope.passwordStrength = '25%';
                        $scope.passwordStrengthColor = "#dd4b39";
                    }
                    if (characterGroupCount == 2) {
                        $scope.passwordStrength = '50%';
                        $scope.passwordStrengthColor = "#f39c12";
                    }
                    if (characterGroupCount == 3) {
                        $scope.passwordStrength = '75%';
                        $scope.passwordStrengthColor = "#00c0ef";
                    }
                    if (characterGroupCount >= 4) {
                        if (pwd.length >= 8) {
                            $scope.passwordStrength = '100%';
                            $scope.passwordStrengthColor = "#00a65a";
                        }
                        else {
                            $scope.passwordStrength = '75%';
                            $scope.passwordStrengthColor = "#00c0ef";
                        }
                    }

                    if ((pwd.length >= 8) && (characterGroupCount >= 4)) {
                        ngModelCtrl.$setValidity('complexity', true);
                        return pwd;
                    }
                    else {
                        ngModelCtrl.$setValidity('complexity', false);
                        return undefined;
                    }
                });
            });
        }
    };
});

mainApp.directive('passwordVerify', function () {
    return {
        require: 'ngModel',
        link: function ($scope, $element, $attrs, ngModelCtrl) {
            $element.on('blur change keydown', function (evt) {
                $scope.$evalAsync(function ($scope) {
                    var pwdA = $element.val();
                    var pwdB = $scope.$eval($attrs.passwordVerify);
                    if (pwdA == pwdB) {
                        $scope.addUserForm.ConfirmPassword.$setValidity('pwdcomparison', true);
                        $scope.addUserForm.NewPassword.$setValidity('pwdcomparison', true);
                        return pwdA;
                    }
                    else {
                        $scope.addUserForm.ConfirmPassword.$setValidity('pwdcomparison', false);
                        $scope.addUserForm.NewPassword.$setValidity('pwdcomparison', false);
                        return undefined;
                    }
                });
            });
        }
    };
});

mainApp.directive('ngEnter', function () { //a directive to 'enter key press' in elements with the "ng-enter" attribute

    return function (scope, element, attrs) {

        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});
mainApp.directive('requestVerificationToken', requestVerificationToken);
    requestVerificationToken.$inject = ['$http'];

    function requestVerificationToken($http)
    {
        return function (scope, element, attrs) {
            $http.defaults.headers.common['RequestVerificationToken'] = attrs.requestVerificationToken || "no request verification token";
        };
    }

mainApp.factory('ApplicationLanguageFactory', ['$http', '$q', function ($http, $q) {
    var ApplicationLanguageFactory = {};

    ApplicationLanguageFactory.Get = function () {
        var defer = $q.defer();
        $http(
            {
                url: '/api/ApplicationLanguage/Get/',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }


    return ApplicationLanguageFactory;
}]);
mainApp.factory('DashboardFactory', ['$http', '$q', function ($http, $q) {
    var DashboardFactory = {};


     DashboardFactory.GetInfo = function () {
         var defer = $q.defer();
         $http(
             {
                 url: '/api/Dashboard/GetInfo',
                 method: 'post',
                 headers: { 'content-type': 'application/json' }
             }).success(function (d) {
                 defer.resolve(d);
             }).error(function (e) {
                 defer.reject(e);
             });
         return defer.promise;
     }
    
     return DashboardFactory;
    
}]);
mainApp.factory('masterFactory', ['$http', '$q', '$filter', function ($http, $q, $filter) {
    var masterFactory = {};
   
    masterFactory.LogOff = function () {
        var defer = $q.defer();
        $http.post('/RespondentAuthentication/Logout',
               JSON.stringify({}),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success(function (data) {
               defer.resolve(data);
           }).error(function (e) {
               defer.reject(e);
           });
        return defer.promise;
    }

    masterFactory.GetOrganizationName = function () {
        var defer = $q.defer();
        $http(
            {
                url: '/api/LawFirm/OrganizationName/',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    masterFactory.GetSiteInfo = function ()
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/SiteDetails/GetSiteInfo/',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }

    return masterFactory; 
}]);
mainApp.factory('QuestionTypeFactory', ['$http', '$q', function ($http, $q) {
    var QuestionTypeFactory = {};

    QuestionTypeFactory.GetByID = function (id) {
        var defer = $q.defer();
        $http(
            {
                url: '/api/QuestionType/GetByID/' + id,
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    QuestionTypeFactory.GetDynamicQuestionTypeShell = function () {
        var defer = $q.defer();
        $http(
            {
                url: '/api/QuestionType/GetDynamicQuestionTypeShell',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }


    QuestionTypeFactory.Get = function (id) {
        var defer = $q.defer();  
        $http(
            {
                url: '/api/QuestionType/Get',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }


    QuestionTypeFactory.GetFillList = function () {
        var defer = $q.defer();
        $http(
            {
                url: '/api/QuestionType/GetFillList',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }


    return QuestionTypeFactory;
}]);
mainApp.factory('RespondentFactory', ['$http', '$q', function ($http, $q) {
    var RespondentFactory = {};

    RespondentFactory.ValidatePassword = function (password) {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Respondent/ValidatePassword',
                params: { password: password },
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    RespondentFactory.ResetPassword = function (user) {
        var defer = $q.defer();
        $http.post('/api/Respondent/ResetPassword',
               JSON.stringify(user),
               {
                   headers: {
                       'Content-Type': 'application/json',
                   }
               }
           ).success(function (data) {
               defer.resolve(data);
           }).error(function (e) {
               defer.reject(e);
           });
        return defer.promise;
    }

    RespondentFactory.SwitchLanguage = function (language) {
        var defer = $q.defer();
        $http(
            {
                url: '/RespondentAuthentication/SwitchLanguage',
                params: { selLang: language },
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }



    return RespondentFactory;

}]);
mainApp.factory('ScrollFactory', ['$http', '$q', function ($http, $q) {
    var ScrollFactory = {};
    
    ScrollFactory.ApplyScroll = function (divId,color, width) {
        var options = reinitialize();
        if (color) {
            options.cursorcolor = color;
        }
        if (width) {
            options.cursorwidth = width;
        }
        $("#" + divId).niceScroll(options);
    }

    function reinitialize() {
        var options = {
            cursorcolor: "#424242",
            cursorwidth: "10px",
            zindex : 5000
        }
        return options;
    }

    return ScrollFactory;

}]);
mainApp.factory( 'SeedSurveyCategoryFactory', ['$http', '$q', function ( $http, $q )
{
    var SeedSurveyCategoryFactory = {};

    SeedSurveyCategoryFactory.Get = function ()
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/SeedSurveyCategory/Get',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }

    SeedSurveyCategoryFactory.GetById = function (id) {
        var defer = $q.defer();
        $http(
            {
                url: '/api/SeedSurveyCategory/GetBySurveyID/' + id,
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }


    return SeedSurveyCategoryFactory;
}] );
mainApp.factory( 'SiteMenusFactory', ['$http', '$q', '$filter', function ( $http, $q, $filter )
{
    var SiteMenusFactory = {};

    SiteMenusFactory.GetMenuList = function ( )
    { 
        var defer = $q.defer();
        $http(
         {
             url: '/api/SiteMenus/GetBySiteId',

             method: 'GET',
             headers: { 'content-type': 'application/json' }
         } ).success( function ( d )
         {
             defer.resolve( d );
         } ).error( function ( e )
         {
             defer.reject( e );
         } );
        return defer.promise;
    }

    return SiteMenusFactory;
}] );
mainApp.factory('SurveyCalendarFactory', SurveyCalendarFactory);
SurveyCalendarFactory.$inject = ['$http', '$q']

function SurveyCalendarFactory($http, $q) {
    var surveyCalendarFactory = {};

    surveyCalendarFactory.GetCurrentDate = GetCurrentDate;
    
    function GetCurrentDate() {
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyCalendar/GetCurrentDate',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }    
    return surveyCalendarFactory;
}
mainApp.factory( 'SurveyMatrixStatusCountFactory', ['$http', '$q', function ( $http, $q )
{
    var SurveyMatrixStatusCountFactory = {};

    SurveyMatrixStatusCountFactory.Get = function ()
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyMatrixStatusCount/Get',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }

    return SurveyMatrixStatusCountFactory;
}] );
mainApp.factory( 'SurveyPreviewFactory', ['$http', '$q', function ( $http, $q )
{
    var SurveyPreviewFactory = {};

    SurveyPreviewFactory.GetByID = function (surveyID, departmentRespondentID, isPreview, isProtectedSurvey)
    {
        if (isProtectedSurvey) {
            return SurveyPreviewFactory.GetProtectedSurvey(surveyID, departmentRespondentID);
        }
        else if (isPreview) {
            return SurveyPreviewFactory.GetPreviewSurvey(surveyID);
        }
        else{
            return SurveyPreviewFactory.GetAnonymousSurvey(surveyID);
        }
        
    }

    SurveyPreviewFactory.GetProtectedSurvey = function (surveyID, departmentRespondentID) {
        if (surveyID == null || surveyID == undefined || surveyID == '') {
            surveyID = 0;
        }
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyPreview/GetProtectedSurvey/',
                method: 'GET',
                params: { surveyId: surveyID, departmentRespondentIDIdEncrypted: departmentRespondentID },
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    SurveyPreviewFactory.GetAnonymousSurvey = function (surveyID) {
        if (surveyID == null || surveyID == undefined || surveyID == '') {
            surveyID = 0;
        }
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyPreview/GetAnonymousSurvey/',
                method: 'GET',
                params: { surveyId: surveyID },
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    SurveyPreviewFactory.GetPreviewSurvey = function (surveyID) {
        if (surveyID == null || surveyID == undefined || surveyID == '') {
            surveyID = 0;
        }
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyPreview/GetPreviewSurvey/',
                method: 'GET',
                params: { surveyId: surveyID },
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    SurveyPreviewFactory.GetAllPage = function (surveyID, surveyTokenID, firmContactId)
    {
        if (surveyID == null || surveyID == undefined || surveyID == '')
        {
            surveyID = 0;
        }
        if(!firmContactId){
            firmContactId = "";
        }
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyPreview/GetAllPage/',
                method: 'GET',
                params: { id: surveyID, surveyTokenId: surveyTokenID, firmContactIdString: firmContactId },
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {                
                defer.reject( e );
            } );
        return defer.promise;
    }

    SurveyPreviewFactory.Save = function (surveyPreview, surveyTokenID)
    {
        surveyPreview.SurveyTokenDetail = {};
        surveyPreview.SurveyTokenDetail.Token = surveyTokenID;
        var defer = $q.defer();
        $http.post( '/api/SurveyPreview/Save',
               JSON.stringify( surveyPreview ),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success( function ( data )
           {
               defer.resolve( data );
           } ).error( function ( e )
           {
               defer.reject( e );
           } );
        return defer.promise;
    }

    SurveyPreviewFactory.GetPreviousPage = function ( surveyPreview, surveyTokenId )
    {
        surveyPreview.SurveyTokenDetail = {};
        surveyPreview.SurveyTokenDetail.Token = surveyTokenId;
        var defer = $q.defer();
        $http.post( '/api/SurveyPreview/GetPreviousPage',
               JSON.stringify( surveyPreview ),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success( function ( data )
           {
               defer.resolve( data );
           } ).error( function ( e )
           {
               defer.reject( e );
           } );
        return defer.promise;
    }

    SurveyPreviewFactory.GetHorizontalQuestionMatrix = function ( id )
    {
        if ( id == null || id == undefined || id == '' )
        {
            id = 0;
        }
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyPreview/GetHorizontalQuestionMatrix/' + id,
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }

    SurveyPreviewFactory.GetFirmSurveyProgress = function ( surveyId )
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyPreview/GetFirmSurveyProgress/' + surveyId,
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }
    
    SurveyPreviewFactory.GetSurveyProgress = function ( surveyId, pageId )
    {
        var name = name;
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyPreview/GetSurveyProgress',
                method: 'GET',
                params: { surveyId: surveyId, pageId: pageId },
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }

    SurveyPreviewFactory.UploadFile = function ( files, questionId )
    {
        var defer = $q.defer();
        var formData = new FormData();
        for ( var file in files )
        {
            formData.append( "file", files[file] );
        }

        $http.post( '/api/SurveyPreview/UploadExcelFile/' + questionId, formData, { headers: { 'Content-Type': undefined } } )
        .success( function ( data, status, headers, config )
        {
            defer.resolve( data );
        } )
        .error( function ( e )
        {
            defer.reject( e );
        } );

        return defer.promise;
    }

    SurveyPreviewFactory.SubmitSurvey = function (surveyId, surveyTokenId, firmContactID, surveyName) {
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyPreview/SubmitSurvey/',
                method: 'GET',
                params: { surveyId: surveyId, surveyTokenId: surveyTokenId, firmContactIdEncrypted: firmContactID, surveyName: surveyName },
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }
    
    SurveyPreviewFactory.GeneratePDF = function (html) {
        var obj = {};
        obj.Param = html;
        var defer = $q.defer();
        $http.post('/SurveyPreview/GeneratePDF',
               JSON.stringify(obj),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success(function (data) {
               defer.resolve(data);
           }).error(function (e) {
               defer.reject(e);
           });
        return defer.promise;
    }

    SurveyPreviewFactory.Logout = function (surveyID, departmentRespondentID) {
      
        var defer = $q.defer();
        $http(
            {
                url: '/RespondentAuthentication/Logout/',
                method: 'GET',
                //params: { surveyId: surveyID, departmentRespondentIDIdEncrypted: departmentRespondentID },
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    SurveyPreviewFactory.GetImageDimensions = function (surveyID) {
        
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyPreview/GetImageDimensions/',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    return SurveyPreviewFactory;
}] );
mainApp.factory( 'SurveyFactory', ['$http', '$q', function ( $http, $q )
{
    var SurveyFactory = {};

    SurveyFactory.Save = function ( user )
    {
        var defer = $q.defer();
        $http.post( '/api/Survey/Save',
               JSON.stringify( user ),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success( function ( data )
           {
               defer.resolve( data );
           } ).error( function ( e )
           {
               defer.reject( e );
           } );
        return defer.promise;
    }

    SurveyFactory.GetByEncryptedID = function (id) {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/GetBySurveyID?surveyID='+ id,
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;

    }

    SurveyFactory.GetByID = function ( id )
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/Get/' + id,
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }


    SurveyFactory.Delete = function ( id )
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/Delete/' + id,
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }

    SurveyFactory.GetTotalRecordCount = function ( keyword,surveyStatus )
    {
        //alert('SurveyFactory.GetTotalRecordCount:' + keyword);

        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/GetSurveyCount',
                params: { keyword: keyword, surveyStatus: surveyStatus },
                method: 'POST',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );

        return defer.promise;
    }

    
    SurveyFactory.Get = function ( id )
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/Get',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }

    SurveyFactory.GetLiveSurvey = function ()
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/GetLiveSurvey',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }

    SurveyFactory.UploadImage = function ( file)
    {
        var defer = $q.defer();
        var fd = new FormData();
        fd.append( "file", file );
        $http.post( '/api/Survey/UploadImage' ,
            fd,
            {
                headers: { 'Content-Type': undefined },
                transformRequest: angular.identity
            } ).success( function ( data )
            {
                defer.resolve( data );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );

        return defer.promise;
    }

    SurveyFactory.IsSurveyNameExists = function (id,name)
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/IsSurveyNameExists',
                method: 'GET',
                params: { id:id,name: name },
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    SurveyFactory.GetSurveyForQuestionID = function ( questionID )
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/GetSurveyForQuestionID',
                params:{questionID:questionID},
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }

    SurveyFactory.ScheduleSurvey = function (user) {
        var defer = $q.defer();
        $http.post('/api/Survey/ScheduleSurvey',
               JSON.stringify(user),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success(function (data) {
               defer.resolve(data);
           }).error(function (e) {
               defer.reject(e);
           });
        return defer.promise;
    }
    SurveyFactory.GetByID = function (id) {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/Get/' + id,
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }


    SurveyFactory.GetTotalRecordCount = function (keyword) {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/GetLiveSurveyCount',
                params: { keyword: keyword },
                method: 'POST',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });

        return defer.promise;
    }

    SurveyFactory.GetByPager = function (pager) {
        var defer = $q.defer();
        $http.post('/api/Survey/SearchLiveOnKeyword',
               JSON.stringify({
                   Keyword: pager.Keyword,
                   PageNumber: pager.CurrentPage,
                   QuestionCount: pager.PageSize,
                   OrderByFilter: pager.SortParam,
                   IsOrderAscending: pager.IsAscending
               }),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success(function (data) {
               defer.resolve(data);
           }).error(function (e) {
               defer.reject(e);
           });
        return defer.promise;

    }

    SurveyFactory.GetByPagerEncrypted = function (pager) {
        var defer = $q.defer();
        $http.post('/api/Survey/SearchLiveOnKeywordEncrypted',
               JSON.stringify({
                   Keyword: pager.Keyword,
                   PageNumber: pager.CurrentPage,
                   QuestionCount: pager.PageSize,
                   OrderByFilter: pager.SortParam,
                   IsOrderAscending: pager.IsAscending
               }),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success(function (data) {
               defer.resolve(data);
           }).error(function (e) {
               defer.reject(e);
           });
        return defer.promise;

    }


    SurveyFactory.Get = function (id) {
        var defer = $q.defer();
        $http(
            {
                url: '/api/Survey/Get',
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }

    SurveyFactory.GetModeratorSurveyByPager = function (pager) {
        var defer = $q.defer();
        $http.post('/api/Survey/GetModeratorSurveyList',
               JSON.stringify({
                   Keyword: pager.Keyword,
                   PageNumber: pager.CurrentPage,
                   QuestionCount: pager.PageSize,
                   OrderByFilter: pager.SortParam,
                   IsOrderAscending: pager.IsAscending
               }),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success(function (data) {
               defer.resolve(data);
           }).error(function (e) {
               defer.reject(e);
           });
        return defer.promise;

    }

    SurveyFactory.GetModeratorSurveyCount = function (surveyName) {
        var defer = $q.defer();
        $http.post('/api/Survey/GetModeratorSurveyCount/',
                JSON.stringify({
                    Keyword: surveyName,
                }),
               {
                   headers: {
                       'Content-Type': 'application/json'
                   }
               }
           ).success(function (data) {
               defer.resolve(data);
           }).error(function (e) {
               defer.reject(e);
           });
        return defer.promise;
    }



    return SurveyFactory;
}] );
mainApp.factory('surveyStatisticsFactory', surveyStatisticsFactory);
surveyStatisticsFactory.$inject = ['$http', '$q']

function surveyStatisticsFactory($http, $q) {
    var surveyStatisticsFactory = {};
    surveyStatisticsFactory.GetSurveyStatistics = GetSurveyStatistics;
    surveyStatisticsFactory.GetSurveyStatisticsByFilter = GetSurveyStatisticsByFilter;
    surveyStatisticsFactory.GetLiveSurvey = GetLiveSurvey;

    function GetSurveyStatistics(status) {
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyStatistics/Get',
                method: 'GET',
                params: { status: status },
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }


    function GetSurveyStatisticsByFilter( status, filter )
    {
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyStatistics/GetByFilter',
                method: 'GET',
                params: { status: status, filter: filter },
                headers: { 'content-type': 'application/json' }
            } ).success( function ( d )
            {
                defer.resolve( d );
            } ).error( function ( e )
            {
                defer.reject( e );
            } );
        return defer.promise;
    }
    function GetLiveSurvey(startDate, endDate) {
        var params = {
            startDate: startDate,
            endDate: endDate
        };
        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyStatistics/Get',
                method: 'GET',
                params: params,
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });
        return defer.promise;
    }
    return surveyStatisticsFactory;
}


mainApp.factory('SurveyTokenFactory', ['$http', '$q', function ($http, $q) {
    var SurveyTokenFactory = {};

    SurveyTokenFactory.GetSurveyTokenBySurveyAndContact = function (surveyID, FirmContactID) {
        //alert('SurveyFactory.GetTotalRecordCount:' + keyword);

        var defer = $q.defer();
        $http(
            {
                url: '/api/SurveyToken/GetSurveyTokenBySurveyAndContact',
                params: { surveyID: surveyID, FirmContactID: FirmContactID },
                method: 'GET',
                headers: { 'content-type': 'application/json' }
            }).success(function (d) {
                defer.resolve(d);
            }).error(function (e) {
                defer.reject(e);
            });

        return defer.promise;
    }

   

    return SurveyTokenFactory;
}]);
mainApp.factory('messageInterceptor', messageInterceptor);
messageInterceptor.$inject = ['$q', '$injector'];
function messageInterceptor($q, $injector)
{
    var requestInterceptor = {
        responseError: function (response) {
            var $http = $injector.get('$http');
            var $ngBootbox = $injector.get('$ngBootbox');
            var $rootScope = $injector.get('$rootScope');
            var $state = $injector.get('$state');
            if (response.status == 410) {
                var deferred = $q.defer();
                $ngBootbox.alert(response.statusText);
            }
            else if (response.status == 417) {
                var deferred = $q.defer();
                $rootScope.ErrorMessage = response.statusText;
                $rootScope.IsLinkVisibleOnError = true;
                $state.go("unauthorized");
            }
            return $q.reject(response);
        }
    };

    return requestInterceptor;
}
