var wacorpApp = angular.module('wacorpApp',
    ['ngRoute', 'ngMessages', 'ngMask', 'ngResource', 'ngAnimate', 'ngCookies','elif',
        'base64', 'angularFileUpload', 'angularValidator', 'angucomplete-alt',
        'ui.bootstrap', 'chieffancypants.loadingBar', 'ngDialog', 'autoComplete', 'angularUtils.directives.dirPagination', 'ngIdle'],
        //, 'treasure-overlay-spinner'
        function ($httpProvider) {
            // Use x-www-form-urlencoded Content-Type
            $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
            $httpProvider.defaults.cache = false;

            /**
             * The workhorse; converts an object to x-www-form-urlencoded serialization.
             * @param {Object} obj
             * @return {String}
             */
            var param = function (obj) {
                var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

                for (name in obj) {
                    value = obj[name];

                    if (value instanceof Array) {
                        for (i = 0; i < value.length; ++i) {
                            subValue = value[i];
                            fullSubName = name + '[' + i + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    }
                    else if (value instanceof Object) {
                        for (subName in value) {
                            subValue = value[subName];
                            fullSubName = name + '[' + subName + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    }
                    else if (value !== undefined && value !== null)
                        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
                }

                return query.length ? query.substr(0, query.length - 1) : query;
            };

            // Override $http service's default transformRequest
            $httpProvider.defaults.transformRequest = [function (data) {
                return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
            }];
        });

//wacorpApp.use(function (req, res, next) {
//    res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers");
//    req.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers");
//})

wacorpApp.run(function ($rootScope, $location, wacorpService, membershipService, Idle) {
    $rootScope.$on('SessionIdleStart', function () {
        Idle.watch();
    });

    // glyphicon glyphicon-plus
    // glyphicon glyphicon-euro
    $rootScope.sortedAscImageClass = "glyphicon glyphicon-sort-by-attributes";
    $rootScope.sortedDescImageClass = "glyphicon glyphicon-sort-by-attributes-alt";

    $rootScope.$on('IdleStart', function () {
        wacorpService.sessionDialog();
    });

    $rootScope.$on('IdleTimeout', function () {
        Idle.unwatch();
        wacorpService.closeAllDialog();

        /* Logout user */
        membershipService.removeUserData();

        wacorpService.alertDialog(messages.Session.Timeout, function () {
            $location.path('/');
            window.location.reload(false);
        });
    });

    $rootScope.$on('IdleEnd', function () {
        wacorpService.closeAllDialog();
    });
});

//wacorpApp.run(['$document', function ($element) {
//    var bodyElement = angular.element($element);
//    //var elements = $document[0].getElementsByTagName('input');
//    bodyElement.bind('change', function (e) {
//        if ($(e.target).is("textarea") || ($(e.target).attr("type") != undefined && $(e.target).attr("type").toLowerCase() == "text")
//            || ($(e.target).attr("type") != undefined && $(e.target).attr("type").toLowerCase() == "email")
//            ) {
//            var val = $(e.target).val().toUpperCase();
//            $(e.target).val(val);
//            $(e.target).trigger("change");
//            return;
//        }
//    });
//}]);

var isNonUnicodeLetter = function (str) {
    return (/[^\u0000-\u007F]+/i).test(str);
};

var blurFocusDirective = function ($timeout) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, elm, attr, ctrl) {
            if (!ctrl) {
                return;
            }
            if (!attr.isNotUpperCase) {
                elm.on('blur', function (e) {
                    if ($(elm).is("textarea") || ($(elm).attr("type") != undefined && $(elm).attr("type").toLowerCase() == "text") ||
                        ($(elm).attr("type") != undefined && $(elm).attr("type").toLowerCase() == "email")) {
                        var formatted = elm.val().toUpperCase();
                        elm.val(formatted);
                        ctrl.$setViewValue(formatted);
                        scope.$apply();
                    }
                });

                elm.on('keypress', function (e) {
                    var keyCode = String.fromCharCode(e.keyCode)
                    if (isNonUnicodeLetter(keyCode))
                        e.preventDefault();
                });

                elm.on('paste', function (e) {
                    
                    $timeout(function () {
                        var inputval = $.trim(e.target.value);
                        if (inputval)
                        {
                            inputval = inputval.replace(/[^\u0000-\u007F]+/ig, '');
                            inputval = inputval.replace(/  /g, ' ');
                            elm.val(inputval);
                            ctrl.$setViewValue(inputval);
                            scope.$apply();
                        }
                    }, 100);
                });
            }
            else {
                $(elm).css("text-transform", "none");
            }
        }
    };
};

var liveChat = function ($interval) {
    return {
        restrict: 'A',
        templateUrl: "ng-app/view/livechat.html",
        link: function ($scope, $element) {
            angular.element(document).ready(function () {
                var stopInterval = $interval(function () {
                    if (typeof sWOTrackPage == 'function') {
                        $interval.cancel(stopInterval);
                        sWOTrackPage();
                    }
                }, 2000, 3);
            });
        }
    }
};

wacorpApp.directive('liveChat', liveChat);
wacorpApp.directive('input', blurFocusDirective);
wacorpApp.directive('select', blurFocusDirective);
wacorpApp.directive('textarea', blurFocusDirective);

wacorpApp.config(function ($routeProvider, $httpProvider, IdleProvider) {

    // session timeout
    IdleProvider.idle(sessionManager.timeOut);
    IdleProvider.timeout(sessionManager.alertBefore);

    // Add Loading Interceptor
    $httpProvider.interceptors.push('httpInterceptor');

    $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'] = 'Mon, 26 Jul 1997 05:00:00 GMT';

    $routeProvider.when('/Home', {
        templateUrl: 'ng-app/view/home/home.html'
    }).when('/', {
        templateUrl: 'ng-app/view/home/home.html',
        resolve: { isPageFound: isPageFound }

        // -------------------------User Account------------------------------//
    }).when('/UserRegistration', {
        templateUrl: 'ng-app/view/account/register.html',
        controller: 'registerController',
        caseInsensitiveMatch: true,
    }).when('/CreateAgentAccount/:id', {
        templateUrl: 'ng-app/view/account/inhouseAgent.html',
        controller: 'inhouseAgentController',
    }).when('/ForgotPassword', {
        templateUrl: 'ng-app/view/account/forgotpassword.html',
        controller: 'accountController',
        caseInsensitiveMatch: true,
    }).when('/ForgotUser', {
        templateUrl: 'ng-app/view/account/forgotuser.html',
        controller: 'accountController',
        caseInsensitiveMatch: true,
    }).when('/ChangePassword', {
        templateUrl: 'ng-app/view/account/changePassword.html',
        controller: 'accountController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AccountMaintenance', {
        templateUrl: 'ng-app/view/account/accountMaintenance.html',
        controller: 'accountMaintenanceController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AccountActivation', {
        templateUrl: 'ng-app/view/account/accountActivation.html',
        controller: 'accountActivationController',
        caseInsensitiveMatch: true,

        //***** Added 10/21/2019, KK
        //}).when('/AddAuthUser', {
        //    templateUrl: 'ng-app/view/account/addAuthUser.html',
        //    controller: 'addAuthUserController',
        //    caseInsensitiveMatch: true,
        //    resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Searches------------------------------//
    }).when('/AdvancedSearch', {
        templateUrl: 'ng-app/view/businesssearch/advancedSearch.html',
        controller: 'advancedSearchController'
    }).when('/BusinessSearch', {
        templateUrl: 'ng-app/view/businesssearch/businessSearch.html',
        controller: 'businessSearchController',
        caseInsensitiveMatch: true,
    }).when('/cftBusinessSearch', {
        templateUrl: 'ng-app/view/businesssearch/cftBusinessSearch.html',
        controller: 'cftBusinessSearchController',
        caseInsensitiveMatch: true,
    }).when('/trademarkHomeSearch', {
        templateUrl: 'ng-app/view/businesssearch/trademarkHomeSearch.html',
        controller: 'trademarkHomeSearchController',
        caseInsensitiveMatch: true,
    }).when('/cftBusinessDetails', {
        templateUrl: 'ng-app/view/businesssearch/cftBusinessDetails.html',
        controller: 'cftBusinessDetailsController',
        caseInsensitiveMatch: true,
    }).when('/trademarkDetails', {
        templateUrl: 'ng-app/view/businesssearch/trademarkDetails.html',
        controller: 'trademarkDetailsController',
        caseInsensitiveMatch: true,
    }).when('/CorporationSearch', {
        templateUrl: 'ng-app/view/businesssearch/loginBusinessSearch.html',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/BusinessSearch/BusinessInformation', {
        templateUrl: 'ng-app/view/businesssearch/businessInformation.html',
        controller: 'businessSearchController',
        caseInsensitiveMatch: true,
    }).when('/BusinessSearch/BusinessFilings', {
        templateUrl: 'ng-app/view/businesssearch/businessFilings.html',
        controller: 'businessSearchController',
        caseInsensitiveMatch: true,
    }).when('/BusinessSearch/BusinessNameHistory', {
        templateUrl: 'ng-app/view/businesssearch/businessNameHistory.html',
        controller: 'businessSearchController',
        caseInsensitiveMatch: true,
    }).when('/cftBusinessDetails', {
        templateUrl: 'ng-app/view/businesssearch/cftBusinessDetails.html',
        controller: 'cftBusinessDetailsController',
        caseInsensitiveMatch: true,
    }).when('/trademarkSearch', {
        templateUrl: 'ng-app/view/TradeMarkSearch/trademarkSearch.html',
        controller: 'trademarkSearchController',
        caseInsensitiveMatch: true,
    }).when('/trademarkInformation', {
        templateUrl: 'ng-app/view/TradeMarkSearch/trademarkInformation.html',
        controller: 'trademarkInformationController',
        caseInsensitiveMatch: true,
    }).when('/trademarkAdvancedSearch', {
        templateUrl: 'ng-app/view/TradeMarkSearch/trademarkAdvancedSearch.html',
        controller: 'trademarkAdvancedSearchController',
        caseInsensitiveMatch: true,
    }).when('/trademarkHomeAdvancedSearch', {
        templateUrl: 'ng-app/view/TradeMarkSearch/trademarkHomeAdvancedSearch.html',
        controller: 'trademarkHomeAdvancedSearchController',
        caseInsensitiveMatch: true,

    }).when('/Dashboard', {
        templateUrl: 'ng-app/view/dashboard/dashboard.html',
        controller: 'dashboardController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/Correspondence', {
        templateUrl: 'ng-app/view/dashboard/Correspondence.html',
        controller: 'dashboardController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/Receipts', {
        templateUrl: 'ng-app/view/dashboard/Receipts.html',
        controller: 'dashboardController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/Inbox', {
        templateUrl: 'ng-app/view/dashboard/MailBox.html',
        controller: 'dashboardController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/draftFiling', {
        templateUrl: 'ng-app/view/ShoppingCart/draftFiling.html',
        controller: 'draftFilingController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Commercical Registered Agents------------------------------//
    }).when('/CommercialRegisteredAgents', {
        templateUrl: 'ng-app/view/CommercialRegisteredAgents/CommercialRegisteredAgents.html',
        controller: 'CommercialRegisteredAgentsController',
        caseInsensitiveMatch: true,

        // -------------------------Annual Report------------------------------//
    }).when('/AnnualReport/BusinessSearch', {
        templateUrl: 'ng-app/view/annualreport/Index.html',
        controller: 'annualReportController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AnnualReport', {
        templateUrl: 'ng-app/view/annualreport/AnnualReport.html',
        controller: 'annualReportController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AnnualReport/:id', {
        templateUrl: 'ng-app/view/annualreport/AnnualReport.html',
        controller: 'annualReportController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AnnualReportReview/', {
        templateUrl: 'ng-app/view/annualreport/AnnualReportReview.html',
        controller: 'annualReportReviewController',
        resolve: { isAuthenticated: isAuthenticated }

        // ------------------------- Amendment of Foriegn Registration Statement ------------------------------//
    }).when('/AmendmentofForiegnRegistrationStatement/BusinessSearch', {
        templateUrl: 'ng-app/view/amendmentofforiegnregistrationstatement/Index.html',
        controller: 'amendmentOfForiegnRegistrationStatementController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AmendmentofForiegnRegistrationStatement', {
        templateUrl: 'ng-app/view/amendmentofforiegnregistrationstatement/AmendmentOfForiegnRegistrationStatement.html',
        controller: 'amendmentOfForiegnRegistrationStatementController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AmendmentofForiegnRegistrationStatement/:id', {
        templateUrl: 'ng-app/view/amendmentofforiegnregistrationstatement/AmendmentOfForiegnRegistrationStatement.html',
        controller: 'amendmentOfForiegnRegistrationStatementController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AmendmentofForiegnRegistrationStatementReview/', {
        templateUrl: 'ng-app/view/amendmentofforiegnregistrationstatement/AmendmentOfForiegnRegistrationStatementReview.html',
        controller: 'amendmentOfForiegnRegistrationStatementReviewController',
        resolve: { isAuthenticated: isAuthenticated }

        // ------------------------- Amended Annual Report ------------------------------//
    }).when('/AmendedAnnualReport/BusinessSearch', {
        templateUrl: 'ng-app/view/amendannualreport/Index.html',
        controller: 'amendedAnnualReportController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AmendedAnnualReport', {
        templateUrl: 'ng-app/view/amendannualreport/AmendedAnnualReport.html',
        controller: 'amendedAnnualReportController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AmendedAnnualReport/:id', {
        templateUrl: 'ng-app/view/amendannualreport/AmendedAnnualReport.html',
        controller: 'amendedAnnualReportController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/AmendedAnnualReportReview/', {
        templateUrl: 'ng-app/view/amendannualreport/AmendedAnnualReportReview.html',
        controller: 'amendedAnnualReportReviewController',
        resolve: { isAuthenticated: isAuthenticated }

        // ------------------------- Certified Copies ------------------------------//
    }).when('/CopyRequest/BusinessSearch', {
        templateUrl: 'ng-app/view/CopyRequest/index.html',
        controller: 'copyRequestController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CopyRequest/Edit', {
        templateUrl: 'ng-app/view/CopyRequest/CopyRequest.html',
        controller: 'copyRequestController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CopyRequest/:id', {
        templateUrl: 'ng-app/view/CopyRequest/CopyRequest.html',
        controller: 'copyRequestController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CopyRequest/:id/:cftType', {
        templateUrl: 'ng-app/view/CopyRequest/CopyRequest.html',
        controller: 'copyRequestController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CopyRequest', {
        templateUrl: 'ng-app/view/CopyRequest/CopyRequest.html',
        controller: 'copyRequestController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CopyRequestcftSearch', {
        templateUrl: 'ng-app/view/CopyRequest/CopyRequestcftSearch.html',
        controller: 'CopyRequestcftSearchController',
        caseInsensitiveMatch: true,

        // ------------------------- Initial Report ------------------------------//
    }).when('/InitialReport/SearchBusiness', {
        templateUrl: 'ng-app/view/initialreport/index.html',
        controller: 'initialreportController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/InitialReport', {
        templateUrl: 'ng-app/view/initialreport/initialReport.html',
        controller: 'initialreportController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/InitialReport/:id', {
        templateUrl: 'ng-app/view/initialreport/initialReport.html',
        controller: 'initialreportController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/InitialReportReview', {
        templateUrl: 'ng-app/view/initialreport/initialReportReview.html',
        controller: 'initialReportReviewController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/RegisterAgent', { // Register Agent is added for preparing directives, this can be deleted
        templateUrl: 'ng-app/view/partial/RegisterAgent.html',
        controller: 'registerAgentController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/businessFormationIndex', { // Business Formation Index page.
        templateUrl: 'ng-app/view/Formations/Index.html',
        controller: 'indexController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/businessFormation', {
        templateUrl: 'ng-app/view/Formations/businessFormation.html',
        controller: 'BusinessFormationController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/foreignbusinessFormation', {
        templateUrl: 'ng-app/view/Formations/foreignbusinessFormation.html',
        controller: 'foreignbusinessFormationController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/LLCbusinessFormation', {
        templateUrl: 'ng-app/view/Formations/LLCbusinessFormation.html',
        controller: 'LLCbusinessFormationController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/LLCforeignbusinessFormation', {
        templateUrl: 'ng-app/view/Formations/LLCforeignbusinessFormation.html',
        controller: 'LLCforeignbusinessFormationController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/LLPbusinessFormation', {
        templateUrl: 'ng-app/view/Formations/LLPbusinessFormation.html',
        controller: 'LLPbusinessFormationController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/LLPforeignbusinessFormation', {
        templateUrl: 'ng-app/view/Formations/LLPforeignbusinessFormation.html',
        controller: 'LLPforeignbusinessFormationController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/shoppingcart', {
        templateUrl: 'ng-app/view/shoppingCart/index.html',
        controller: 'shoppingCartController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/payment', {
        templateUrl: 'ng-app/view/shoppingCart/payment.html',
        //controller: 'paymentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/paymentdone', {
        templateUrl: 'ng-app/view/shoppingCart/paymentdone.html',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/cartitems', {
        templateUrl: 'ng-app/view/shoppingCart/cartitems.html',
        caseInsensitiveMatch: true,
        controller: 'cartItemsController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/Review', {
        templateUrl: 'ng-app/view/Formations/Review.html',
        controller: 'reviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/LLCReview', {
        templateUrl: 'ng-app/view/Formations/LLCReview.html',
        controller: 'LLCReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/LLPReview', {
        templateUrl: 'ng-app/view/Formations/LLPReview.html',
        controller: 'LLPReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/foreignReview', {
        templateUrl: 'ng-app/view/Formations/foreignReview.html',
        controller: 'foreignReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/LLCforeignReview', {
        templateUrl: 'ng-app/view/Formations/LLCforeignReview.html',
        controller: 'LLCforeignReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/LLPforeignReview', {
        templateUrl: 'ng-app/view/Formations/LLPforeignReview.html',
        controller: 'LLPforeignReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // ------------------------- Statement of Change ------------------------------//
    }).when('/StatementofChangeIndex', {
        templateUrl: 'ng-app/view/StatementofChange/Index.html',
        controller: 'statementofChangeController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/StatementofChange', {
        templateUrl: 'ng-app/view/StatementofChange/StatementofChange.html',
        controller: 'statementofChangeController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/StatementofChangeReview', {
        templateUrl: 'ng-app/view/StatementofChange/Review.html',
        controller: 'statementofChangeReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        //---------------------------  Reinstatement --------------------------------//
    }).when('/ReinstatementIndex', {
        templateUrl: 'ng-app/view/Reinstatement/Index.html',
        controller: 'reinstatementController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/Reinstatement', {
        templateUrl: 'ng-app/view/Reinstatement/Reinstatement.html',
        controller: 'reinstatementController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/Reinstatement/:id', {
        templateUrl: 'ng-app/view/Reinstatement/Reinstatement.html',
        controller: 'reinstatementController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/ReinstatementReview/', {
        templateUrl: 'ng-app/view/Reinstatement/ReinstatementReview.html',
        controller: 'reinstatementReviewController',
        resolve: { isAuthenticated: isAuthenticated }

        // ------------------------- Certificate Of Dissolution ------------------------------//
    }).when('/CertificateOfDissolutionIndex', {
        templateUrl: 'ng-app/view/CertificateOfDissolution/Index.html',
        controller: 'CertificateOfDissolutionController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CertificateOfDissolution', {
        templateUrl: 'ng-app/view/CertificateOfDissolution/CertificateOfDissolution.html',
        controller: 'CertificateOfDissolutionController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CertificateOfDissolutionReview', {
        templateUrl: 'ng-app/view/CertificateOfDissolution/CertificateOfDissolutionReview.html',
        controller: 'CertificateOfDissolutionReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // ------------------------- Articles Of Dissolution ------------------------------//
    }).when('/ArticlesOfDissolutionIndex', {
        templateUrl: 'ng-app/view/ArticlesOfDissolution/Index.html',
        controller: 'ArticlesOfDissolutionController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/ArticlesOfDissolution', {
        templateUrl: 'ng-app/view/ArticlesOfDissolution/ArticlesOfDissolution.html',
        controller: 'ArticlesOfDissolutionController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/ArticlesOfDissolutionReview', {
        templateUrl: 'ng-app/view/ArticlesOfDissolution/ArticlesOfDissolutionReview.html',
        controller: 'ArticlesOfDissolutionReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // ------------------- Statement of Withdrawal ---------------------------//
    }).when('/StatementofWithdrawalIndex', {
        templateUrl: 'ng-app/view/StatementOfWithdrawal/index.html',
        controller: 'statementOfWithdrawalIndexController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/StatementofWithdrawal', {
        templateUrl: 'ng-app/view/StatementOfWithdrawal/StatementOfWithdrawal.html',
        controller: 'statementOfWithdrawalController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/StatementofWithdrawalReview', {
        templateUrl: 'ng-app/view/StatementOfWithdrawal/StatementOfWithdrawalReview.html',
        controller: 'statementOfWithdrawalReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // ------------------- Voluntary Termination ---------------------------//
    }).when('/VoluntaryTerminationIndex', {
        templateUrl: 'ng-app/view/VoluntaryTermination/index.html',
        controller: 'voluntaryTerminationIndexController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/VoluntaryTermination', {
        templateUrl: 'ng-app/view/VoluntaryTermination/VoluntaryTermination.html',
        controller: 'voluntaryTerminationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/VoluntaryTerminationReview', {
        templateUrl: 'ng-app/view/VoluntaryTermination/VoluntaryTerminationReview.html',
        controller: 'voluntaryTerminationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        //---------------------------Business Amendment--------------------------//
    }).when('/BusinessAmendmentIndex', {
        templateUrl: 'ng-app/view/businessAmendment/index.html',
        controller: 'businessAmendmentIndexController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/BusinessAmendment', {
        templateUrl: 'ng-app/view/businessAmendment/businessAmendment.html',
        controller: 'businessAmendmentController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/BusinessAmendment/:id', {
        templateUrl: 'ng-app/view/businessAmendment/businessAmendment.html',
        controller: 'businessAmendmentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/BusinessAmendmentReview', {
        templateUrl: 'ng-app/view/businessAmendment/businessAmendmentReview.html',
        controller: 'businessAmendmentReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Commercial Statement of Change ------------------------------//
    }).when('/CommercialStatementofChangeIndex', {
        templateUrl: 'ng-app/view/CommercialStatementofChange/Index.html',
        controller: 'commercialStatementofChangeController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CommercialStatementofChange', {
        templateUrl: 'ng-app/view/CommercialStatementofChange/StatementofChange.html',
        controller: 'commercialStatementofChangeController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CommercialStatementofChangeReview', {
        templateUrl: 'ng-app/view/CommercialStatementofChange/Review.html',
        controller: 'commercialStatementofChangeReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // ------------------------- Statement of Termination ------------------------------//
    }).when('/StatementofTerminationIndex', {
        templateUrl: 'ng-app/view/StatementofTermination/Index.html',
        controller: 'statementofTerminationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/StatementofTermination', {
        templateUrl: 'ng-app/view/StatementofTermination/StatementofTermination.html',
        controller: 'statementofTerminationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/StatementofTerminationReview', {
        templateUrl: 'ng-app/view/StatementofTermination/Review.html',
        controller: 'statementofTerminationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Commercial Statement of Termination ------------------------------//
    }).when('/CommercialStatementofTerminationIndex', {
        templateUrl: 'ng-app/view/CommercialStatementofTermination/StatementofTermination.html',
        controller: 'commercialStatementofTerminationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CommercialStatementofTermination', {
        templateUrl: 'ng-app/view/CommercialStatementofTermination/StatementofTermination.html',
        controller: 'commercialStatementofTerminationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CommercialStatementofTerminationReview', {
        templateUrl: 'ng-app/view/CommercialStatementofTermination/Review.html',
        controller: 'commercialStatementofTerminationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Commercial Listing Statement ------------------------------//
    }).when('/CommercialListingStatement', {
        templateUrl: 'ng-app/view/CommercialListingStatement/CommercialListingStatement.html',
        controller: 'commercialListingStatementController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/CommercialListingStatementReview', {
        templateUrl: 'ng-app/view/CommercialListingStatement/Review.html',
        controller: 'commercialListingStatementReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Charities Registration ------------------------------//
    }).when('/charitiesRegistration', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRegistration.html',
        controller: 'charitiesRegistrationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesRegistrationReview', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRegistrationReview.html',
        controller: 'charitiesRegistrationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Charities Optional Registration ------------------------------//
    }).when('/charitiesOptionalRegistration', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRegistration.html',
        controller: 'charitiesRegistrationController',
        caseInsensitiveMatch: true,
    }).when('/charitiesOptionalRegistrationReview', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRegistrationReview.html',
        controller: 'charitiesRegistrationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // --------------Charities Optional Registration Update-------------------------//
    }).when('/charitiesOptionalSearch/:charitySearchType', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesOptionalSearch.html',
        controller: 'charitiesOptionalSearchController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesOptionalRegistrationUpdate/:CharityID', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesOptionalRegistrationUpdate.html',
        controller: 'charitiesOptionalRegistrationUpdateController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesOptionalRegistrationUpdate', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesOptionalRegistrationUpdate.html',
        controller: 'charitiesOptionalRegistrationUpdateController',
        caseInsensitiveMatch: true,
    }).when('/charitiesOptionalRegistrationUpdateReview', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesOptionalRegistrationUpdateReview.html',
        controller: 'charitiesOptionalRegistrationUpdateReviewController',
        caseInsensitiveMatch: true,

        // -------------------------Charities Renewal ------------------------------//
    }).when('/charitiesSearch/:charitySearchType', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesSearch.html',
        controller: 'charitiesSearchController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesRenewal/:CharityID', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRenewal.html',
        controller: 'charitiesRenewalController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesRenewal', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRenewal.html',
        controller: 'charitiesRenewalController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesRenewalReview', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRenewalReview.html',
        controller: 'charitiesRenewalReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Charities Optional Renewal------------------------//
    }).when('/charitiesOptionalRenewal/:CharityID', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRenewal.html',
        controller: 'charitiesRenewalController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesOptionalRenewal', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRenewal.html',
        controller: 'charitiesRenewalController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesOptionalRenewalReview', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesRenewalReview.html',
        controller: 'charitiesRenewalReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Charities Amendment ------------------------------//
    }).when('/charitiesAmendment/:CharityID', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesAmendment.html',
        controller: 'charitiesAmendmentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesAmendment', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesAmendment.html',
        controller: 'charitiesAmendmentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesAmendmentReview', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesAmendmentReview.html',
        controller: 'charitiesAmendmentReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Charities Optional Amendment ------------------------------//
    }).when('/charitiesOptionalAmendment/:CharityID', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesAmendment.html',
        controller: 'charitiesAmendmentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesOptionalAmendment', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesAmendment.html',
        controller: 'charitiesAmendmentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesOptionalAmendmentReview', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesAmendmentReview.html',
        controller: 'charitiesAmendmentReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Charities Closure ------------------------------//
    }).when('/charitiesClosure/:CharityID', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesClosure.html',
        controller: 'charitiesClosureController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesClosure', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesClosure.html',
        controller: 'charitiesClosureController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesClosureReview', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesClosureReview.html',
        controller: 'charitiesClosureReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Charities Optional Closure ------------------------------//
    }).when('/charitiesOptionalClosure/:CharityID', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesClosure.html',
        controller: 'charitiesClosureController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesOptionalClosure', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesClosure.html',
        controller: 'charitiesClosureController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesOptionalClosureReview', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesClosureReview.html',
        controller: 'charitiesClosureReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        //--------------------------Optional Qualifier----------------------------------------------------//
    }).when('/charitiesOptionalQualifier', {
        templateUrl: 'ng-app/view/CFT/Charities/charitiesOptionalQualifier.html',
        controller: 'charitiesOptionalQualifierController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Fundraising Service Contract Registration------------------------------//
    }).when('/submitFundraisingServiceContract/:CharityID', {
        templateUrl: 'ng-app/view/CFT/Charities/submitFundraisingServiceContract.html',
        controller: 'submitFundraisingServiceContractController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/submitFundraisingServiceContract', {
        templateUrl: 'ng-app/view/CFT/Charities/submitFundraisingServiceContract.html',
        controller: 'submitFundraisingServiceContractController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/submitFundraisingServiceContractReview', {
        templateUrl: 'ng-app/view/CFT/Charities/submitFundraisingServiceContractReview.html',
        controller: 'submitFundraisingServiceContractReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Fundraising Service Contract Amendment------------------------------//
    }).when('/submitFundraisingServiceContractAmendment/:CharityID', {
        templateUrl: 'ng-app/view/CFT/Charities/submitFundraisingServiceContractAmendment.html',
        controller: 'submitFundraisingServiceContractAmendmentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/submitFundraisingServiceContractAmendment', {
        templateUrl: 'ng-app/view/CFT/Charities/submitFundraisingServiceContractAmendment.html',
        controller: 'submitFundraisingServiceContractAmendmentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/submitFundraisingServiceContractAmendmentReview', {
        templateUrl: 'ng-app/view/CFT/Charities/submitFundraisingServiceContractAmendmentReview.html',
        controller: 'submitFundraisingServiceContractAmendmentReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Fundraiser Registration------------------------------//
    }).when('/fundraiserRegistration', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/commercialFundraiserRegistration.html',
        controller: 'commercialFundraiserRegistrationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserRegistrationReview', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserRegistrationReview.html',
        controller: 'fundraiserRegistrationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Fundraiser Renewal------------------------------//
    }).when('/fundraiserSearch/:fundraiserSearchType', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserSearch.html',
        controller: 'fundraiserSearchController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserRenewal', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserRenewal.html',
        controller: 'fundraiserRenewalController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserRenewal/:id', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserRenewal.html',
        controller: 'fundraiserRenewalController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserRenewalReview', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserRenewalReview.html',
        controller: 'fundraiserRenewalReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Fundraiser Amendment------------------------------//
    }).when('/fundraiserAmendment/:id', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserAmendment.html',
        controller: 'fundraiserAmendmentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserAmendment', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserAmendment.html',
        controller: 'fundraiserAmendmentController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserAmendmentReview', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserAmendmentReview.html',
        controller: 'fundraiserAmendmentReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Fundraiser Closure ------------------------------//
    }).when('/fundraiserClosure/:FundraiserID', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserClosure.html',
        controller: 'fundraiserClosureController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserClosure', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserClosure.html',
        controller: 'fundraiserClosureController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserClosureReview', {
        templateUrl: 'ng-app/view/CFT/Fundraisers/fundraiserClosureReview.html',
        controller: 'fundraiserClosureReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Fundraiser Registration------------------------------//
    }).when('/trusteeRegistration', {
        templateUrl: 'ng-app/view/CFT/Trust/trusteeRegistration.html',
        controller: 'trusteeRegistrationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/trusteeRegistrationReview', {
        templateUrl: 'ng-app/view/CFT/Trust/trusteeRegistrationReview.html',
        controller: 'trusteeRegistrationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Trustee Renewal------------------------------//
    }).when('/trusteeSearch/:trusteeSearchType', {
        templateUrl: 'ng-app/view/CFT/Trustees/trusteesSearch.html',
        controller: 'trusteeSearchController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/trusteeRenewalSearch', {
        templateUrl: 'ng-app/view/CFT/Trustees/trusteeRenewalSearch.html',
        controller: 'trusteeRenewalSearchController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/trusteeRenewal', {
        templateUrl: 'ng-app/view/CFT/Trustees/trusteeRenewal.html',
        controller: 'trusteeRenewalController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/trusteeRenewal/:id', {
        templateUrl: 'ng-app/view/CFT/Trustees/trusteeRenewal.html',
        controller: 'trusteeRenewalController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/trusteeRenewalReview', {
        templateUrl: 'ng-app/view/CFT/Trustees/trusteeRenewalReview.html',
        controller: 'trusteeRenewalReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Trustee Closure ------------------------------//
    }).when('/trusteeClosure/:TrustID', {
        templateUrl: 'ng-app/view/CFT/Trustees/trusteeClosure.html',
        controller: 'trustClosureController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/trusteeClosure', {
        templateUrl: 'ng-app/view/CFT/Trustees/trusteeClosure.html',
        controller: 'trustClosureController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/trustClosureReview', {
        templateUrl: 'ng-app/view/CFT/Trustees/trusteeClosureReview.html',
        controller: 'trustClosureReview',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        //}).when('/trustClosure/:TrustID', {
        //    templateUrl: 'ng-app/view/CFT/Trustees/trusteeClosure.html',
        //    controller: 'trustClosureController',
        //    caseInsensitiveMatch: true,
        //    resolve: { isAuthenticated: isAuthenticated }
        //}).when('/trustClosure', {
        //    templateUrl: 'ng-app/view/CFT/Trustees/trusteeClosure.html',
        //    controller: 'trustClosureController',
        //    caseInsensitiveMatch: true,
        //    resolve: { isAuthenticated: isAuthenticated }
        //}).when('/trustClosureReview', {
        //    templateUrl: 'ng-app/view/CFT/Trustees/trustClosureReview.html',
        //    controller: 'trustClosureReviewController',
        //    caseInsensitiveMatch: true,
        //    resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Re-Registration------------------------------//
    }).when('/cftReRegistration', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/cftReRegistrationSearch.html',
        controller: 'cftReRegistrationSearchController',
        caseInsensitiveMatch: true

        // -------------------------Charities Re-Registration ------------------------------//
    }).when('/charitiesReRegistration/:CharityID', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/charitiesReRegistration.html',
        controller: 'charitiesReRegistrationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesReRegistration', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/charitiesReRegistration.html',
        controller: 'charitiesReRegistrationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/charitiesReRegistrationReview', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/charitiesReRegistrationReview.html',
        controller: 'charitiesReRegistrationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Fundraiser Re-Registration ------------------------------//
    }).when('/fundraiserReRegistration/:FundraisedID', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/fundraiserReRegistration.html',
        controller: 'fundraiserReRegistrationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserReRegistration', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/fundraiserReRegistration.html',
        controller: 'fundraiserReRegistrationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/fundraiserReRegistrationReview', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/fundraiserReRegistrationReview.html',
        controller: 'fundraiserReRegistrationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Trust Re-Registration ------------------------------//
    }).when('/trustReRegistration/:TrustID', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/trusteeReRegistration.html',
        controller: 'trusteeReRegistrationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/trustReRegistration', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/trusteeReRegistration.html',
        controller: 'trusteeReRegistrationController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/trustReRegistrationReview', {
        templateUrl: 'ng-app/view/CFT/ReRegistration/trusteeReRegistrationReview.html',
        controller: 'trusteeReRegistrationReviewController',
        caseInsensitiveMatch: true,
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Charities and Fundraisers Public Search------------------------------//
    }).when('/cftSearch', {
        templateUrl: 'ng-app/view/CFT/CFTSearch/cftSearch.html',
        controller: 'cftSearchController',
        caseInsensitiveMatch: true

        //--------------------------- charities foundation organization ----------------------//
    }).when('/organization', {
        templateUrl: 'ng-app/view/CFT/CFTSearch/organigation.html',
        controller: 'organizationController',
        caseInsensitiveMatch: true

        //--------------------------- charities foundation organization Filling ----------------------//
    }).when('/CFTSearch/cftSearchOrganizationFilings', {
        templateUrl: 'ng-app/view/CFT/CFTSearch/cftSearchOrganizationFilings.html',
        controller: 'organizationController',
        caseInsensitiveMatch: true

        //--------------------------- charities foundation organization History ----------------------//
    }).when('/CFTSearch/cftSearchOrganizationNameHistory', {
        templateUrl: 'ng-app/view/CFT/CFTSearch/cftSearchOrganizationNameHistory.html',
        controller: 'organizationController',
        caseInsensitiveMatch: true
    }).when('/mergedorganization', {
        templateUrl: 'ng-app/view/CFT/CFTSearch/mergedorganigation.html',
        controller: 'mergedorganizationController',
        caseInsensitiveMatch: true

        // -------------------------One Click Annual Report------------------------------//
    }).when('/oneClickARSearch/BusinessSearch', {
        templateUrl: 'ng-app/view/OneClickAnnualReport/oneClickARSearch.html',
        controller: 'oneClickARSearchController',
        caseInsensitiveMatch: true
    }).when('/oneClickAnnualReport/:id', {
        templateUrl: 'ng-app/view/OneClickAnnualReport/oneClickAnnualReport.html',
        controller: 'oneClickAnnualReportController',
        caseInsensitiveMatch: true
    }).when('/oneClickAnnualReportSuccess', {
        templateUrl: 'ng-app/view/OneClickAnnualReport/oneClickARSuccess.html',
        controller: 'oneClickAnnualReportController',
        caseInsensitiveMatch: true

        //---------------------------  Requalification --------------------------------//
    }).when('/RequalificationIndex', {
        templateUrl: 'ng-app/view/Requalification/Index.html',
        controller: 'requalificationController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/Requalification', {
        templateUrl: 'ng-app/view/Requalification/Requalification.html',
        controller: 'requalificationController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/Requalification/:id', {
        templateUrl: 'ng-app/view/Requalification/Requalification.html',
        controller: 'requalificationController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/RequalificationReview/', {
        templateUrl: 'ng-app/view/Requalification/RequalificationReview.html',
        controller: 'requalificationReviewController',
        resolve: { isAuthenticated: isAuthenticated }

        // -------------------------Express Annual Report------------------------------//
    }).when('/expressAnnualReportSearch/BusinessSearch', {
        templateUrl: 'ng-app/view/ExpressAnnualReport/expressAnnualReportSearch.html',
        controller: 'expressAnnualReportSearchController',
        caseInsensitiveMatch: true
    }).when('/expressAnnualReport/:id', {
        templateUrl: 'ng-app/view/ExpressAnnualReport/expressAnnualReport.html',
        controller: 'expressAnnualReportController',
        caseInsensitiveMatch: true
    }).when('/expressAnnualReportReview', {
        templateUrl: 'ng-app/view/ExpressAnnualReport/expressAnnualReportReview.html',
        controller: 'expressAnnualReportReviewController',
        caseInsensitiveMatch: true
    }).when('/expressAnnualReportSuccess', {
        templateUrl: 'ng-app/view/ExpressAnnualReport/expressAnnualReportSuccess.html',
        controller: 'expressAnnualReportReviewController',
        caseInsensitiveMatch: true

        // ------------------------- Express PDF Certificate of Existence ------------------------------//
    }).when('/ExpressPDFCertificate/BusinessSearch', {
        templateUrl: 'ng-app/view/ExpressPDFCertificate/index.html',
        controller: 'expressPDFCertificateController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/ExpressPDFCertificate/Edit', {
        templateUrl: 'ng-app/view/ExpressPDFCertificate/ExpressPDFCertificate.html',
        controller: 'expressPDFCertificateController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/ExpressPDFCertificate/:id', {
        templateUrl: 'ng-app/view/ExpressPDFCertificate/ExpressPDFCertificate.html',
        controller: 'expressPDFCertificateController',
        resolve: { isAuthenticated: isAuthenticated }
    }).when('/ExpressPDFCertificate', {
        templateUrl: 'ng-app/view/ExpressPDFCertificate/ExpressPDFCertificate.html',
        controller: 'expressPDFCertificateController',
        resolve: { isAuthenticated: isAuthenticated }
    }).otherwise({
        redirectTo: '/'
    })

    //------------------------------------Formations Back Button Functionality---------------//
    .when('/Formations/businessFormationIndex', {
        templateUrl: 'ng-app/view/Formations/Index.html',
        controller: 'indexController',
        caseInsensitiveMatch: true
    });
});

// Example of how to set default values for all dialogs
wacorpApp.config(['ngDialogProvider', function (ngDialogProvider) {
    ngDialogProvider.setDefaults({
        //className: 'ngdialog-theme-default',
        plain: false,
        showClose: false,
        closeByDocument: false,
        closeByEscape: false,
        //appendTo: false,
        preCloseCallback: function () {
            console.log('default pre-close callback');
        }
    });
}]);

var isAuthenticated = function (membershipService, $rootScope, $location) {
    if (!membershipService.isUserLoggedIn()) {
        $rootScope.previousState = $location.path();
        $location.path('/');
    }
};
var isPageFound = function (membershipService, $rootScope, $location) {
    if (!membershipService.isUserLoggedIn()) {
        $rootScope.previousState = $location.path();
        $location.path('/');
    }
    else
        $location.path('/Dashboard');
};
angular.isNullorEmpty = function (val) {
    return angular.isUndefined(val) || val === null || val === '' || val === 0;
};
wacorpApp.run(function ($rootScope, $location, $cookieStore, $http, $routeParams, $window, $timeout, $route) {
    $rootScope.repository = angular.fromJson($window.sessionStorage.getItem('repository') || {});
    if ($rootScope.repository.loggedUser) {
        $http.defaults.headers.common['Authorization'] = $rootScope.repository.loggedUser.authdata;
    }
});
var baseUrl = aPIURL.baseUrl;
//var baseUrl = "http://localhost:54783/api/";          // local
//var baseUrl = "https://wacorpapi.pcctg.net/api/";        // dev
//var baseUrl = "http://wacorptestapi.pcctg.net/api/";    // test
//var baseUrl = "https://wacorppcctestapi.pcctg.net/api/";    // pcc test


var sessionManager = {

    timeOut: 1200, // in seconds 
    alertBefore: 15  // in seconds
};

var filePath = { sharedPath: "\\172.16.2.8\\project\\WA CRD\\WACorporations\\" };
var isUSPSServiceValid = 1;
var usaCode = "261";
var washingtonCode = "271";
var washingtonIntegerCode = 271;
var isAllowForeign = false;
var isConsole = false;
var webservices = {
    Dashboard: {
        getDashboardCounts: baseUrl + 'Dashboard/GetDashboardCountsForOnline',
        getCorrespondenceList: baseUrl + 'Dashboard/GetCorrespondenceDetails',
        getReceiptList: baseUrl + 'Dashboard/GetReceiptDetails',
        getOnlineCorrespondenceDocumentsList: baseUrl + 'Dashboard/GetOnlineCorrespondenceDocumentsList',
        deleteCorrespondence: baseUrl + 'Dashboard/DeleteCorrespondence',
        deleteReceipts: baseUrl + 'Dashboard/DeleteReceipts',
    },

    UserAccount: {
        getLogin: baseUrl + 'UserAccount/GetLogin',
        saveUserRegistration: baseUrl + 'UserAccount/SaveUserRegistration',
        createAgentAccount: baseUrl + 'UserAccount/CreateAgentAccount',
        updateAccount: baseUrl + 'UserAccount/UpdateAccount',
        resetPassword: baseUrl + 'UserAccount/GetResetPassword',
        sendUserId: baseUrl + 'UserAccount/GetSendUserId',
        getUserDetails: baseUrl + 'UserAccount/GetUserDetails',
        getFilerDetails: baseUrl + 'UserAccount/GetFilerDetails',
        isUserExists: baseUrl + 'UserAccount/UserExists',
        isExistsPassword: baseUrl + 'UserAccount/ExistsPassword',
        changePassword: baseUrl + 'UserAccount/ChangePassword',
        addToCart: baseUrl + 'UserAccount/AddToCart',
        resendEmail: baseUrl + 'UserAccount/ResendEmailVerification',
        verifyEmail: baseUrl + 'UserAccount/EmailVerification',

        //***** Added for CRA addauthuser 10/21/2019, KK
        //addauthuser: baseUrl + 'UserAccount/AddAuthUser',

    },

    Common: {
        GetBusinessNames: baseUrl + 'Common/GetBusinessNames',
        GetBusinessDBANames: baseUrl + 'Common/CheckDBABusinessNames',
        GetReservedBusiness: baseUrl + 'Common/GetBusinessDetailsOnRegistrationID',
        PrincipalHeaderTitle: baseUrl + 'Common/PrincipalHeaderTitle',
        getValidAddress: baseUrl + 'Common/GetValidAddress',
        getCityStateZip: baseUrl + 'Common/GetCityStateOnZip',
        getCommercialAgetns: baseUrl + 'Common/GetOnlineCommercialAgents',
        fileUpload: baseUrl + 'Common/UploadFiles',
        deleteUploadedFile: baseUrl + 'Common/DeleteUploadedFile',
        deleteAllUploadedFiles: baseUrl + 'Common/DeleteAllUploadedFiles',
        GetUBINUmber: baseUrl + 'Common/GetUBINUmbers',
        ValidateBusinessStatus: baseUrl + 'Common/ValidateBusinessStatus',
        getNonCommercialRADetailsForEdit: baseUrl + 'Common/GetNonCommercialRADetails',
        isReinstatementARWithInDueDate: baseUrl + 'Common/isReinstatementARWithInDueDate',
        isRequalificationARWithInDueDate: baseUrl + 'Common/isRequalificationARWithInDueDate',
        getCommercialAgentAvailableOrNot: baseUrl + 'Common/GetCommercialAgentAvailableOrNot',
        GetEntityNameCleanUp: baseUrl + 'Common/EntityNameCleanUp',
    },

    Home: {
        getQuickLinks: baseUrl + 'Home1/GetStatistics/',
    },

    Lookup: {
        getLookUpData: baseUrl + 'Lookup/GetLookUpData',
        getBusinessFilingType: baseUrl + 'BusinessSearch/GetBusinessFilingTypeWithFormationType',
        getLookUpDataForAmendment: baseUrl + 'Amendment/GetLookUpDataForAmendment',
    },

    OnlineFilingsLookup: {
        OnBusinessFilingLookups: baseUrl + 'LookUp/OnBusinessFilingLookup',
        OnlineCFTStatus: baseUrl + 'LookUp/GetLookUpData',
        GetLookUpData: baseUrl + 'LookUp/GetLookUpData',
    },

    OnlineFiling: {
        FormationCriteria: baseUrl + 'BusinessFormation/GetBusinessCriteria',
        LLCFormationCriteria: baseUrl + 'BusinessFormation/GetLLCBusinessCriteria',
        LLPFormationCriteria: baseUrl + 'BusinessFormation/GetLLPBusinessCriteria',
        AddToCart: baseUrl + 'BusinessFormation/AddToCart',
        AddToCartLLC: baseUrl + 'BusinessFormation/AddToCartLLC',
        AddToCartLLP: baseUrl + 'BusinessFormation/AddToCartLLP',
        AnnualReportCriteria: baseUrl + 'OnlineAnnualReport/GetBusinessCriteria',
        AnnualAddToCart: baseUrl + 'OnlineAnnualReport/AddToCart',
        validateAnnualReport: baseUrl + 'OnlineAnnualReport/ValidateAnnualReport',
        validateInitialReport: baseUrl + 'OnlineInitialReport/ValidateInitialReport',
        AmendedAnnualReportCriteria: baseUrl + 'OnlineAmendedAnnualReport/GetBusinessCriteria',
        AmendedAnnualAddToCart: baseUrl + 'OnlineAmendedAnnualReport/AddToCart',
        InitialReportCriteria: baseUrl + 'OnlineInitialReport/GetBusinessCriteria',
        InitialAddToCart: baseUrl + 'OnlineInitialReport/AddToCart',
        AmendedInitialReportCriteria: baseUrl + 'OnlineAmendedInitialReport/GetBusinessCriteria',
        AmendedInitialAddToCart: baseUrl + 'OnlineAmendedInitialReport/AddToCart',
        StatementofChangeCriteria: baseUrl + 'OnlineStatementofChange/GetBusinessDetails',
        StatementofChangeAddToCart: baseUrl + 'OnlineStatementofChange/AddToCart',
        GetReinstatementBusinessCriteria: baseUrl + 'OnlineReinstatement/GetBusinessCriteria',
        AddReinstatementToCart: baseUrl + 'OnlineReinstatement/AddToCart',
        ValidateAmendedAR: baseUrl + 'OnlineAmendedAnnualReport/IsValidateAmendedAR',
        StatementofWithdrawalCriteria: baseUrl + 'OnlineSOW/GetBusinessCriteria',
        SOWAddToCart: baseUrl + 'OnlineSOW/AddToCart',
        CertificateOfDissolutionCriteria: baseUrl + 'OnlineCertificateofDissolution/GetBusinessDetails',
        CertificateOfDissolutionAddToCart: baseUrl + 'OnlineCertificateOfDissolution/AddToCart',
        ArticlesOfDissolutionCriteria: baseUrl + 'OnlineArticlesofDissolution/GetBusinessDetails',
        ArticlesOfDissolutionAddToCart: baseUrl + 'OnlineArticlesOfDissolution/AddToCart',
        AmendmentOfForiegnRegistrationStatementCriteria: baseUrl + 'OnlineAmendment/GetBusinessCriteria',
        AmendmentOfDomesticCriteria: baseUrl + 'OnlineAmendment/GetDomesticBusinessCriteria',
        reloadwithNewBusinessType: baseUrl + 'OnlineAmendment/PostReloadwithNewBusinessType',
        AmendmentofForiegnRegStmtToCart: baseUrl + 'OnlineAmendment/AddToCart',
        AmendmentofDomestic: baseUrl + 'OnlineAmendment/AddToCartOfDemesticAmendment',
        VoluntaryTerminationCriteria: baseUrl + 'OnlineVoluntaryTermination/GetBusinessCriteria',
        VoluntaryTerminationAddToCart: baseUrl + 'OnlineVoluntaryTermination/AddToCart',
        CommercialStatementofChangeCriteria: baseUrl + 'CommercialStatementofChange/GetBusinessDetails',
        CommercialStatementofChangeAddToCart: baseUrl + 'CommercialStatementofChange/AddToCart',
        StatementofTerminationCriteria: baseUrl + 'OnlineStatementofTermination/GetBusinessDetails',
        StatementofTerminationAddToCart: baseUrl + 'OnlineStatementofTermination/AddToCart',
        CommercialStatementofTerminationCriteria: baseUrl + 'CommercialStatementofTermination/GetBusinessDetails',
        CommercialStatementofTerminationAddToCart: baseUrl + 'CommercialStatementofTermination/AddToCart',
        CommercialListingStatementCriteria: baseUrl + "CommercialListingStatement/GetAgentDetails",
        CommercialListingStatementAddToCart: baseUrl + 'CommercialListingStatement/AddToCart',
        GetRegistrationCRAFeeDetails: baseUrl + "CommercialListingStatement/GetRegistrationCRAFeeDetails",
        getCopyRequestBusinessCriteria: baseUrl + 'CopyRequest/GetBusinessCriteria',
        getExpressPDFBusinessCriteria: baseUrl + 'CopyRequest/GetBusinessCriteriaForExpressPDF',
        addCertificatesCart: baseUrl + 'CopyRequest/AddToCart',
        addToCartForExpressPDF: baseUrl + 'CopyRequest/AddToCartForExpressPDF',
        OneClickARAddToCart: baseUrl + 'OnlineAnnualReport/FileOneClickAnnualReport',
        ExpressARAddToCart: baseUrl + 'OnlineAnnualReport/FileExpressAnnualReport',

        //For SaveAsDraft Functionality
        StatementOfChangeSaveAsDraft: baseUrl + 'OnlineStatementofChange/SaveStatementOfChangeAsDraft',
        AmendmentSaveAsDraft: baseUrl + 'OnlineAmendment/SaveAmendmentAsDraft',
        AmendmentAnnualReportSaveAsDraft: baseUrl + 'OnlineAmendedAnnualReport/SaveAmendmentAnnualReportAsDraft',
        AnnualReportSaveAsDraft: baseUrl + 'OnlineAnnualReport/SaveAnnualReportAsDraft',
        InitialReportSaveAsDraft: baseUrl + 'OnlineInitialReport/SaveInitialReportAsDraft',
        ReinstatementSaveAsDraft: baseUrl + 'OnlineReinstatement/SaveReinstatementAsDraft',
        DomesticForamtionSaveAsDraft: baseUrl + 'BusinessFormation/SaveForamtionAsDraft',
        ForeignFormationSaveAsDraft: baseUrl + 'BusinessFormation/SaveForamtionAsDraft',
        LLCFormationSaveAsDraft: baseUrl + 'BusinessFormation/SaveLLCForamtionAsDraft',
        LLCForeignFormationSaveAsDraft: baseUrl + 'BusinessFormation/SaveLLCForamtionAsDraft',
        LLPFormationSaveAsDraft: baseUrl + 'BusinessFormation/SaveLLPForamtionAsDraft',
        LLPForeignFormationSaveAsDraft: baseUrl + 'BusinessFormation/SaveLLPForamtionAsDraft',
        ArticlesofDissolutionSaveAsDraft: baseUrl + 'OnlineArticlesOfDissolution/SaveArticlesofDissolutionAsDraft',
        CertificateofDissolutionSaveAsDraft: baseUrl + 'OnlineCertificateofDissolution/SaveCertificateOfDissolutionAsDraft',
        VoluntaryTerminationSaveAsDraft: baseUrl + 'OnlineVoluntaryTermination/SaveVoluntaryTerminationAsDraft',
        StatementOfWithDrawalSaveAsDraft: baseUrl + 'OnlineSOW/SaveStatementOfWithDrawalAsDraft',
        StatementofTerminationSaveAsDraft: baseUrl + 'OnlineStatementofTermination/SaveStatementofTerminationAsDraft',
        CopyRequestSaveAsDraft: baseUrl + 'CopyRequest/SaveCopyRequestAsDraft',
        CommercialStatementofChangeSaveAsDraft: baseUrl + 'CommercialStatementofChange/SaveCommercialStatementofChangeAsDraft',//Commercial Statement of change
        CommercialListingStatementSaveAsDraft: baseUrl + 'CommercialListingStatement/SaveCommercialListingStatementAsDraft',//Commercial Listing Statement
        CommercialStatementofTerminationSaveAsDraft: baseUrl + 'CommercialStatementofTermination/SaveCommercialStatementofTerminationAsDraft',//Commercial Statement of termination
        GetRequalificationBusinessCriteria: baseUrl + 'OnlineRequalification/GetBusinessCriteria',
        AddRequalificationToCart: baseUrl + 'OnlineRequalification/AddToCart',
        requalificationSaveAsDraft: baseUrl + 'OnlineRequalification/SaveRequalificationAsDraft',
        GetTransactionDocumentsListForAR: baseUrl + 'OnlineAnnualReport/GetTransactionDocumentsListForSuccessScreen',
    },

    BusinessSearch: {
        getAdvanceBusinessSearchList: baseUrl + 'BusinessSearch/GetAdvanceBusinessSearchList',
        getBusinessSearchList: baseUrl + 'BusinessSearch/GetBusinessSearchList',
        getbusinessInformation: baseUrl + 'BusinessSearch/BusinessInformation',
        getNameReservation_businessInformation: baseUrl + 'NameReservation/GetReservationDetails',
        getBusinessFilingList: baseUrl + 'BusinessSearch/GetBusinessFilingList',
        getBusinessNameHistoryList: baseUrl + 'BusinessSearch/GetBusinessNameHistoryList',
        getBusinessNames: baseUrl + 'BusinessSearch/GetBusinessSearchDetails',
        getTransactionDocumentsList: baseUrl + 'Common/GetTransactionDocumentsList',
        //getTrademarSearchDetails: baseUrl + 'BusinessSearch/GetPublicHomeTrademarkSearchList',  //TFS 1500 mkr spelling error
        getTrademarkSearchDetails: baseUrl + 'BusinessSearch/GetPublicHomeTrademarkSearchList',
        getTrademarkInfoDetails: baseUrl + 'BusinessSearch/GetTrademarkInformation',
        getTrademarkDocuments: baseUrl + 'BusinessSearch/GetTransactionDocumentsListForTrademark',
    },

    //TradeMarkSearch: { !!!***** Spelling corrected 10/21/2019, KK
    TradeMarkSearch: {
        getTrademarkSearchDetails: baseUrl + 'Trademark/GetPublicTrademarkSearchList',
        getTrademarkInfoDetails: baseUrl + 'Trademark/GetTrademarkInformationForOnline',
        getTrademarkDocuments: baseUrl + 'WorkOrder/GetTransactionDocumentsListForTrademark',
        getTrademarkAdvancedSearchDetails: baseUrl + 'BusinessSearch/GetTrademarkAdvancedSearchList',
    },

    ShoppingCart: {
        getCartItems: baseUrl + 'Common/GetOnlineCartList',
        cartItemDelete: baseUrl + 'Common/DeleteOnlineCartDetails',
        cartItemEdit: baseUrl + 'Common/DeleteOnlineCartDetails',
        processPayment: baseUrl + 'Payment/CreditFromOnline',
        updatePayments: baseUrl + 'Common/UpdateOnlineCartDetails',
        checkPaymentAmount: baseUrl + 'Common/CheckAmounUpdateForEntity',
        checkAmountReactiveUpdateForEntity: baseUrl + 'Common/CheckAmountReactiveUpdateForEntity',
        validateBusinessName: baseUrl + 'Common/ValidateBusinessName',
        validateBusiness: baseUrl + 'Common/ValidateBusinessStatus',
        shoppingCartPayment: baseUrl + 'Common/ShoppingCartPayments',
    },

    CopyRequest: {
        getAllCertifiedCopies: baseUrl + 'CopyRequest/GetAllCertifiedCopies',
        calculateAnnualFeeOnline: baseUrl + 'CopyRequest/CalculateAnnualFeeOnline',
        getCFPublicSearchDetails: baseUrl + 'CFTEntitySearch/GetCFTEntityNameSearchListForRc',
        getCFTTransactionDocumentsList: baseUrl + 'CFTOfficeCorrection/GetCFTTransactionDocumentsListForRc',
        getTransactionDocumentsList: baseUrl + 'Common/GetTransactionDocumentsListForRCOnline',
        getExpressPDFAllCertifiedCopies: baseUrl + 'CopyRequest/GetExpressPDFAllCertifiedCopies',
    },

    Subscription: {
        getBusinessesForSubscription: baseUrl + 'BusinessSearch/GetSubscriptionBusinessetails',
        getCFTForSubscription: baseUrl + 'CFTPublicSearch/GetCFTSubscriptionDetails',
        //CORP
        SubscribeBusiness: baseUrl + 'Dashboard/BusinessSubscription',
        UnSubscribeBusiness: baseUrl + 'Dashboard/BusinessUnSubscription',
        //CFT
        SubscribeCFTBusiness: baseUrl + 'Dashboard/CFTSubscription',
        UnSubscribeCFTBusiness: baseUrl + 'Dashboard/CFTUnSubscription',
    },

    MailBox: {
        getMailBox: baseUrl + 'OnlineApprovals/GetFilerMailBox',
        getMailDetails: baseUrl + 'OnlineApprovals/GetMailDetails',
        deleteMailItem: baseUrl + 'OnlineApprovals/DeleteMailItem',
    },

    DraftFilings: {
        getDraftData: baseUrl + 'OnlineApprovals/GetDraftFilings',
        getDraftDataById: baseUrl + 'OnlineApprovals/GetDraftFilingById',
        deleteDraftFilingById: baseUrl + 'OnlineApprovals/DeleteDraftFiling',
    },

    CFT: {
        getOrganizationSolicitServiceTypes: baseUrl + 'LookUp/GetCFTLookUps',
        getFederalTaxTypes: baseUrl + 'LookUp/GetCFTLookUps',
        getColorCrossList: baseUrl + 'LookUp/GetCFTLookUps',
        getTrustPurposeList: baseUrl + 'LookUp/GetCFTLookUps',
        getIRSDocumentList: baseUrl + 'LookUp/GetCFTLookUps',
        FundraiserCriteria: baseUrl + 'OnlineFundraiser/GetFundraiserCriteria',
        FundraiserAddToCart: baseUrl + 'OnlineFundraiser/FundraiserAddToCart',
        CharitiesCriteria: baseUrl + 'OnlineCharities/GetCharitiesCriteria',
        CharitiesAddToCart: baseUrl + 'OnlineCharities/CharitiesAddToCart',
        CharitiesSaveandClose: baseUrl + 'OnlineCharities/CharitiesSaveandClose',
        FundraiserSaveandClose: baseUrl + 'OnlineFundraiser/FundraiserSaveandClose',
        TrustSaveandClose: baseUrl + 'OnlineTrustees/TrustSaveandClose',
        CharityClosureCriteria: baseUrl + 'OnlineCharities/GetCharityClosureCriteria',
        FundraiserClosureCriteria: baseUrl + 'OnlineFundraiser/GetFundriaserClosureCriteria',
        FundraiserSearchForCharities: baseUrl + 'Charities/SearchFundraisersList',
        FundraiserSearchForCharitiesOFC: baseUrl + 'Charities/GetCharityFundraisersForFSC',
        getCounties: baseUrl + 'LookUp/GetCFTLookUps',
        getCFTStatus: baseUrl + 'LookUp/GetLookUpData',

        //***** Added re: CCFS TFS #3034 - KK, 9/10/2019 *****
        //getFedTaxExStatus: baseUrl + 'LookUp/GetCFTLookUps', 

        getBusinessDetailsByUBINumber: baseUrl + 'CFTCommon/GetEntityDetailsByUBINumber',
        getBusinessNames: baseUrl + 'CFTCommon/GetBusinessNamesAvailability',
        //getBusinessNames: baseUrl + 'CFTCommon/GetBusinessNames', -- New LookUp Algorithm -- 03/31/2018
        getCharityDetailsByCharityId: baseUrl + 'Fundraiser/GetCharityDetailsByCharityId',
        getCharitiesRenewalDetails: baseUrl + 'OnlineCharities/GetCharitiesRenewalCriteria',
        getOptionalRegistrationUpdateDetails: baseUrl + 'OnlineCharities/GetOptionalRegistrationUpdateCriteria',
        getCharitiesAmendmentDetails: baseUrl + 'OnlineCharities/GetCharitiesAmendmentCriteria',
        getCharitySearchDetails: baseUrl + 'Charities/GetCharitySearchDetails',
        getCharityCommonBasicSearchDetails: baseUrl + 'CFTEntitySearch/GetCFTEntityNameSearchList',
        getCharityAmendRenewalDetails: baseUrl + 'CFTPublicSearch/GetCFTPublicEntityNameSearchList',
        getFundraiserSearchDetails: baseUrl + 'Fundraiser/GetFundraiserSearchDetails',
        FundraiserRenewalCriteria: baseUrl + 'OnlineFundraiser/GetFundraiserRenewalCriteria',
        FundraiserAmendmentCriteria: baseUrl + 'OnlineFundraiser/GetFundraiserAmendmentCriteria',
        getTrusteeSearchDetails: baseUrl + 'Trustees/GetTrusteesSearchDetails',
        getTrustRenewalCriteria: baseUrl + 'OnlineTrustees/GetTrustRenewalCriteria',
        TrusteeAddToCart: baseUrl + 'OnlineTrustees/TrusteeAddToCart',
        getOrganizationPurposeTypes: baseUrl + 'LookUp/GetCFTLookUps',
        getFundraiserSubContractorDetails: baseUrl + 'Fundraiser/GetFundraiserSubContractorDetails',
        IsFEINNumberExists: baseUrl + 'CFTCommon/IsFEINNumberExists',
        IsUBINumberExists: baseUrl + 'CFTCommon/IsUBINumberExists',
        getCFPublicSearchDetails: baseUrl + 'CFTPublicSearch/GetCFPublicSearchList',
        getCFPublicSearchListExport: baseUrl + 'CFTPublicSearch/GetCFPublicSearchListExport',
        getOrganizationNameByUBI: baseUrl + 'CFTCommon/GetOrganizationNamebyUBI',
        getOrganizationNameByFEIN: baseUrl + "CFTCommon/GetOrganizationNamebyFEIN",
        getCFSearchDetails: baseUrl + 'CFTPublicSearch/GetCFTEntityNameSearchList',
        getCFTCharityFundraiserSearchDetails: baseUrl + 'CFTPublicSearch/GetCFTPublicEntityNameSearchList',
        getCFTPublicSearchResults: baseUrl + 'CFTPublicSearch/GetCFTPublicSearchResults',
        getFEINDataDetails: baseUrl + 'CFTPublicSearch/GetCFTEntityNameSearchList',
        getFEINDataDetailsFundraiserSearchDetails: baseUrl + 'CFTPublicSearch/GetCFTPublicEntityNameSearchList',
        getCharityAmendRenewalDetails: baseUrl + 'CFTPublicSearch/GetCharityAmendRenewalResults',
        getCharityOptionalSearchResult: baseUrl + 'CFTPublicSearch/GetCharitesOptionalPublicSearchList',
        fileUpload: baseUrl + 'CFTCommon/UploadFiles',
        fundraiserfileUpload: baseUrl + 'CFTCommon/UploadFundraiserFiles',
        deleteUploadedFile: baseUrl + 'CFTCommon/DeleteUploadedFile',
        deleteAllUploadedFiles: baseUrl + 'CFTCommon/DeleteAllUploadedFiles',
        getcharityOrganization: baseUrl + 'CFTCommon/GetOnlieCharitiSummaryById',
        getCftSearchOrganizationFillings: baseUrl + 'CFTCommon/GetFilingHistory',
        getCftSearchOrganizationNameHistoryList: baseUrl + 'CFTCommon/GetCFTEntityNameSearchList',
        getCFTTransactionDocumentsList: baseUrl + 'CFTCommon/GetCFTTransactionDocumentsList',
        TrustClosureCriteria: baseUrl + 'OnlineTrustees/GetTrusteeClosureCriteria',
        getCharitiesSubmitFundraisingCriteria: baseUrl + 'OnlineCharities/GetCharitiesSubmitFundraisingCriteria',
        getCharitiesSubmitFundraisingAmendmentCriteria: baseUrl + 'OnlineCharities/GetCharitiesSubmitFundraisingAmendmentCriteria',
        getFundraisingServiceContractEntity: baseUrl + 'CFTOfficeCorrection/GetFundraiserServiceContractEntity',
        getNonContractServiceEntity: baseUrl + 'CFTOfficeCorrection/GetNonContractServiceEntity',

        //Re-Registration
        getCharitiesReRegistrationDetails: baseUrl + 'OnlineCharities/GetCharitiesReRegistrationCriteria',
        getFundraiserReRegistrationDetails: baseUrl + 'OnlineFundraiser/GetFundraiserReRegistrationCriteria',
        getTrustReRegistrationDetails: baseUrl + 'OnlineTrustees/GetTrustReRegistrationCriteria',
        getCFTFinHistoryValidation: baseUrl + 'CFTCommon/validateFinancialHistoryForReRegistration',
        downloadActivityReport: baseUrl + 'Common/DownloadActivityReport',
    },

    WorkOrder: {
        GetTransactionDocuments: baseUrl + 'WorkOrder/GetTransactionDocumentsListForSuccessScreen',
        GetTransactionDocumentsAfterPaymentSuccess: baseUrl + 'WorkOrder/GetTransactionDocumentsListForPaymentSuccessScreen', // 2984
    },

    CommercialAgents:{
        getCommercialAgentsList: baseUrl + 'CommercialRegisteredAgents/GetCommercialAgentsList',
    }
};

var messages = {
    ENTER_USERNAME_PWD: "Please enter the username and password",
};

//Constant for Status.
var ResultStatus =
{
    SUCCESS: "success",// SUCCESSS = "SUCCESSS"
    FAILED: "failed",// FAIL = "FAIL"
    INDIVIDUAL: "I",//INDIVIDUAL
    OFFICEORPOSITION: "O",//OFFICEORPOSTITON
    ENTITY: "E",//ENTITY
    ACTIVE: "Active",//ACTIVE
    DELINQUENT: "Delinquent",//DELINQUENT
    DATEOFFILING: "DateOfFiling",//DATEOFFILING
    NONE: "",//NONE,
    TRUE: "true",//TRUE
    FALSE: "false",//FALSE
    COMPLETED: "completed",//COMPLETED
    DATEOFADOPTIONFILING: "DateOfAdoptionFiling",//DateOfAdoptionFiling
    AdministrativelyDissolved: "Administratively Dissolved",//Administratively Dissolved
    Terminated: "Terminated",//Terminated
};

//Constant for Actions.
var Actions =
{
    /// Add = "A"
    Add: "A",

    /// Edit = "E"
    Edit: "E",

    /// Delete = "D"
    Delete: "D"
};

//Constant for activityType.
var activityType = {

    // EDIT = "Edit"
    EDIT: "Edit",

    /// NEWAMENDED = "NewAmended"
    NEWAMENDED: "NewAmended",

    /// NEW = "New"
    NEW: "New",
};


//Constant for Action Mode
var actionModes = {

    // EDIT = "Edit"
    EDIT: "Edit",

    /// NEWAMENDED = "NewAmended"
    RETURN: "Return",

    /// NEW = "New"
    DELETE: "Delete"
};

var filerType = {
    // EDIT = "Edit"
    Filer: "FI",
    NonCommercialRegisteredAgent: "RA",
    CommercialRegisteredAgent: "CA",
    CommercialListingStatement: "COMMERCIAL LISTING STATEMENT",
};

var constant = {
    NEGATIVE: -1,//MINUS 1
    ZERO: 0,//Zero
    ONE: 1,//One
    TWO: 2,//Two
    THREE: 3,//THREE
    FOUR: 4,//FOUR
    FIVE: 5,//FIVE
    TEN: 10,//Ten
    TWENTYFIVE: 25,//Twenty Five
    ExpdateAmount: 50
};

var codes = {
    USA: "USA",//USA
    WA: "WA",//WA
    WASHINGTON: "WASHINGTON",//Washington
    DOMESTIC: "D",//DOMESTIC
    FOREGIN: "F",//FOREGIN
    CAN:"CAN"//CAN
};

var filingTypeIDs = {
    STATEMENTOFWITHDRAWAL: 147,//STATEMENTOFWITHDRAWAL
    VOLUNTARYTERMINATION: 157,//VOLUNTARYTERMINATION
    COMMERCIALLISTINGSTATEMENT: 191,
};

var businessTypeIDs = {
    WAPROFITCORPORATION: 86,//WAPROFITCORPORATION
    WANONPROFITCORPORATION: 73,//WANONPROFITCORPORATION
    WANONPROFITPROFESSIONALSERVICECORPORATION: 74,//WANONPROFITPROFESSIONALSERVICECORPORATION
    WAMISCELLANEOUSANDMUTUALCORPORATION: 72,//WAMISCELLANEOUSANDMUTUALCORPORATION
    WACORPSOLE: 59,//WACORPSOLE
    WALIMITEDLIABILITYPARTNERSHIP: 68, // WA LIMITED LIABILITY PARTNERSHIP
    WALIMITEDLIABILITYLIMITEDPARTNERSHIP: 67,
    WALIMITEDPARTNERSHIP: 69,
    WAPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP: 75,
    WAPROFESSIONALLIMITEDLIABILITYPARTNERSHIP: 76,
    WAPROFESSIONALLIMITEDPARTNERSHIP: 77,
    WAPROFESSIONALSERVICECORPORATION: 85,

    FOREIGNBANKLIMITEDLIABILITYCOMPANY: 15,
    FOREIGNLIMITEDLIABILITYCOMPANY: 20,
    FOREIGNLIMITEDLIABILITYLIMITEDPARTNERSHIP: 21,
    FOREIGNLIMITEDLIABILITYPARTNERSHIP: 22,
    FOREIGNLIMITEDPARTNERSHIP: 23,
    FOREIGNPROFESSIONALLIMITEDLIABILITYCOMPANY: 33,
    FOREIGNPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP: 34,
    FOREIGNPROFESSIONALLIMITEDLIABILITYPARTNERSHIP: 35,
    FOREIGNBANKCORPORATION: 14,
    FOREIGNPROFESSIONALLIMITEDPARTNERSHIP: 36,
    FOREIGNINSURANCECOMPANY: 19,
    FOREIGNCREDITUNION: 17,
    FOREIGNSAVINGSANDLOANASSOCIATION: 40,
    FOREIGNPROFITCORPORATION:38,

    COMMERCIALREGISTEREDAGENT: 11,
    WAPUBLICBENEFITCORPORATION:87,
};

var docuementTypeIds = {
    CORRESPONDENCES: 5,//OnlineFiling
    RECEIPTS: 3,//PaymentReceipt

    AcceptanceLetter: 1,
    RejectionLetter: 2,
    //PaymentReceipt: 3,
    OnlineReportwithFiledStamp: 4,
    //OnlineFiling: 5,
    InhouseFiling: 6,
    BusinessDocument: 7,
    UploadCertificateofFormation: 8,
    UploadCertificateofLimitedPartnership: 9,
    UploadCertificateofLimitedLiabilityPartnership: 10,
    UploadCertificateofExistence: 11,
    UploadArticlesofIncorporation: 12,
    UploadDeclarationofTrust: 13,
    PURPOSEANDPOWERS: 99,
    FOREIGNREGISTRATIONSTATEMENT: 85,
    FUNDRAISINGSERVICECONTRACT: 86,
    GRANTMAKER: 87,
    AMENDEDANDRESTATEDARTICLESOFINCORPORATION: 42,
    AMENDEDANDRESTATEDCERTIFICATEOFFORMATION: 41,
    AMENDEDANDRESTATEDCERTIFICATEOFLIMITEDLIABILITYCOMPANY: 43,
    AMENDEDANDRESTATEDCERTIFICATEOFLIMITEDLIABILITYLIMITEDPARTNERSHIP: 44,
    AMENDEDANDRESTATEDCERTIFICATEOFLIMITEDLIABILITYPARTNERSHIP: 45,
    AMENDEDANDRESTATEDCERTIFICATEOFLIMITEDPARTNERSHIP: 46,
    AMENDMENTOFFOREIGNREGISTRATIONSTATEMENT: 47,
    RevenueClearanceCertificate: 19,
    PreparedAmendment:120,
    PreferredStock: 121,
    CertificateofLimitedLiabilityLimitedPartnership: 55,
    FederalTaxDocuments: 15,
    LegalInfoAddressDocuments: 14,
    ListOfAddressesDocuments: 17,
    TaxReturnListDocuments: 18,
    OverrideDocuments: 20,
    UploadBondwaiverSosBondDocument: 21,
    UploadBondwaiverSuretyBondDocuments: 22,
    FinancialInformationIrsDocumentUpload: 23,
    DeclarationOfTrust: 13,
    UploadSuretyBondsDocuments: 16,
    SuretyBond: 113,
};

var businessTypeGroupIDs = {
    DOMESTIC: 3,//DOMESTIC
    FOREGIN: 5//FOREGIN
};

var pricipals = {
    EXECUTOR: "Executor"//EXECUTOR
};

var searchTypes = {
    COMMERCIALSTATEMENTOFCHANGE: "CommercialStatementofChange",//COMMERCIALSTATEMENTOFCHANGE,
    BUSINESSNO: "businessno",//BUSINESSNO
    BUSINESSNAME: 'businessname',//BUSINESSNAME
    BUSINESSTYPE: "BusinessType",//BUSINESSTYPE
    BUSINESSSTATUS: "BusinessStatus",//BusinessStatus
    UBINUMBER: "UBINumber",//UBINUMBER
    BUSINESSBYAGENTID: 'BusinessByAgentID',//BUSINESSBYAGENTID
    BUSINESSSEARCH: 'BusinessSearch',//BUSINESSSEARCH
    SUBSCRIPTIONSEARCH: 'SubscriptionSearch',//SUBSCRIPTIONSEARCH
    CHARITY: "charity",//CHARITY
    FUNDRAISER: "fundraiser",//FUNDRAISER
    TRUSTS: "trusts",//TRUSTS
    FEINNO: "feinnumber",
    FEINNumber: "FEINNo",
    RegistrationNumber: 'RegistrationNumber',
    UBINumber: 'UBINumber',
    ENTITYNAME: "entityname",
    BUSINESSTYPEONLINEDASHBOARD: "BusinessTypeOnlineDashboard",//BusinessType Online Dashboard
    CFTONLINEDASHBOARD: "CFTOnlineDashboard",//CFT Online Dashboard
    REGISTRATIONNUMBER: "RegistrationNumber",
    ORGANIZATIONNAME: "OrganizationName",
    Contains: 'Contains',
};

var sectionNames = {
    AUTHORIZEDPERSON: "Authorized Person",//AUTHORIZEDPERSON
    JURISDICTION: "Jurisdiction",//AUTHORIZEDPERSON
    INITIALBOARDDIRECTOR: "I am an Initial Board of Director",
    INITIALDIRECTOR: "I am an Initial Director"//INITIALDIRECTOR For BussinessType ID 73 and 74
};

var settings = {
    KEY: "Key",//Key
    VALUE: "Value",//VALUE
    SCROLLHEIGHT: '300px',//SCROLLHEIGHT
};

var principalStatus = {
    INSERT: "N",//INSERT
    UPDATE: "M",//UPDATE
    DELETE: "D"//DELETE
};

var uploadedFiles = {
    FILETYPES: [' jpg', ' jpeg', ' pdf'], //DevOps 1813 Org Code ['jpg', 'jpeg', 'pdf'], //Legacy supported items: ['jpg', 'jpeg', 'png', 'tif', 'doc', 'docx', 'pdf']
    FILESIZE: 10 * 1024 * 1024,
    FILESIZEMB: 1 * 1024 * 1024,
    ARTICLESOFINCORPORATIONMODAL: "ArticlesofIncorporation",//ARTICLESOFINCORPORATION
    CERTIFICATEOFFORMATIONMODAL: "CertificateofFormation",//CERTIFICATEOFFORMATIONMODAL
    CLEARANCECERTIFICATEMODAL: "ClearanceCertificate",//CLEARANCECERTIFICATEMODAL
    CERTIFICATEOFEXISTENCEMODAL: "CertificateOfExistence",//CERTIFICATEOFEXISTENCEMODAL
    CertificateOfFormation: "Certificate of Formation",
    PURPOSEANDPOWERS: "Purpose and Powers",
    CertificateofLimitedPartnership:"Certificate of Limited Partnership",
    CertificateofExistence: "Certificate of Existence",
    CertificateofLimitedLiabilityPartnership: "Certificate of Limited Liability Partnership",
    CertificateofLimitedLiabilityLimitedPartnership: "Certificate of Limited Liability Limited Partnership",
    ArticlesofIncorporation: "Articles of Incorporation",
    RevenueClearanceCertificate: "Revenue Clearance Certificate",
    PreferredStock: "Preferred Stock",
    PreparedAmendment: "Prepared Amendment",
    FederalTaxDocuments: "FEDERAL TAX DOCUMENTS",
    LegalInfoAddressDocuments: "LEGAL INFO ADDRESS DOCUMENTS",
    ListOfAddressesDocuments: "LIST OF ADDRESSES DOCUMENTS",
    TaxReturnListDocuments: "TAX RETURN LIST DOCUMENTS",
    OverrideDocuments: "OVERRIDE DOCUMENTS",
    UploadBondwaiverSosBondDocument: "UPLOAD BONDWAIVER SOS BOND DOCUMENT",
    UploadBondwaiverSuretyBondDocuments: "UPLOAD BONDWAIVER SURETY BOND DOCUMENTS",
    FinancialInformationIrsDocumentUpload: "FINANCIAL INFORMATION IRS DOCUMENT UPLOAD",
    DeclarationOfTrust: "DECLARATION OF TRUST",
    UploadSuretyBondsDocuments: "UPLOAD SURETY BONDS DOCUMENTS",
    SuretyBond: "SURETY BOND",
    Requalification: "REQUALIFICATION",
};

var WAFeeProvider = {
    AGENTREGISTRATIONFEE: 10,
    CERTIFIEDCOPIESFEE: 10,
};

var BusinessStatus = {
    Active: 1,
    Delinquent: 2,
    AdministrativelyDissolved: 3,
    AdministrativelyTerminated: 4,
    Merged: 5,
    Consolidated: 6,
    InActive: 7,
    Expired: 8,
    Converted: 9,
    ActivePending: 10,
    Dissolved: 11,
    VoluntarilyTerminated: 12,
};

var PartialViews = {
    FilingFeeListView: "/ng-app/view/partial/_FilingFeeList.html"
}

var FilingTypeHavingExpDate =
    [
        'ADM DISSOLUTION/TERMINIATION', 'AMENDED', 'AMENDED CERTIFICATE OF LIMITED LIABILITY  PARTNERSHIP', 'AMENDED CERTIFICATE OF FORMATION',
        'AMENDED CERTIFICATE OF LIMITED LIABILITY LIMITED PARTNERSHIP', 'AMENDED CERTIFICATE OF LIMITED PARTNERSHIP',
        'AMENDED CERTIFICATE OF PROF LIMITED LIABILITY LIMITED PARTNERSHIP', 'AMENDED CERTIFICATE OF PROF LIMITED PARTNERSHIP',
        'AMENDED CERTIFICATE OF PROF LIMITED LIABILITY PARTNERSHIP', 'AMENDMENT', 'AMENDMENT OF FOREIGN REGISTRATION STATEMENT',
        'ANNUAL REPORT', 'ARTICLES OF AMENDMENT', 'ARTICLES OF INCORPORATION', 'ARTICLES OF INCORPORATION WITH INITIAL REPORT',
        'CERTIFICATE OF AMENDMENT', 'CERTIFICATE OF FORMATION', 'CERTIFICATE OF FORMATION WITH INITIAL REPORT',
        'CERTIFICATE OF LIMITED LIABILITY LIMITED PARTNERSHIP WITH INITIAL REPORT', 'CERTIFICATE OF LIMITED PARTNERSHIP WITH INITIAL REPORT',
        'CONVERSION', 'CORRESPONDENCE', 'FOREIGN REGISTRATION STATEMENT', 'FORMATION RECORD', 'INITIAL REPORT', 'MERGERS', 'REGISTRATION OF NAME',
        'REINSTATEMENT', 'RESERVATION OF NAME', 'RESIGNATION OF AGENT', 'REVOCATION OF VOLUNTARY DISSOLUTION', 'STATEMENT OF CHANGE', 'STATEMENT OF CORRECTION',
        'TRANSFER OF REGISTRATION', 'VOL DISSOLUTION/WITHDRAWAL', 'WITHDRAWAL OF FILED RECORD'
    ];

var TrustOrganizationalType = {
    ArticlesofIncorporation: "Articles of Incorporation and Bylaws",
    TrustAgreement: "Trust Agreement",
    LastWilandTestament: "Last Will and Testament",
    ProbateOrder: "Probate Order",
};

var userRegistrationHeaders = {
    RA: "Agent Registration",
    CA: "Commercial Agent Registration",
    FI: "User Registration",
};

// governor Address Required Entity Types
var governerAddressRequiredEntityTypeID = {
    WaProfitCorporation: 86,
    WaProfessionalServiceCorporation: 85,
    WaSocialPurposeCorporation: 90,
    WaPublicUtilityCorporation: 88,
    WaEmployeeCooperative: 61,
    WaMassachusettsTrust: 71,
    WaAssociationUnderFishMarketingAct: 54,
    ForeignProfitCorporation: 38,
    ForeignProfessionalServiceCorporation: 37,
    ForeignPublicUtilityCorporation: 39,
    ForeignMassachusettsTrust: 24,
};

//Filing Service Types Of CFT
var CFTServiceTypes = {
    charityRegistration: "CHARITABLE ORGANIZATION REGISTRATION",
    charityAmendments: "CHARITABLE ORGANIZATION AMENDMENT",
    charityRenewals: "CHARITABLE ORGANIZATION RENEWAL",
    fundraiserRegistration: "COMMERCIAL FUNDRAISER REGISTRATION",
    fundraiserAmendments: "COMMERCIAL FUNDRAISER AMENDMENT",
    fundraiserRenewals: "COMMERCIAL FUNDRAISER RENEWAL",
    trustRegistration: "CHARITABLE TRUST REGISTRATION",
    trustAmendments: "CHARITABLE TRUST AMENDMENT",
    trustRenewals: "CHARITABLE TRUST RENEWAL",
}

//CFTStatus
var CFTStatus = [{
    closed: "Closed",
    involuntaryClosure: "Involuntarily Closed",
    active: "Active",
    delinquent: "Delinquent",
}];

//Type of Withdrawal
var TypeOfWithdrawal =
{
    WithdrawalfromWAState: "Withdrawal from WA State",
    DissolutioninHomeJurisdiction: "Dissolution in Home Jurisdiction",
    ConversioninHomeJurisdiction: "Conversion in Home Jurisdiction"
};

var businessCatType = {
    CORP: "CORP",
    CFT: "CFT"
}
var messages = {
    serverError: "'We've encountered an unexpected issue.  We apologize for the inconvenience. Please try again later.  You may also email us at corps@sos.wa.gov. \n Error code: {0}.",
    deleteConfirmation: 'Are you sure you want to delete?',
    noDataFound: 'No Value Found.',
    selectedBusiness: 'Selected business is {0}.',
    deleteSuccessful: 'Deleted successfully.',
    EntityNameRequired: 'Please enter Business Name.',
    UBINumberRequired: 'Please enter UBI Number.',
    FEINNumberRequired: 'Please enter FEIN Number.',
    EntityTyperequired: 'Please select a Business Type.',
    BondWaiversBondExpirationDate: 'Please specify Bond Expiration Date.',
    selectedEntity: 'Selected business is {0}.',
    InvalidFilingMsg: 'Please review the information entered and complete the required fields to proceed.',
    MailBoxDeleteMsg: 'Selected correspondence deleted successfully.',
    SaveDraftSuccess: 'Filing saved successfully.',
    statementofWithdrawalAllowed: 'Statement of Withdrawal is allowed for active, delinquent and Terminated businesses only.',
    voluntaryTerminationAllowed: 'Voluntary Termination is allowed for active, delinquent and administrative dissolution businesses only.',
    certificateOfDissolutionAllowed: 'Certificate of Dissolution is allowed for active, delinquent and administrative dissolution businesses only.',
    articlesOfDissolutionAllowed: 'Articles of Dissolution is allowed for active, delinquent and administrative dissolution businesses only.',
    Index: 'Amendment is allowed for active businesses only.',
    HasActiveFilings: "Alert!  Alert!  There are filing(s) for this business/organization currently awaiting review by the Washington Secretary of State. If you chose to proceed with this filing, any previously submitted filings may supersede this online filing.  Would you like to proceed?",
    UBILookup: "Please click on Lookup to check the name availability for the given UBI number.",
    UbiUse: "Please click the Use button to use the business name.",
    DomesticUBI: "The given UBI number is already associated with a business. Please provide a valid UBI number.",
    ForeignUBI: "The given UBI number is associated with a domestic business. Please provide foreign UBI number.",
    NatureOfBusinessOtherDescription: "Please enter other nature of business.",
    ubiNotAssociated: 'The Organization Name provided does not match the name of the organization on file for the UBI provided.',
    statementofResgination: "Please select Statement of Resignation.",//Please upload your Statment of Resignation or document of similar import.
    attestationofRA: 'Please select Attestation.',
    futureEffectiveDate: 'Do you need a delayed effective date for this filing?',
    reregistrationNotAllowed: 'This organization has passed its Re-Registration period and is not eligible to file a Re-Registration.',
    reregistrationMissingRenewalDate: 'Please contact our office at <a href="mailto:charities@sos.wa.gov">charities@sos.wa.gov</a> and provide your EIN and that a Re-Registration is needed. Due to a technical issue, the organization may need to submit the Re-Registration by mail.',//TFS 2622
    reregistrationToRenewal: 'You must do a Renewal Filing as the business is Active.',
    representedEntityExists: 'Represented entity already exists, please select another business.',
    NoticesandFiledDocumentsDeleteMsg: 'Selected notice and filed documents deleted successfully.',
    ReceiptsDeleteMsg: 'Selected receipt deleted successfully.',
    ValidDissolutionFilings: 'Dissolution/Withdrawal is not allowed for this business type.',
    Attention: 'Please enter Attention.',
    AmendmentNotAllowStatus: 'The Amendment is allowed for active, delinquent and Administratively Dissolved businesses only.',

    Account: {
        firstName: 'Please enter First Name.',
        lastName: 'Please enter Last Name.',
        email: 'Please enter Email Address.',
        validEmail: 'Please enter a valid Email Address.',
        phone: 'Please enter Phone Number.',
        validPhone: 'Please enter a valid Phone Number.',
        businessNumber: 'Please enter Business Phone Number.',
        validBusinessNumber: 'Please enter a valid Business Number.',
        cellNumber: 'Please enter Cell Phone Number.',
        validCellNumber: 'Please enter a valid Cell Phone Number.',
        accountUpdate: 'Your account has been updated successfully.',
        accountUpdateFailed: 'Account update failed. Please try again later.',
        userSentEmail: "Hi {0}, Your User ID has been sent to the email address provided.",
        agentAlreadyCreated: "This Registered Agent account has already been activated. Please try to login."
    },
    ChangePassword: {
        currentPassword: 'Please enter current password.',
        newPassword: 'Please enter new password.',
        passwordLength: 'Password should contain a minimum of 10 characters.',
        passwordUserIDMatch: 'User ID cannot be part of Password.',
        passwordValidate: 'Password must contain three of the following: an upper case letter, a lower case letter, a number, and a special character.',
        passwordMatch: 'Password does not match.',
        passwordReset: 'Your password has been reset successfully.',
        oldPassword: 'Please enter valid current password.',
        passwordUpdate: 'Password updated successfully.',
        passwordUpdateFailed: 'Password update failed. Please try again later.'
    },
    ForgotPassword: {
        userID: 'Please enter User ID.',
        email: 'Please enter Email Address.',
        validEmail: 'Please enter a valid Email Address'
    },
    ForgotUser: {
        validEmail: 'Please enter a valid Email Address.',
        registeredEmail: 'Please enter your registered Email Address.',
        invalidEmail: 'Invalid registered Email, please try again'
    },
    Login: {
        userID: 'Please enter User ID.',
        password: 'Please enter Password.'
    },
    Register: {
        firstName: 'Please enter First Name.',
        lastName: 'Please enter Last Name.',
        email: 'Please enter Email Address.',
        confirmEmail: 'Please enter Confirm Email Address.',
        validEmail: 'Please enter a valid Email Address.',
        emailMatch: 'Email addresses do not match.',
        phone: 'Please enter Phone Number.',
        validPhone: 'Please enter a valid Phone Number.',
        businessNumber: 'Please enter Business Number.',
        validBusinessNumber: 'Please enter a valid Business Number.',
        cellNumber: 'Please enter Cell Phone Number.',
        validCellNumber: 'Please enter valid Cell Phone Number.',
        userID: 'Please enter User ID.',
        userIDStrength: 'User ID must be at least 6  characters.',
        userIDValidate: 'User ID may contain letters, numbers, and some special characters.',
        password: 'Please enter Password.',
        confirmPassword:'Please enter Confirm Password.',
        passwordLength: 'Password must contain a minimum of 10 characters.',
        passwordUserIDMatch: 'User ID cannot be part of Password.',
        passwordValidate: 'Password must contain 3 of the 4 following character types: Upper case letters, Lower case letters, Numbers and/or Special Characters.',
        passwordMatch: 'Passwords must match.',
        goHomeConfirmation: 'Are you sure you want to go back to Home page?',
        userExists: 'User ID already exists. Please try another ID.',
        agentTypeRequired: 'Please select Agent Type.',
        userTypeRequired: 'Please select User Type.',
        validExt: 'Please enter valid Extension.',
        craAvailableOrNot: 'CRA name is not available. Please enter a different name.',
        craLookup: 'Please click on lookup to check name availability.',
        craAttestation: 'Please select CRA Attestation.',
        craNameAvailable: 'CRA name is available.',
        craRepresentedAttestation: 'Please select CRA Represented Entities Attestation.',
    },
    AuthorizedPerson: {
        personType: 'Please select Authorized Person Type.',
        executedPenalities: 'Please certify this document by checking the box above.',
        entityNameRequiredMsg: 'Please enter Entity Name.',
        firstNameRequiredMsg: 'Please enter First Name.',
        lastNameRequiredMsg: 'Please enter Last Name.',
        titleRequiredMsg: 'Please enter Title.',
    },
    Address: {
        address1: 'Please enter Address 1.',
        validZip: 'Please enter a valid Zip code.',
        zip: 'Please enter Zip code.',
        validZipExtension: 'There is no City and State associated for given zip code.',
        city: 'Please enter City.',
        country: 'Please select Country.',
        postalCode: 'Please enter Postal Code.',
        state: 'Please select State.',
        otherState: 'Please enter Other.',
        invalidAddressData: 'Given address has some invalid data.\nDo you want to correct?',
        invalidCityState: 'City will be changed on Zip Code.\nDo you want to continue?',
        notWashingtonAddress: 'Registered Agent addresses must be in WA.',
        county: 'Please select County.',
        poBox: 'The street address cannot be a PO Box or PMB (personal/private mailbox).',
        poBox1: 'The street address cannot be a PO Box or PMB (personal/private mailbox).',
        poBoxAddress1: 'Address 1 cannot be a PO Box or PMB (personal/private mailbox).',
        poBoxAddress2: 'Address 2 cannot be a PO Box or PMB (personal/private mailbox).',
        Attention: 'Please enter Attention.',
        Notvalidaddress: 'Given address is invalid.',
        validCorrespondenceEmail: 'Please enter a valid Email Address.',
        emailCorrespondenceMatch: 'Email Addresses do not match.',
        returnedMailMsg: 'This address has been marked as Returned Mail and needs to be updated.',
    },
    DBAName: {
        businessName: 'Please enter DBA Name.',
        businessNameAvailable: 'Please click the "Look Up" button to check the availability of the name entered.'
    },
    EntityName: {
        reservedBusinessID: 'No data found, please enter a valid Name Reservation Number.',
        indicator: 'Please select an Indicator.',
        businessName: 'Please enter Business Name.',
        reservedBusinessName: 'Please click the "Get Name" button to confirm the availability.',
        noReservedName: 'No data found, please enter a valid Name Reservation Number.',
        businessNameAvaibilityCheck: 'Please click the "Look Up" button to check the availability of the name entered.',
        businessNameNotAvailable: 'The name is not available. Please enter a new name and click the "Look Up" button to check for availability.',
        CFTbusinessName: 'Please enter Organization Name.',
        CFTreservedBusinessName: 'Please get reserved Organization Name.',
        CFTbusinessNameAvaibilityCheck: 'Please check the Organization Name availability',
        //OSOS ID - 3165
        UseDBAName: 'The business name is not available for use. Please use a DBA Name and check the look up for DBA name availability.',
        //UseDBAName: 'The name is not available for use, check the look up on the DBA Name for availability',
        UseDBANameForIndicator: 'The business name requested does not contain the necessary designation. Do you want to use the DBA name?',
        UseDBANameForMustNotIndicator: 'The business name containing invalid indicator. Do you want to use the DBA name?',
        nameAlreadyUsed: 'The name you have selected is not available for use. To file a reinstatement, first please file a Business Amendment changing your name.',
        ResetAmendBusinessType: "If you are changing your business type, you must change your business name/designation. If you choose not to change your business name/designation, the business type change will not be recorded."
    },

    EffectiveDate: {
        specifyDate: 'Please specify a date.'
    },
    InitialBoardDirector: {
        firstName: 'Please enter First Name.',
        lastName: 'Please enter Last Name.',
    },
    PrincipalOffice: {
        validEmail: 'Please enter a valid Email Address.',
        emailMatch: 'Email Addresses do not match.',
        email: "Please enter Email Address.",
        confirmEmail: "Please enter Confirm Email Address.",
    },
    Principals: {
        name: 'Please enter Business Name.',
        firstName: 'Please enter First Name.',
        lastName: 'Please enter Last Name.',
        title: 'Please enter Title.',
        atleastOneExecutor: 'Please add at least one Executor.',
        isEntityExecutor:'*An entity cannot be its own executor.',
        atleastOneInitialBoardofDirector: 'Please add at least one Initial Director.',
        isEntityInitialBoard:'*An entity cannot be its own initial board of director.',
        atleastOneInCorporator: 'Please add at least one Incorporator',
        isEntityIncorporator:'*An entity cannot be its own incorporator.',
        atleastOneGoverningPerson: 'Please add at least one Governor.',
        atleastOneGeneralPartner: 'Please add at least one General Partner.',
        isEntityGeneralPartner:'*An entity cannot be its own general partner.',
        atleastOneTrustee: 'Please add at least one Trustee.',
        atleastOneBusiness: 'Please add at least one Represented Entity.',
    },
    PrincipalsNonProfitMembers: {
        HasMembers: 'Please select if Nonprofit has Members',
        name: 'Please enter Business Name.',
        firstName: 'Please enter First Name.',
        lastName: 'Please enter Last Name.',
        title: 'Please enter Title.',
        atleastOneMember: 'Please add at least one Member.',
        isEntityMember: '*An entity cannot be its own member.',
    },
    PurposeAndPowers: {
        businessPurpose: 'Please enter the Business Purpose or Purposes of this Corporation.',
        termOrganization: 'Please select one or more boxes above.',
        socialPurpose: 'Please check the box above.',
        uploadFile: 'Please upload a file.',
    },
    RegisteredAgent: {
        Email: "Please enter Email Address.",
        confirmEmail: "Please enter Confirm Email Address.",
        validEmail: 'Please enter a valid Email Address.',
        emailMatch: 'Email Addresses do not match.',
        atleastOneAgent: ' Please add a Registered Agent.',
        selectAgent: 'Please select Agent.',
        emptyRecordsMsg: 'No Value Found.',
        name: 'Please enter Entity name.',
        firstName: 'Please enter First Name.',
        lastName: 'Please enter Last Name.',
        officeOrPosition: 'Please enter Office or Position.',
        agentStreetAddress: 'Please provide valid agent Address.',
        //agentStreetAddress: 'Please provide agent Street Address.'
    },
    UploadFiles: {
        uploadFile: 'Please upload a file.',
        addressSolicitation: 'Please submit a list of other addresses used for solicitation',
        uploadFailed: 'File upload failed.  Please try again.',
        fileNotFound: 'File cannot be found in the system.',
        fileDelete: 'File deleted.',
        fileDeleteFailed: 'File cannot be deleted at this time. Please try again.',
        fileNotSupport: 'The file format you are trying to upload is not supported. Upload a file with the following allowed extensions: {0}.',
        fileSizeNotSupport: 'File size cannot exceed {0} MB.',
        filesDeleteConfirm: 'Uploaded files will be deleted.\nDo you want to continue?',
        irsConfirm: 'Existing IRS Determination Letter will be deleted Do you want to continue?',
        fileSizeNote: "Attachment size limit is {0} MB.",
        fileTypeNote: "(supports only{0}.)",  //DevOps 1813 Org Code "(supports only {0}.)",
        articleUploadText: "Articles of Incorporation (If you have additional provisions in the articles, you may upload them here.)",
        certificateofFormationUploadText: "Certificate of Formation (If you have additional provisions in the certificate, you may upload them here.)",
        clearanceCertificateUploadText: "Revenue Clearance Certificate",
        certificateOfExistenceUploadText: "Certificate of Existence (If you have additional provisions in the articles, you may upload them here.)",
        uploadFilesSectionConfirmation: "Do you have {0} to upload?",
        uplodDocumentType: "Please Select Upload Document Type",
        deleteallRecords: 'Are you sure you would like to delete the records?',
        serviceContract: 'Please submit a document of contract',
        contractBetweenCharityAndFundraiser: 'Please submit a document of contract between charities and fundraisers'
    },
    VoluntaryTermination: {
        dissolutionApprovedDate: 'Please enter Dissolution Approved Date.',
        dissolutionDate: 'Please enter Dissolution Date'
    },
    ShoppingCart: {
        firstName: 'Please enter First Name.',     //Payee Name
        lastName: 'Please enter Last Name.', //Cardholder Name
        email: 'Please enter Email.',
        validEmail: 'Please enter a valid Email Address.',
        phone: 'Please enter Phone Number.',
        validPhone: 'Please enter a valid Phone Number.',
        cardType: 'Please select Card Type.',
        cardNumber: 'Please enter Card Number.',
        CVVNumber: 'Please enter CVV Number.',
        validCVVNumber: 'Please enter a valid CVV Number.',
        expirationMonth: 'Please select Expiration Month.',
        expirationYear: 'Please enter Expiration Year.',
        validExpirationYear: 'Please enter valid Expiration Year.',
        streetAddress: 'Please enter Address.',
        city: 'Please enter City.',
        state: 'Please select State.',
        zip: 'Please enter Zip.',
        validZip: 'Please enter a Valid Zip Code.',
        validZipExtension: 'Please enter valid zip code extension.',
        otherState: 'Please enter Other.',
        postalCode: 'Please enter Postal Code.',
        country: 'Please select Country.',
        shippingName: 'Please enter Shipping Name.',
        invalidItemsCheckout: 'Your cart contains invalid item(s), please clear it before proceeding to checkout.',
        shoppingCartValidate: 'This filing item needs to be updated as the Business Name is no longer available. Please click on the edit icon next to this filing in your shopping cart to conduct a new Business Name availability check.',
        Payment: 'Payment is unsuccessful.',
        PaymentAmountMisMatch: 'Filing Amount and paying amount is not matched.',
        CartItemIsDeleted: "The selected cart item(s) <b>  {0} </b> is deleted by one of the users.",
        AlreadyCartItemIsProcessed: "The selected cart item(s) <b>  {0} </b> is being processed.",
        AnnualReportAlreadyFiled: "This business <b> ( {0} ) </b> is {0} </br>",
        DeleteCartItemAlreadyProcessed: 'This cart item is already being processed.',
        DeleteCartItemAlreadyDone: 'This cart item is already deleted by one of the users.',
        DeleteCartItemUnCommitedTrnsIdProcessed: 'This item is being processed and cannot be deleted. It will be removed from your cart shortly.'
    },
    BusinessFormation: {
        UBINumber: 'Please enter valid UBI number.',
        attestationOfSocialPurpose: 'Please select Attestation of Social Purpose.',
        authorizedShares: 'Please enter Number of Authorized Shares.',
        classOfShares: 'Please select at least one class of shares.',
        purposeOfCorporation: 'Please enter Purpose of Corporation.',
        anyOtherProvisions: 'Please enter Any Other Provisions.',
        otherProvisions: 'Please enter Other Provisions.',
        durationYears: 'Please enter Duration in years.',
        expirationDate: 'Please enter Expiration Date.',
        attestationOfStatedProfession: 'Please check the box above.',
        natureOfBusiness: 'Please select Nature of Business.',
        PLLCAttestation: 'Please check the box above.',
        generalPartnerSignatureConfirmation: 'Must select Yes for General Partners Signature Confirmation.',
        nameinHomeJurisdiction: 'Please enter Business Name in home jurisdiction.',
        jurisdiction: 'Please select Jurisdiction.',
        dateofFormationinHomeJurisdiction: 'Please enter a date of formation in home jurisdiction.',
        noReserverBusiness: 'No Value Found.',
        preferredStock: 'Please upload Preferred Stock document(s).',
        ImplementationPlan: 'Please enter Implementation plan for change.',
        NumberOfShares: 'Number of shares must be greater than or equal to 1.',
        distributionOfAssets: 'Please enter Distribution of Assets.',
        //incorporatorSignatureConfirmation: 'Please select Incorporators Signature Confirmation.',
        certificateOfExistenceUpload: 'Please upload your Certificate of Existence or document of similar import.',
        businessEngages: 'Please enter Brief Statement of Business in Which the Partnership Engages.',
        attestationOfStated: 'Please select Attestation of stated profession.',
        rcwElection: 'Please check the box above.',
        // TFS#2671; added
        incorporatorSignatureAttestation: 'Must attest to Incorporator Signature(s)',
    },
    Reinstatement: {
        purposeOfCorporation: 'Please enter Purpose of Corporation.',
        attestationOfSocialPurpose: 'Please select Attestation of Social Purpose.',
        numberOfPartners: 'Please enter number of partners.',
        partnersCount: 'Number of partners must be two or more.',
        businessDescription: 'Please enter Description of Business.',
        businessDescriptionIncluded: 'Please select Description of Business included.',
        generalPartnerSignatureConfirmation: 'Please select General Partners Signature Confirmation should be Yes.',
        natureOfBusiness: 'Please select Nature of Business.',
        administrativeDissolvedMsg: 'Reinstatement is only available within 5 years of an administrative dissolution.',
        InvalidFilingTypeMsg: 'An annual report is not available for the selected business.',
        reinstatementDissolutionEndDateMsg: 'Reinstatement is only available within 5 years of an administrative dissolution.',// As per FRD 011
        ReinstatementARalert: 'Do you want to pay to reinstate the current annual report year?',
        isAdministrativeDissolved: 'An entity which is not administratively dissolved is not eligible to file for a Reinstatement.',
    },
    InitialReport: {
        purposeOfCorporation: 'Please enter Purpose of Corporation.',
        attestationOfSocialPurpose: 'Please select Attestation of Social Purpose.',
        numberOfPartners: 'Please enter Number of Partners.',
        partnersCount: 'Number of partners must be two or more.',
        businessDescription: 'Please enter Description of Business.',
        businessDescriptionIncluded: 'Please select Description of business included.',
        generalPartnerSignatureConfirmation: 'Please select General Partners Signature Confirmation should be Yes.',
        natureOfBusiness: 'Please select Nature of Business.',
        cannotFileinitialReport: 'Initial Report is no longer available for this business. If you have changes, please file an Amended Annual Report.',
        ActiveAndDelinquentStatus: 'Initial report is allowed for active and delinquent businesses only.',
        InvalidFilingTypeMsg: 'The system is unable to process the initial report for the selected business type.',
    },
    CertificateOfDissolution: {
        dissolutionDate: 'Please enter Dissolution Date.',
        dissolutionType: 'Please check Dissolution Type.',
        dissolutionAttestation: 'Please check Dissolution Attestations.',
        withdrawalRequirments: 'Please check above Requirement.',
        entitySurrenders: 'Please check above entity surrenders.',
        nameOfConvertingEntity: 'Please enter Name of converting entity.',
        convertedEntityType: 'Please select converted entity type.',
    },
    ArticlesOfDissolution: {
        dissolutionDate: 'Please enter Dissolution Date.',
        dissolutionType: 'Please check Dissolution Type.',
        dissolutionAttestation: 'Please check Dissolution Attestations.',
        clearanceUpload: 'Please select Do you have Revenue Clearance Certificate to upload? Yes.',
        AdoptionStatement: 'Please select Articles of Dissolution Adoption Statement',
        AODAdoptedByMembersOnlyNonProfit: 'Please select whether members have right to vote or approved by directors.',
        AODAdoptedByNotMembersOnlyNonProfit: 'Please The dissolution was authorized by the requisite number of directors.',
        AODAdoptedByOnlyNonProfit: 'Articles of Dissolution were Adopted By.',
    },
    AnnualReport: {
        purposeOfCorporation: 'Please enter Purpose of Corporation.',
        socialPurposeAttestation: 'Please select Attestation of Social Purpose.',
        numberOfPartners: 'Please enter Number of partners.',
        partnersCount: 'Number of partners must be two or more.',
        businessDescription: 'Please enter Description of Business.',
        businessDescriptionIncluded: 'Please select Description of business included.',
        generalPartnerSignatureConfirmation: 'Please select General Partners Signature Confirmation should be Yes.',
        natureOfBusiness: 'Please select Nature of Business.',
        UnableFilingMsg: 'The system is unable to process the annual report for the selected business type.',
        ActiveAndDelinquentStatus: 'Annual report is allowed for active and delinquent businesses only.',
        InvalidFilingTypeMsg: 'The system is unable to process the annual report for the selected business type.',
        OneClickBeforeReplace: 'Would you like to apply for reinstatement?',
        OneClickAfterReplace: 'Please reactivate your business. If you have any questions, please contact the Washington State Office of the Secretary of State.',
        feinNumber: 'Please enter a 9-digit EIN.',
        feinNumberlength: 'Please enter a 9-digit EIN.',
        CharitableNonProfitReqMsg: 'Please Answer Charitable NonProfit Corporation question.',
        CanBePublicBenefitNonProfitMsg: 'Please Answer Public Benefit Nonprofit Corporation question 1.',
        ElectToBePublicBenefitNonProfitMsg: 'Please Answer Public Benefit Nonprofit Corporation question 2.',
        disabledFiling: 'IMPORTANT: This filing type is not available through our online filing system. For a fillable .pdf version, visit our website https://www.sos.wa.gov/corps/forms.aspx or same day service is available at our office. We apologize for any inconvenience.',
    },
    AmendedAnnualReport: {
        purposeOfCorporation: 'Please enter Purpose of Corporation.',
        socialPurposeAttestation: 'Please select Attestation of Social Purpose.',
        numberOfPartners: 'Please enter Number of partners.',
        partnersCount: 'Number of partners must be two or more.',
        businessDescription: 'Please enter Description of Business.',
        businessDescriptionIncluded: 'Please select Description of business included.',
        generalPartnerSignatureConfirmation: 'Please select General Partners Signature Confirmation should be Yes.',
        natureOfBusiness: 'Please select Nature of Business.',
        ActiveAndDelinquentStatus: 'The Amended Annual Report is allowed for Active and Delinquent businesses only.',
        InvalidFilingTypeMsg: 'The system is unable to process the initial report for the selected business type.',
    },
    BusinessInfo: {
    	enterDate: 'Please enter Date.',
		testError: 'Please select atleast one option',
        nameinHomeJurisdiction: 'Please enter Name in Home jurisdiction.',
        jurisdiction: 'Please select Jurisdiction.',
        jurisdictionCountry: 'Please select Country.',
        jurisdictionState: 'Please select State.',
        dateofFormationinHomeJurisdiction: 'Please enter Date of Entity in its home jurisdiction.',
        durationYears: 'Please enter Duration years.',
        expirationDate: 'Please enter Expiration date.',
        natureOfBusiness: 'Please select Nature of Business.',
        uploadCertificateOfExistenceNote: 'Note: Certificate of Existence from the home jurisdiction should not be older than 60 days from the date of filing.',
        certificateOfExistanceMsg: 'Business have to upload a  Certificate of Existence; not more than 60 days old; from the home jurisdiction if business name, business type or jurisdiction is changed'
    },
    BusinessSearch: {
        entityNameRequiredMsg: 'Please enter Business Name.',
        ubiNumberRequiredMsg: 'Please enter UBI Number.',
        emptyRecordsMsg: 'No Value Found.',
    },
    TrademarkSearch: {
        trademarktext: 'Please enter Trademark Text.',
        registrationNumber: 'Please enter Registration Number.',
        trademarkOwner: 'Please enter Trademark Owner.',
        tradeUBINumber: 'Please enter UBI Number.'
    },
    AmendmentOfForiegnRegistrationStmt: {
        entityTypeNpte: 'Change Business type only if the business wants to amend its business type, otherwise you should leave the business type the same and amend the applicable fields below.',
        ActiveAndDelinquentStatus: 'The Amendment of Foreign Registration statement is allowed for active and delinquent businesses only.',
        ActiveStatus: 'Amendment of Foreign Registration statement is allowed for active businesses only.',
        InvalidFilingTypeMsg: 'The system is unable to process the initial report for the selected business type.',
    },
    GoverningPersons: {
        governingPerson: 'Please add Governor.',
    },
    CopyRequest: {
        emptyCartMsg: 'Please add Certificates to the cart.',
        certificateOfFactMsg: 'Please enter Certificate of Fact.',
        ApostilleCopyRequest: 'The number of Apostilles selected cannot be more than the number of selected Certified documents/Certificates.',
    },
    Subscription: {
        //CORP
        subscriptionSuccess: 'Selected businesses subscribed successfully.',
        subscriptionFailed: 'Selected businesses cannot be subscribed.',
        unSubscriptionSuccess: 'Selected businesses unsubscribed successfully.',
        unSubscriptionFailed: 'Selected businesses cannot be unsubscribed.',
        //CFT
        CFTSubscriptionSuccess: 'Selected organizations subscribed successfully.',
        CFTSubscriptionFailed: 'Selected organizations cannot be subscribed.',
        CFTUnSubscriptionSuccess: 'Selected organizations unsubscribed successfully.',
        CFTUnSubscriptionFailed: 'Selected organizations cannot be unsubscribed.',
    },
    ShoppingCartAlertMessage: {
        AlertMessage: 'Please select 1 or all items that you wish to pay for at this time, by checking the box next to the item you wish to check out.',
        ReinstatementARalert: 'Do you want to pay to reinstate the current annual report year?',
        AtLeastOneItem: 'Please select at least one item.',
    },
    SignatureAttestaion: {
        isAttestationInformationProvidedMsg: 'Please select Attestation.',
        firstNameRequiredMsg: 'Please enter First Name.',
        lastNameRequiredMsg: 'Please enter Last Name.',
        phoneNoRequiredMsg: 'Please enter Phone Number.',
        validPhone: 'Please enter a valid Phone Number.',
        attestdateRequiredMsg: 'Please select Attestation Date.',
    },
    CharitableOrganization: {
        charityRegistration: 'Please enter Charity Registration Number.',
        nameOfCharitableOrganization: 'Please enter Name of Charitable Organization.',
        phoneNuber: 'Please enter Phone Number.',
        validPhone: 'Please enter a valid Phone Number.',
        contractBeginningDate: 'Please enter Contract Beginning Date.',
        contractEndingDate: 'Please enter Contract Ending Date.',
        contractCancelledDate: 'Please enter Contract Cancelled Date.',
        serviceBeginningDate: 'Please enter Service Beginning Date.',
        serviceEndingDate: 'Please enter Service Ending Date.',
        atleastOneCharitableOrganization: 'Please add at least one Charitable Organization.',
        contractBeginGreaterThanEndDate: 'Contract Ending Date should be greater than Contract Beginning Date.',
        serviceBeginGreaterThanEndDate: 'Service Ending Date should be greater than Service Beginning Date.',
        officerHighPayFirstName: 'Please enter officers high pay first name',
        officerHighPayLastName: 'Please enter officers high pay last name',
        EffectiveDate: 'Please enter Date of Closure',
        qualifier: 'You do not qualify for optional registration. Please go for charities registration',
        qualifier1: 'You do not qualify for optional registration.You are redirected to charitable organization registration',
        qualifierAmendment: 'You do not qualify for optional amendement.You are redirected to charitable organization amendement',
        qualifierRenewal: 'You do not qualify for optional renewal.You are redirected to charitable organization renewal',
        qualifierReRegistration: 'You do not qualify for optional reregistration.You are redirected to charitable organization reregistration',
    },
    LegalInfo: {
        entityName: 'Please enter Entity Name.',
        firstName: 'Please provide the financial preparer First Name.',
        lastName: 'Please provide the financial preparer Last Name.',
        organizationName: 'Please provide the financial preparer business name',
        //organization
        repFirstName: 'Please provide the financial preparer representative first name',
        repLastName: 'Please provide the financial preparer representative last name',
        repTitle: 'Please provide the financial preparer business title',

    },
    LegalAction: {
        court: 'Please enter Court.',
        case: 'Please enter Case.',
        titleOfAction: 'Please enter Title Of Legal Action.',
        actionDate: 'Please enter Date of Legal Action.',
        addAtLeastOneLegal: 'Please enter Legal Information.',
        legalUpload: 'Please submit a list of Legal Actions'
    },
    FundraiserSearch: {
        atleastOneFundraiser: 'Please add at least one Fundraiser.',
        selectFundraiser: 'Please select Fundraiser.',
        emptyRecordsMsg: 'No Value Found.',
        noIsRequired: 'Please enter FEIN Number.',
        nameisRequired: 'Please enter Fundraiser Name',
        selectCharity: 'Please select Charity.'
    },
    EntityInfo: {
        email: "Please provide the Organization Email",
        confirmEmail: "Please enter Confirm Organization Email",
        validEmail: 'Please enter a valid Email Address.',
        emailMatch: 'Organization Email addresses do not match.',
        entityName: 'Please enter Organization Name.',
        phone: 'Please provide the Phone Number.',
        validPhone: 'Please enter a valid Organization Phone Number.',
        countryCode: 'Please enter Country Code.',
    },
    FinancialInfo: {
        beginningDate: "Please enter Accounting year beginning date",
        endingDate: "Please enter Accounting year ending date",
        firstAccountingYearEndDate: 'Please provide the First Accounting Year End Date.',
        fundraisingService: 'Please select at least one Fundraising Service.',
        otherStates: 'Please select Other.',
        otherServiceType: 'Please enter other service type.',
        state: 'Please select at least one State.',
        beginGreaterThanEndDate: 'Accounting year ending date should be greater than Accounting year beginning date.',
        grossAssets: 'Please enter Beginning Gross Assets.',
        revenueGD: 'Please enter Gross Dollar Value of All Contribution.',
        revenueOther: 'Please enter Gross Dollar Value of Revenue from All Other Sources.',
        expenseGDService: 'Please enter Gross Dollar Value of Expenditures for Program Services.',
        expenseGDAll: 'Please enter Gross Dollar Value of All Expenditures.',
        endGrossAssets: 'Please enter Ending Gross Assets',
        firstName: 'Please enter Officer First Name',
        lastname: 'Please enter Officer Last Name',
        officerHighPay: 'Please add at least one High Paid Officer',
        percentToCharity: 'Please enter Percent to Charity',
        contributionsRecieved: 'Please enter All Contributions Received',
        amountOfFunds: 'Please enter Amount of Funds Distributed to Charities',
        percentageValidate: 'All Contributions Received cannot be less than Amount of Funds Distributed to Charities.',
    },
    CFTOfficers: {
        firstName: 'Please enter First Name.',
        lastName: 'Please enter Last Name.',
        title: 'Please enter Title.',
        phoneNuber: 'Please enter Phone Number.',
        validPhone: 'Please enter a valid Phone Number.',
        atleastOneOfficers: 'Please provide at least one officer.',
        
    },
    GreenCrossCFD: {
        DevInfoFirstName: 'Please enter first name.',
        DevInfoLastName: 'Please enter last name.',
        DevInfoEmailAddress: 'Please enter email address.',
        DevInfoConfirmEmailAddress: 'Please enter confirm email address.',
        DevInfoPhoneNumber: 'Please enter phone number.',
        FinancialInfoFirstName: 'Please enter first name.',
        FinancialInfoLastName: 'Please enter last name.',
        FinancialInfoEmailAddress: 'Please enter email address.',
        FinancialInfoConfirmEmailAddress: 'Please enter confirm email address.',
        FinancialInfoPhoneNumber: 'Please enter phone number.',
        CharityVendorId: 'Please enter charity vendor id.',
        WebSite: 'Please enter website.',
        CategoryOfService: 'Please select atleast one category of service.',
        CategoryOfServiceValid: 'Please select maximum of 3 Category of Services only.',
        CountiesServed: 'Please select atleast one county served.',
        validFinanaceInfoEmail: 'Please enter valid email.',
        validDevelopmentInfoEmail: 'Please enter valid email.',
        devInfoEmailMatch: 'Email addresses do not match.',
        fininfoEmailMatch: 'Email addresses do not match.',
        emptyRecordsMsg: 'No Value Found.'
    },
    EnrollToCFDDetails: {
        firstNameReq: 'Please enter first name.',
        lastNameReq: 'Please enter last name.',
        emailAddressReq: 'Please enter email address.',
        comfirmEmailReq: 'Please enter confirm email address.',
        phoneNoReq: 'Please enter phone number.',
        charityVendorId: 'Please enter charity vendor id.',
        webSite: 'Please enter website.',
        categoryOfService: 'Please select atleast one category of service.',
        categoryOfServiceValid: 'Please select maximum of 3 Category of Services only.',
        countiesServed: 'Please select atleast one county served.',
        validEmail: 'Please enter valid email.',
        emailnotMatch: 'Email addresses do not match.',
        emptyRecordsMsg: 'No Value Found.'
    },
    CharityOrganization: {
        OtherDesc: 'Please enter Other Description.',
        OSJurisdictionId: 'Please enter Jurisdiction.',
        OSJurisdictionState: 'Please enter Jurisdiction State.',
        OSJurisdictionCountry: 'Please enter Jurisdiction Country.',
        akaList: 'Please add atleast one Solicit Contribution Name.',
        PurposeRequired: 'Please enter purpose/mission of the Organization.',
        TaxType: 'Please select Federal Status Type.',
        akaNameReq: 'Please enter Solicit Contribution Name',
        akaNameReq1: 'Please enter also known as names',
    },
    Trust: {
        SummarizeRequired: 'Please enter Summarize Charitable Purpose.',
        EstablishmentRequired: 'Please enter atleast one Establishment of Trust type',

        NameOfCorporation: 'Please enter Name of corporation',
        DateOfIncorporation: 'Please enter Date of incorporation',
        NameAndAddress: 'Please enter Name and address of the charitable organization',
        TrustAgreementAndInterVivos: 'Please enter Trust Agreement/Inter Vivos',
        DateOfEstablishment: 'Please enter Date of establishment',
        EstateOf: 'Please enter Estate of',
        CountyProbated: 'Please enter County probated',
        ProbatedNumber: 'Please enter Probated number',
        ProbatedDate: 'Please enter Probated date',
        uploadFile: 'Please upload a file',
    },
    CharitiesFinancial: {
        beginnningDateRequired: 'Please enter Accounting year beginning date.',
        endingDateRequired: 'Please enter Accounting year ending date.',
        endDateNotGreater: 'Accounting year end date should not be less than beginning date.',
        endDateNotGreaterThanTodayDate: 'Accounting Year End Date cannot be greater than current date',
        shortYearEndDateNotGreaterThanTodayDate: 'Short Fiscal Year End Date Cannot be greater than current date',
        endDateNotLessThanTodayDate: 'First Accounting Year End Date cannot be less than 11 months from current date.',
        //Accounting Year End Date should be greater than current date for Registration.

        //Start--Amendment Fiscal Rules
        amendedStartDateIsMoreThanYear: 'Current Accounting Year Start Date should not be more than one year from previous Accounting year end date.',
        amendedStartDateIsMoreThanPreviousStartDate: 'Accounting Year Beginning Date should be greater than previous Accounting Year End date.',
        isShortFiscalYear: 'Please enter the short Fiscal Year Information.',
        fiscalStartDateGreaterThanEndDate: 'Short Year Start Date should be greater than Previous Accounting Year End Date.',
        //End--Amendment Fiscal Rules

        firstyearEndDate: 'Please provide the First Accounting Year End Date.',
        grossAssets: 'Please enter Beginning Gross Assets.',
        revenueGD: 'Please enter Gross Dollar Value of All Contribution.',
        revenueOther: 'Please enter Gross Dollar Value of Revenue from All Other Sources.',
        expenseGDService: 'Please enter Gross Dollar Value of Expenditures for Program Services.',
        expenseGDAll: 'Please enter Gross Dollar Value of All Expenditures.',
        endGrossAssets: 'Please enter Ending Gross Assets.',
        expenseValidate: 'Total Gross Dollar of All Expenditures cannot be less than Gross Dollar Value of Expenditures for Program Services.',
    },
    Fein: {
        feinNumber: 'Please enter a 9-digit EIN.',
        feinNumberlength: 'Please enter a 9-digit EIN.',
        ubiNumberlength: 'Please Enter Valid UBI Number.',
        ubiNumber: 'Please enter UBI Number.',
        state: 'Please select State.',
        isFEINExistorNot: 'Entered FEIN Number is already exists.',
        isUBIExistorNot: 'Entered UBI Number is already exists.',
        TaxType: 'Please select Federal Status Type.',
        akaNameReq: 'Please enter Solicit Contribution Name.',
        PurposeRequired: 'Please provide the Purpose/Mission of the Organization.',
        FederaltaxUpload: 'Please submit IRS Determination Letter.',
    },
    FunraiserOrganizationStructure: {
        state: 'Please select State.',
        PurposeRequired: 'Please enter Purpose/Mission of the Organization.',
        TaxType: 'Please select Federal Tax Type.',
    },
    CFTSearch: {
        entityNameRequired: 'Please enter Organization Name.',
        feinNoRequired: 'Please enter FEIN Number.',
        RegNoRequired: 'Please enter Registration Number.',
        UBINoRequired: 'Please enter UBI Number.',
        emptyRecordsMsg: 'No Value Found.',
        registrationId: 'Please enter Registration ID.',
    },
    DirectoryInformation: {
        purpose: 'Please select at least one Purpose.',
        purposeLimit: 'Please select maximum of three purposes only.',
        initialOtherDesc: 'Please enter Other Description.',
        gsOtherDesc: 'Please enter Other Description.',
        gsLocalDesc: 'Please enter Local Description.',
        email: 'Please enter Email Address.',
        confirmEmail: 'Please enter Confirm Email Address.',
        validEmail: 'Please enter a valid Email Address.',
        emailMatch: 'Email addresses do not match.',
        firstName: 'Please enter First Name.',
        lastName: 'Please enter Last Name.',
        title: 'Please enter Title.',
        PhoneNumber: 'Please enter Phone Number.',
    },
    TrustBeneficiary: {
        name: 'Please enter Name.',
        atleastOneBeneficiary: 'Please add at least one Beneficiary.',
        charityName: 'Please enter Charity Name.',
        atleastOneBeneficary: 'Please provide at least one Trust Beneficiary.',
    },
    LegalInformation: {
        entityName: 'Please enter Entity Name.',
        firstName: 'Please enter First Name.',
        lastName: 'Please enter Last Name.',
        title: 'Please enter Title.',
        PhoneNumber: 'Please enter Phone Number.',
        validPhone: 'Please enter a valid Phone Number.',
        atleastOneLeagalInfo: 'Please add at least one Legal Information.',
    },

    TrustFinancialInformation: {
        OtherDesc: 'Please enter Other Description.',
        beginnningDateRequired: 'Please enter Accounting year beginning date.',
        endingDateRequired: 'Please enter Accounting year ending date.',
        endDateNotGreater: 'Accounting year end date should not be less than beginning date.',
        firstyearEndDate: 'Please enter First Accounting year end date.',
        beginningAssets: 'Please enter Beginning Gross Assets.',
        totalRevenue: 'Please enter Total Revenue.',
        contributions: 'Please enter Grants, Contributions and Program Services.',
        compensation: 'Please enter Compensation of Officers, Directors, Trustees, etc.',
        totalExpenses: 'Please enter Total Expenses.',
        endingAssets: 'Please enter Ending Assets.',
        BeginGreaterThanEndDate: 'Contract Ending Date should be greater than Contract Beginning Date.',
        uploadFile: 'Please upload a file',
        File: 'File not found.',
        irsDocument: 'Please select atleast one IRS Tax Document Type'
    },
    Qualifier: {
        qualifier1: 'Qualifier must be Church or Integrated Auxiliary',
        qualifier2: 'Qualifier must be a Political Organization',
        qualifier3: 'Qualifier must be Raising funds for an individual/Raising less than $50,000 a year',
        qualifier4: 'Please Select Are you raising less than $50,000 a year',
        isInfoAccurate: 'Please check All Information is true and accurate',
        qualifier: 'Please complete all Qualifier questions'
    },
    CFTPublicSearch: {
        alert: "Cannot file for the Organizations which are Closed and Involuntarily Closed",
    },
    //Failed:
    //    {
    //      Error:'failed',
    //    },
    businessForm:
        {
            Correct: 'Valid',
            Incorrect: 'In-Valid',
        },
    Session:
        {
            Timeout: 'Your session has expired.',
        },
    Confirm: {
        ConfirmMessage: 'Are you sure you would like to delete the record?',
    },
    Cartitems: {
        InhouseAppovalFiling: 'This filing item is ready for submission for review by WA OSOS.',
        OnlineProcessFiling: 'This filing item is ready to be processed online.',
        FeeItemsUpdated: 'Fees for this item were updated due to one of the following reasons:',
        AnnualReportDueDatePassed: 'The annual report due date for this business entity has passed.',
        InitialReportDueDatePassed: 'The initial report due date for this business entity has passed.',
    },
    Requalification: {
        purposeOfCorporation: 'Please enter Purpose of Corporation.',
        attestationOfSocialPurpose: 'Please select Attestation of Social Purpose.',
        numberOfPartners: 'Please enter number of partners.',
        partnersCount: 'Number of partners must be two or more.',
        businessDescription: 'Please enter Description of Business.',
        businessDescriptionIncluded: 'Please select Description of Business included.',
        generalPartnerSignatureConfirmation: 'Please select General Partners Signature Confirmation should be Yes.',
        natureOfBusiness: 'Please select Nature of Business.',
        administrativeDissolvedMsg: 'Requalification is only available within 5 years of termination.',
        InvalidFilingTypeMsg: 'An annual report is not available for the selected business.',
        reinstatementDissolutionEndDateMsg: 'Requalification is only available within 5 years of terminated.',
        ReinstatementARalert: 'Do you want to pay to requalify the current annual report year?',
        isTerminated: 'An entity which is not Terminated is not eligible to file for a Requalification.',
        certificateOfExistenceUpload: 'Please upload your Certificate of Existence or document of similar import.',
    },
    //TFS 2628
    CharitableNonProfitAndReporting: {
        CharitableNonProfitReqMsg: 'Please select if the Nonprofit Corporation is Charitable.',
        CharitableNonProfitExemptReqMsg: 'Please indicate if the Nonprofit Corporation meets the exemptions for reporting.',
        CharitableNonProfitReporting1ReqMsg: "Please select if the Nonprofit Corporation's purpose has had changes.",
        CharitableNonProftReporting2ReqMsg: 'Please select if the Nonprofit Corporation has done the above.',
    },
    //TFS 2628
    //TFS 2626
    GrossRevenueNonProfit: {
        GrossRevenueNonProfitReqMsg: 'Please certify if the Gross Revenue is less than $500K.',
    }
    //TFS 2626
};


var helptext = {
    Corporations: {
        LLLP:'The name must contain the words "Limited Liability Limited Partnership", "LLLP", or "L.L.L.P." The name is limited to a maximum of 255 characters. If you wish to use a name longer than 255 characters, your application must be filed in paper form instead of electronically.'
    },
    charities: {
        fundEntityName: 'Enter a name and click the Look Up button to check whether the name you have chosen is already used by another Commercial Fundraiser. After clicking on Look Up, a list of close matches will appear in the space below.',
        trustEntityName: 'Enter a name and click the Look Up button to check whether the name you have chosen is already used by another Charitable Trust. After clicking on Look Up, a list of close matches will appear in the space below.',
        legalInfo: 'Has the charitable organization or any individual in its registration been subject to any legal action in which a judgement or final order was entered, or action is currently pending? If so, a list of legal actions, including the court or other forum, case number, title of legal action and date of each action, must be enclosed.' + '"Legal Actions"' + 'include any administrative or judicial proceedings alleging that the entity has failed to comply with these rules, chapter 19.09 RCW, or state or Federal laws pertaining to taxation, revenue, charitable solicitation, or record-keeping, whether such action has been instituted by a public agency or a private person or entity.',
        commercialFundraiser: '',
    },
};
/*To storing value with key and store it
It is helful, when passing scope value from one controller to another.
We can store multiple value withe key and can be call simply with the key*/
//note: once the task done dispose the data 
wacorpApp.factory('ScopesData', function ($rootScope) {
    var mem = {};
    return {
        store: function (key, value) {
            mem[key] = value;
        },
        get: function (key) {
            var result = mem[key];
            if (result == undefined) {
                return null;
            }
            else {
                return mem[key];
            }
        },
        remove: function () {
            mem = {};
        },
        removeByKey: function (Key) {
            delete mem[Key];
            var k = mem;
        },
        getAll: function () {
           return mem
        }

    };

});



var AgentEntity = {
    AgentID: 0, EntityName: null, FirstName: null, LastName: null, IsNonCommercial: false,
    EmailAddress: null, ConfirmEmailAddress: null, AgentType: "I", AgentTypeID: 0,
    StreetAddress: {
        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
            FilerID: 0, UserID: 0, CreatedBy: 0,
            IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null
        },
        FullAddress: null, ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: "WA", OtherState: null,
        Country: "USA", Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
    },
    MailingAddress: {
        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
            FilerID: 0, UserID: 0,
            CreatedBy: 0, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null
        },
        FullAddress: null, ID: 0, StreetAddress1: null, StreetAddress2: null, City: null,
        State: "WA", OtherState: null, Country: "USA", Zip5: null, Zip4: null, PostalCode: null, County: "USA",
        CountyName: null
    },
    IsUserRegisteredAgent: false, PhoneNumber: null, IsRegisteredAgentConsent: true, Title: null, IsSameAsMailingAddress: false, CreatedBy: null, //TFS 1143 original -> IsRegisteredAgentConsent: false
    AgentCreatdDate: null, AgentCreatdIP: null, IsNewAgent: false
};

var PrincipalOfficeInWAEntity = {
    PrincipalID: 0, SequenceNo: '', FirstName: null, LastName: null, Title: null, Name: null,
    PhoneNumber: null, EmailAddress: null, TypeID: "I", PrincipalBaseType: null,
    PrincipalMailingAddress: {
        ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
        baseEntity: { FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null },
        FullAddress: null, ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null,
        Country: 'USA', Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
    },
    PrincipalStreetAddress: {
        ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
        baseEntity: { FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null },
        FullAddress: null, ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: "WA", OtherState: null, Country: "USA", Zip5: null,
        Zip4: null, PostalCode: null, County: null, CountyName: null
    }, IsSameAsMailingAddress: false, BusinessID: 0, Status: null, MemberOrManager: 0, IsPrincipalOfficeNotInWa: false, FilerID: 0,
    UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null
};

var InitialReportEntity = {
    IsLLLPElection: false,
    IsFilingComplete: false,
    NumberOfPartners: 0,
    DescriptionOfBusinessIncluded: false,
    GeneralPartnersSignatureConfirmation: false,
    IsAttestationOfStatedProfession: false,
    IsPLLCAttestation: false,
    IsDentalService: false,
    IsPurposeOfCorporation: false,
    IsAttestationOfSocialPurpose: false,
    IsStockOrNonStock: false,
    JurisdictionOfTrust: 0,
    JurisdictionOfTrustDesc: "",
    DateTrustCreated: "0001-01-01T00:00:00",
    CorporateShares: 0,
    IsCorporateSharesCommonStock: false,
    IsCorporateSharesPreferedStock: false,
    DescriptionOfBusiness: "",
    PurposeOfCorporation: "",
    ErrorMsgs: {},
    UBINumber: "",
    BusinessName: "",
    BusinessNameSearch: "",
    NewBusinessName: "",
    BusinessID: 0,
    DBABusinessName: "",
    NewDBABusinessName: "",
    BusinessType: "",
    AmendedBusinessType: "",
    BusinessTypeID: 0,
    OtherProvisions: "",
    DurationType: "",
    DurationYears: 0,
    IsPerpetual: false,
    DurationExpireDate: "0001-01-01T00:00:00",
    EffectiveDate: "0001-01-01T00:00:00",
    EffectiveDateType: "",
    AvailableStatus: "",
    IsUploadDocumentExist: false,
    FilingDate: "0001-01-01T00:00:00",
    Jurisdiction: 0,
    JurisdictionDesc: "",
    OldJurisdictionDesc: "",
    BusinessStatusID: 0,
    BusinessStatus: "",
    AgentName: "",
    IsOnline: false,
    CorrespondenceFileName: "",
    ReceiptFileName: "",
    FileLocationCorrespondence: "",
    FileLocationReceipt: "",
    DocumentID: 0,
    NameInHomeJurisdiction: "",
    NewNameInHomeJurisdiction: "",
    DateOfFormationInHomeJurisdiction: "0001-01-01T00:00:00",
    DateBeganDoingBusinessInWA: "0001-01-01T00:00:00",
    DateBeganDoingBusinessInWAType: "",
    FilingSucces: false,
    createdBy: 0,
    createdIP: "",
    createdDate: "0001-01-01T00:00:00",
    LastARFiledDate: null,
    PlaceofFormationId: null,
    NextARDueDate: "0001-01-01T00:00:00",
    ARDueDate: "0001-01-01T00:00:00",
    DateOfIncorporation: "0001-01-01T00:00:00",
    PurposeAndPowersID: 0,
    IsWalkinWorkOrder: false,
    IsInitialReportFiled: false,
    ShareValue: 0,
    IsArticalsExist: false,
    UploadFileInfoList: {},
    EntityTypesWithScreens: {},
    AllScreenParts: {},
    Agent: [],
    PrincipalOffice: [],
    PrincipalOfficeInWA: [],
    NatureOfBusiness: {},
    AuthorizedPerson: {},
    PrincipalsList: {},
    BusinessFiling: [],
    BusinessTransaction: [],
    PurposeAndPowers: []
};

// annual report
var annualReportEntity =
{
    BusinessMailingAddress: {},
    BusinessStreetAddress: {},
    Agent: {},
    NatureOfBusinessEntity: [],
    AuthorizedPerson: {
        AuthorizedPersonFirstName: null,
        AuthorizedPersonLastName: null,
        AuthorizedPersonTitle: null,
        AuthorizedPersonEntityName: null,
        IsAccepted: false,
        PersonType: "E",
        DocUnderPenalities: null,
        DocIsSigned: false,
        IsRAorTrusteeCoverSheetSigned: false
    },
    PrincipalOffice: {},
    PrincipalsList: [],
    UploadFileInfoList: [],
    BusinessFiling: {},
    BusinessTransaction: {},
    PurposeAndPowers: {},
    PrincipalOfficeInWA: {},
    PreferedStockUploadFiles: [],
    isARLateFiling: false,
    isStockTransfer: null,
    isFuturePurchaseAggrement: null,
    NumberOfPartners: 0,
    Purpose: null,
    IsFilingSuccess: false,
    isUploadCertificateofLLP: false,
    isUploadDeclarationOfTrust: false,
    isDistributionofAssetsProvided: false,
    isOfficersAddress: false,
    NumberOfShares: 0,
    JurisdictionOfTrust: 0,
    DateTrustCreated: "0001-01-01T00:00:00",
    JurisdictionOfTrustDesc: null,
    isPurposeofCorporationSC: false,
    IsDescriptionOfBusIncluded: false,
    isGeneralPartnerSignatureConfirmation: false,
    CorporateShares: 0,
    isCorporateSharesCommonStock: false,
    isCorporateSharesPreferedStock: false,
    isPllcAttestation: false,
    isProfessionalLLLPElection: false,
    isLLLPElection: false,
    isUploadCertificateofLP: false,
    isUploadCertOfFormation: false,
    isuploadArticalsOfIncorporation: false,
    isAttestationofSocialPurpose: false,
    isAttestationofStatedProfession: false,
    PurposeOfCorporation: null,
    isProfitNonProfitDesignation: false,
    isStockorNonStockAssociation: false,
    ErrorMsgs: {},
    UBINumber: null,
    FEINNo: null,
    BusinessName: null,
    BusinessNameSearch: null,
    NewBusinessName: null,
    BusinessID: 0,
    DBABusinessName: null,
    NewDBABusinessName: null,
    BusinessType: null,
    AmendedBusinessType: null,
    BusinessTypeID: 0,
    OtherProvisions: null,
    DurationType: null,
    DurationYears: 0,
    IsPerpetual: false,
    DurationExpireDate: "0001-01-01T00:00:00",
    EffectiveDate: "0001-01-01T00:00:00",
    EffectiveDateType: null,
    AvailableStatus: null,
    IsUploadDocumentExist: false,
    IsNameReserved: false,
    NameReservedId: 0,
    BusinessIndicator: null,
    FilingDate: "0001-01-01T00:00:00",
    Jurisdiction: 0,
    JurisdictionDesc: null,
    OldJurisdictionDesc: null,
    BusinessStatusID: 0,
    BusinessStatus: null,
    AgentName: null,
    IsOnline: false,
    CorrespondenceFileName: null,
    ReceiptFileName: null,
    FileLocationCorrespondence: null,
    FileLocationReceipt: null,
    DocumentID: 0,
    NameInHomeJurisdiction: null,
    NewNameInHomeJurisdiction: null,
    DateOfFormationInHomeJurisdiction: "0001-01-01T00:00:00",
    DateBeganDoingBusinessInWA: "0001-01-01T00:00:00",
    DateBeganDoingBusinessInWAType: null,
    FilingSuccess: false,
    createdBy: 0,
    createdIP: null,
    createdDate: "0001-01-01T00:00:00",
    LastARFiledDate: null,
    PlaceofFormationId: null,
    NextARDueDate: "0001-01-01T00:00:00",
    ARDueDate: "0001-01-01T00:00:00",
    DateOfIncorporation: "0001-01-01T00:00:00",
    PurposeAndPowersID: 0,
    IsInitialReportFiled: false,
    EntityTypesWithScreens: {},
    AllScreenParts: {},
    ShareValue: 0,
    DescriptionOfBusiness: "",
    DescriptionOfBusinessIncludedOnline: false,
    IsArticalsExist: false,
    OtherComments: null,

    //***** Added per TFS #1212 - KK, 11/6/2019
    //ControllingInterest: {}
};

var reinstatementEntity = {
    PrincipalEntity: {},
    ReinstatementAgent: {},
    PrincipalsList: [],
    AuthorizedPerson: {},
    Indicator: {},
    BusinessFiling: {},
    BusinessTransaction: {},
    NatureOfBusiness: {},
    UploadFileInfo: {},
    ReinstPrincipalsList: [],
    LLCPrincipalList: [],
    PrincipalOffice: {},
    TrustCreationEntity: {},
    ListBoardOfDirectors: [],
    PurposeAndPowers: {},
    CorporateShares: 0,
    NumberOfPartners: 0,
    JurisdictionOfTrust: 0,
    DescriptionOfBusinessIncluded: false,
    isForeign: false,
    GeneralPartnersSignatureConfirmation: false,
    IsDentalService: false,
    IsLLLPElection: false,
    isPursposeAndPower: false,
    isPurposeofCorporationSC: false,
    IsAttestationOfSocialPurpose: false,
    isCorporateSharesCommonStock: false,
    isCorporateSharesPreferedStock: false,
    isStockorNonStockAssociation: false,
    isAttestationOfStatedProfession: false,
    isGeneralPartnerSignatureConfirmation: false,
    IsPLLCAttestation: false,
    PurposeOfCorporation: null,
    CertificateName: null,
    isRAConsentStaffConsole: null,
    PurposeOfAssociation: null,
    JurisdictionOfTrustDesc: null,
    TrusteesList: [],
    DateTrustCreated: "0001-01-01T00:00:00",
    ErrorMsgs: {},
    UBINumber: null,
    BusinessName: null,
    BusinessNameSearch: null,
    NewBusinessName: null,
    BusinessID: 0,
    DBABusinessName: null,
    NewDBABusinessName: null,
    BusinessType: null,
    AmendedBusinessType: 0,
    AmendedBusinessTypeDesc: null,
    BusinessTypeID: 0,
    OtherProvisions: null,
    DurationType: null,
    DurationYears: 0,
    IsPerpetual: false,
    DurationExpireDate: "0001-01-01T00:00:00",
    EffectiveDate: "0001-01-01T00:00:00",
    EffectiveDateType: null,
    AvailableStatus: null,
    IsUploadDocumentExist: false,
    IsNameReserved: false,
    NameReservedId: 0,
    BusinessIndicator: null,
    FilingDate: "0001-01-01T00:00:00",
    Jurisdiction: 0,
    JurisdictionDesc: null,
    OldJurisdictionDesc: null,
    BusinessStatusID: 0,
    BusinessStatus: null,
    AgentName: null,
    IsOnline: false,
    CorrespondenceFileName: null,
    ReceiptFileName: null,
    FileLocationCorrespondence: null,
    FileLocationReceipt: null,
    DocumentID: 0,
    NameInHomeJurisdiction: null,
    NewNameInHomeJurisdiction: null,
    DateOfFormationInHomeJurisdiction: "0001-01-01T00:00:00",
    DateBeganDoingBusinessInWA: "0001-01-01T00:00:00",
    DateBeganDoingBusinessInWAType: null,
    FilingSuccess: false,
    createdBy: 0,
    createdIP: null,
    createdDate: "0001-01-01T00:00:00",
    LastARFiledDate: null,
    PlaceofFormationId: null,
    NextARDueDate: "0001-01-01T00:00:00",
    ARDueDate: "0001-01-01T00:00:00",
    DateOfIncorporation: "0001-01-01T00:00:00",
    PurposeAndPowersID: 0,
    IsInitialReportFiled: false,
    EntityTypesWithScreens: {},
    AllScreenParts: {},
    IsFormationWithIntialReport: false,
    UploadFileInfoList: [],
    OtherComments: null,
    ShareValue: null,
    DescriptionOfBusiness: null,
    DescriptionOfBusinessIncludedOnline: false,

    //***** Added per TFS #1212 - KK, 11/6/2019
    //ControllingInterest: {}
};

var amendmentEntity =
{
    UBINumber: null,
    BusinessName: null,
    BusinessNameSearch: null,
    NewBusinessName: null,
    BusinessID: 0,
    DBABusinessName: null,
    NewDBABusinessName: null,
    BusinessType: null,
    AmendedBusinessType: 0,
    AmendedBusinessTypeDesc: null,
    BusinessTypeID: 0,
    OtherProvisions: null,
    DurationType: null,
    DurationYears: 0,
    IsPerpetual: false,
    DurationExpireDate: null,
    EffectiveDate: "0001-01-01T00:00:00",
    EffectiveDateType: null,
    AvailableStatus: null,
    IsUploadDocumentExist: false,
    IsNameReserved: false,
    NameReservedId: 0,
    BusinessIndicator: null,
    FilingDate: "0001-01-01T00:00:00",
    Jurisdiction: 0,
    JurisdictionDesc: null,
    OldJurisdictionDesc: null,
    BusinessStatusID: 0,
    BusinessStatus: null,
    AgentName: null,
    IsOnline: false,
    CorrespondenceFileName: null,
    ReceiptFileName: null,
    FileLocationCorrespondence: null,
    FileLocationReceipt: null,
    DocumentID: 0,
    NameInHomeJurisdiction: null,
    NewNameInHomeJurisdiction: null,
    DateOfFormationInHomeJurisdiction: "0001-01-01T00:00:00",
    DateBeganDoingBusinessInWA: "0001-01-01T00:00:00",
    DateBeganDoingBusinessInWAType: null,
    FilingSuccess: false,
    createdBy: 0,
    createdIP: null,
    createdDate: "0001-01-01T00:00:00",
    LastARFiledDate: null,
    PlaceofFormationId: null,
    NextARDueDate: "0001-01-01T00:00:00",
    ARDueDate: "0001-01-01T00:00:00",
    DateOfIncorporation: "0001-01-01T00:00:00",
    PurposeAndPowersID: 0,
    IsInitialReportFiled: false,
    EntityTypesWithScreens: {},
    AllScreenParts: {},
    IsFormationWithIntialReport: false,
    IsPLLLPElection: false,
    IsLLLPElection: false,
    CertificateName: null,
    PrincipalEntity: {},
    Agent: {},
    PrincipalsList: [],
    AuthorizedPerson: {},
    Indicator: {},
    BusinessFiling: {},
    BusinessTransaction: {},
    NatureOfBusiness: {},
    UploadFileInfo: [],
    ListBoardOfDirectors: [],
    GrangeAddress: {},
    PurposeAndPowersEntity: {},
    PrincipalEntityInWA: {},
    MeetingPlace: {},
    PurposeAndPowers: {},
    IsMeetingPlaceExist: false,
    IsResponsibilitiesOfMembers: false,
    IsProfitNonProfitDesignation: false,
    IsOfficersAddress: false,
    IsPursposeAndPower: false,
    IsPurposeofCorporationSCConfirmation: false,
    IsAttestationOfSocialPurpose: false,
    AnyOtherProvision: null,
    NumberOfShares: 0,
    CorporateShares: 0,
    IsCorporateSharesCommonStock: false,
    IsCorporateSharesPreferedStock: false,
    IsStockorNonStockAssociation: false,
    IsAdoptionofArticlesofAmendmentSC: false,
    IsBuildingSocietyPurpose: false,
    IsBuildingSocietyStocksandShares: false,
    IsBuildingSocietyNamesAndAddressOfMembers: false,
    PurposeOfAssociation: null,
    IsDissention: false,
    IsCapitalStockProvided: false,
    IsAttestationofStatedProfession: false,
    IsSignedBySOSWithSeal: false,
    AdoptionType: null,
    DateOfAdoption: "0001-01-01T00:00:00",
    IsOfficersAndAddressProvided: false,
    PurposeOfGrange: 0,
    PurposeOfGrangeDesc: null,
    PurposeOfGrangeOther: null,
    JurisdictionOfTrust: null,
    JurisdictionOfTrustDesc: null,
    DateTrustCreated: "0001-01-01T00:00:00",
    IsDescriptionOfBusIncluded: false,
    isGeneralPartnerSignatureConfirmation: false,
    IsPllcAttestation: false,
    IsDistributionOfAssets: false,
    IsSecretaryAreProvided: false,
    NumberOfPartners: 0,
    IsGrangeAddressExist: false,
    FilingType: 0,
    IsReinstatementConsent: false,
    IsDentalService: false,
    IsRestatementIncluded: false,
    ErrorMsgs: {}
};
wacorpApp.factory('notificationService', function notificationService() {

        toastr.options = {
            "debug": false,
            "positionClass": "toast-top-right",
            "onclick": null,
            "fadeIn": 100,
            "fadeOut": 2000,
            "timeOut": 2500,
            "extendedTimeOut": 1000
        };

        var service = {
            displaySuccess: displaySuccess,
            displayError: displayError,
            displayWarning: displayWarning,
            displayInfo: displayInfo
        };

        return service;

        function displaySuccess(message) {
            toastr.success(message);
        }

        function displayError(error) {
            if (Array.isArray(error)) {
                error.forEach(function (err) {
                    toastr.error(err);
                });
            } else {
                toastr.error(error);
            }
        }

        function displayWarning(message) {
            toastr.warning(message);
        }

        function displayInfo(message) {
            toastr.info(message);
        }

    });

wacorpApp.factory('wacorpService', function wacorpService($http, $location, notificationService, $rootScope, ngDialog, $q) {
    var service = {
        get: get,
        post: post,
        confirmDialog: confirmDialog,
        confirmOkCancel: confirmOkCancel,
        alertDialog: alertDialog,
        customAlertDialog: customAlertDialog,
        fullAddressService: fullAddressService,
        cftFullAddressService: cftFullAddressService,
        isIndicatorValid: isValidIndicator,
        dateFormatService: dateFormat,
        closeAllDialog: closeAllDialog,
        sessionDialog: sessionDialog,
        ispOBoxExist: ispOBoxExist,
        //isValidAddress:isValidAddress,
        validateAddressOnRegister: validateAddressOnRegister,
        checkAccYearEndDateForReg: checkAccYearEndDateForReg,
        checkForShortFiscalYear: checkForShortFiscalYear,
        checkForAccYearMaxThenOneYear: checkForAccYearMaxThenOneYear,
        checkDateValidity: checkDateValidity,
        getShortYearStartDate: getShortYearStartDate,
        getShortYearEndDate: getShortYearEndDate,
        getpoboxAddress: getpoboxAddress,
        validatePoBox: validatePoBox,
        isFinancialMandetory: compareCurrentDate,
        validatePoBoxAddress: validatePoBoxAddress,
        shortFisicalYearDataFormat: shortFisicalYearDataFormat,
        addYearsToGivenDate: addYearsToGivenDate,
        IsAlphaNumeric: IsAlphaNumeric,
        addDaysToGivenDate: addDaysToGivenDate,
        validateOptionalQualifiers: validateOptionalQualifiers,
        isEndDateMoreThanToday: isEndDateMoreThanToday,
        validateInitialBoardListWithEntityName: validateInitialBoardListWithEntityName,
        validateIncorporatorListWithEntityName: validateIncorporatorListWithEntityName,
        validateExecutorListWithEntityName: validateExecutorListWithEntityName,
        validateGeneralPartnerWithEntityName: validateGeneralPartnerWithEntityName,
        isEndDateMoreThanToday: isEndDateMoreThanToday,
        nullCheckAddressCompnent: nullCheckAddressCompnent,
        enableEmailOpt: enableEmailOpt,
        setAgentObjForAllCorpFilings: setAgentObjForAllCorpFilings,
        isRAStreetAddressValid: isRAStreetAddressValid,
        isRAMailingAddressValid: isRAMailingAddressValid,
        compareAddress: compareAddress,
    };

    function validatePoBoxAddress(acpAddress) {
        var poboxaddress = getpoboxAddress();
        var flag = acpAddress.StreetAddress1 && acpAddress.StreetAddress1.toLowerCase() == poboxaddress.StreetAddress1.toLowerCase()
                    && acpAddress.City && acpAddress.City.toLowerCase() == poboxaddress.City.toLowerCase()
                    && acpAddress.State && acpAddress.State.toLowerCase() == poboxaddress.State.toLowerCase()
                    && acpAddress.Zip5 && acpAddress.Zip5.toLowerCase() == poboxaddress.Zip5.toLowerCase()
                    && acpAddress.Zip4 && acpAddress.Zip4.toLowerCase() == poboxaddress.Zip4.toLowerCase();
        return flag == null ? false : flag;
    }

    function validatePoBox(value) {
        value = angular.lowercase(value);
        var status = false;
        var address = new Array("po box", "pobox", "post office box", "post office", "p.o.box", "p.o. box", "p o box", "p. o. box", "po. box", "box", "p. o box", "pmb", "p.m.b", "p m b", "private mailbox", "private mail box");
        if (value != "") {

            angular.forEach(address, function (key, data) {
                var patt = new RegExp("^(" + key + ")$|^(" + key + ")\\W|\\W(" + key + ")\\W|\\W(" + key + ")$");
                var flg = patt.test(value);
                if (flg) {
                    status = true;
                }
            });
        }
        return status;
    }

    function getpoboxAddress() {
        return {
            Country: 'USA',
            StreetAddress1: 'PO BOX 257', StreetAddress2: '',
            City: 'OLYMPIA', State: 'WA', Zip5: '98507', Zip4: '0257',
            PostalCode: '', OtherState: ''
        };
    }

    function get(url, config, success, failure) {
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        config = config || {};
        return $http({
            method: "GET",
            url: url,
            params: config.params,
        })
                .then(function (result) {
                    success(result);
                }, function (error) {
                    if (error.status == '401') {
                        alertDialog('Authentication required.');
                        $rootScope.previousState = $location.path();
                        $location.path('/login');
                    }
                    else if (failure != null) {
                        failure(error);
                    }
                });
    }

    function post(url, data, success, failure) {
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;

        return $http({
            method: 'post',
            url: url,
            data: data,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
            }
        })
                .then(function (result) {
                    success(result);
                }, function (error) {
                    if (error.status == '401') {
                        alertDialog('Authentication required.');
                        $rootScope.previousState = $location.path();
                        $location.path('/login');
                    }
                    else if (failure != null) {
                        failure(error);
                    }
                });
    }

    function confirmDialog(message, yesCallback, noCalback) {
        //var dialogScope = $scope.$new();
        //dialogScope.alertMessage = message;
        //'<button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="closeThisDialog(1)">Yes' +
        message = message || "Are you sure you would like to delete the record?";
        ngDialog.openConfirm({
            template:
                     '<p>' + message + '</p>' +
                     '<div class="ngdialog-buttons">' +
                         '<button type="button" class="ngdialog-button btn btn-brown" ng-click="closeThisDialog(0)">No' +
                         '<button type="button" class="ngdialog-button btn-success" ng-click="closeThisDialog(1)">Yes' +
                     '</button></div>',
            plain: true,
            className: 'ngdialog-theme-default',
            preCloseCallback: function (value) {
                if (value === 1) {
                    if (yesCallback) yesCallback();
                }
                else {
                    if (noCalback)
                        noCalback();
                }
            }
            //,scope: dialogScope

        });
    }

    function confirmOkCancel(message, yesCallback, noCalback) {
        //var dialogScope = $scope.$new();
        //dialogScope.alertMessage = message;
        //'<button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="closeThisDialog(1)">Yes' +
        message = message || "Are you sure you want to delete?";
        ngDialog.openConfirm({
            template:
                    '<p>' + message + '</p>' +
                    '<div class="ngdialog-buttons">' +
                        '<button type="button" class="ngdialog-button btn btn-brown" ng-click="closeThisDialog(0)">Cancel' +
                        '<button type="button" class="ngdialog-button btn-success" ng-click="closeThisDialog(1)">Ok' +
                    '</button></div>',
            plain: true,
            className: 'ngdialog-theme-default',
            preCloseCallback: function (value) {
                if (value === 1) {
                    if (yesCallback) yesCallback();
                }
                else {
                    if (noCalback)
                        noCalback();
                }
            }
            //,scope: dialogScope

        });
    }

    function alertDialog(message, callback) {
        ngDialog.openConfirm({
            template:
                    '<p>' + message + '</p>' +
                    '<div class="ngdialog-buttons">' +
                        '<button type="button" class="ngdialog-button btn-success" ng-click="closeThisDialog(1)">Ok' +
                    '</button></div>',
            plain: true,
            className: 'ngdialog-theme-default',
            preCloseCallback: function (value) {
                if (callback) callback();
            }
        });
    }

    function customAlertDialog(message, callback) {
        ngDialog.openConfirm({
            template:
                     message +
                    '<div class="ngdialog-buttons">' +
                        '<button type="button" class="ngdialog-button btn-success" ng-click="closeThisDialog(1)">Ok' +
                    '</button></div>',
            plain: true,
            className: 'ngdialog-theme-default',
            preCloseCallback: function (value) {
                if (callback) callback();
            }
        });
    }

    function sessionDialog() {
        ngDialog.openConfirm({
            template:
                    "<p>You'll be logged out in {{countdown}} second(s).</p>" +
                    "<div class='ngdialog-buttons'></div>",
            plain: true,
            className: 'ngdialog-theme-default',
            controller: 'ngDialogController'
        });


    }

    function ispOBoxExist(value) {
        value = angular.lowercase(value);
        var status = false;
        var address = new Array("po box", "pobox", "post office box", "post office", "p.o.box", "p.o. box", "p o box", "p. o. box", "po. box", "box", "p. o box", "pmb", "p.m.b", "p m b", "private mailbox", "private mail box");
        if (value != "") {

            angular.forEach(address, function (key, data) {
                var patt = new RegExp("^(" + key + ")$|^(" + key + ")\\W|\\W(" + key + ")\\W|\\W(" + key + ")$");
                var flg = patt.test(value);
                if (flg) {
                    status = true;
                }
            });
        }
        return status;
    }

    function closeAllDialog() {
        ngDialog.closeAll();
    }

    function checkAccYearEndDateForReg(accYearEndDate, flag) {
        var currentDate = new Date(jQuery.now());
        var endDate = new Date(accYearEndDate);
        if (flag) {
            if (endDate > currentDate) {
                return true
            }
            else {
                return false;
            }
        }
        else {
            var currentDateMinus11Months = new Date(addMonths(currentDate, -11));
            currentDateMinus11Months = new Date(addDays(currentDateMinus11Months, -1));
            if (endDate >= currentDateMinus11Months) {
                return false;
            }
            else {
                return true;
            }
        }
    };

    function addMonths(date, months) {
        date.setMonth(date.getMonth() + months);
        return date;
    };

    function addDays(date, days) {
        date.setDate(date.getDate() + days);
        return date;
    };

    function isEndDateMoreThanToday(endDate) {
        var today = new Date(jQuery.now());
        var accountingEndDate = new Date(endDate);
        if (accountingEndDate > today) {
            return true;
        }
        else {
            return false;
        }
    };


    //Check whether the difference between current end date and previous year end date is greater than One Year or not
    function checkForAccYearMaxThenOneYear(currentStartDateForAmendment, previousEndDate) {

        var previousDate = new Date(previousEndDate);
        var previousYear = previousDate.getFullYear();
        var previousMonth = previousDate.getMonth();
        var previousDay = previousDate.getDate();
        var futureDate = new Date(previousYear + 1, previousMonth, previousDay);
        var currentStartDate = new Date(currentStartDateForAmendment);
        if (currentStartDate > futureDate) {
            return true;
        }
        else {
            return false;
        }
    };

    //Check whether it is a short fiscal year
    function checkForShortFiscalYear(currentStartDateForAmendment, previousStartDate, previousEndDate) {
        var previousEndingDate = new Date(previousEndDate);
        var previousYear = previousEndingDate.getFullYear();
        var previousMonth = previousEndingDate.getMonth();
        var previousDay = previousEndingDate.getDate();
        var futureDate = new Date(previousYear + 1, previousMonth, previousDay);
        var shortFiscalYearGapDate = new Date(previousYear, previousMonth, previousDay + 1);

        var currentDate = new Date(previousStartDate);
        var previousStartYear = currentDate.getFullYear();
        var previousStartMonth = currentDate.getMonth();
        var previousStartDay = currentDate.getDate();
        var previousStartDate = new Date(previousStartYear, previousStartMonth, previousStartDay);

        var currentStartDate = new Date(currentStartDateForAmendment);
        //if (currentStartDate < futureDate && currentStartDate > previousStartDate) {
        if (currentStartDate < futureDate && currentStartDate > shortFiscalYearGapDate) {
            return true
        }
        else {
            return false;
        }
    };

    //Date Comparisons
    function checkDateValidity(startDate, endDate, isFicalYearshown) {
        return validateDates(startDate, endDate, isFicalYearshown);
    };

    function validateDates(previousEndDate, currentDate, isFicalYearshown) {
        previousEndDate = dateFormat(previousEndDate);
        currentDate = dateFormat(currentDate);
        if (previousEndDate != null && currentDate != null) {
            var msg = "";
            var previousDate = new Date(previousEndDate);
            var noOfYearsAdd = 1;
            //previousDate.setYear(previousDate.getYear() + noOfYearsAdd);
            var previousYear = previousDate.getFullYear() + 1;
            var previousMonth = previousDate.getMonth();
            var previousDay = previousDate.getDate();
            var previousDatePlusOneDay = new Date(previousDate);
            previousDatePlusOneDay.setDate(previousDatePlusOneDay.getDate() + 1);
            var lastFinancialEndDate = new Date(previousYear, previousMonth, previousDay);
            var currentStartDate = new Date(currentDate);
            var flag = isFicalYearshown;
            if (currentStartDate < lastFinancialEndDate) {
                var noOfDaysAdded = 1;
                var currentDatePlusOneDay = new Date(currentStartDate);
                currentDatePlusOneDay.setDate(currentDatePlusOneDay.getDate() + 1);
                if (previousDatePlusOneDay < currentStartDate) {
                    return "SFY";
                }
                else if (previousDatePlusOneDay > currentStartDate) {
                    return "SDgPnD"

                } else {
                    return "";
                }
            }
            else {
                // msg = msg + " Short accounting due can not be greater than one year.";
                return "Y1Plus";
            }
        } else {
            return "";
        }
    };

    function checkForAccYearMaxThenOneYear(previousEndDate, currentDate, isFicalYearshown) {
        var msg = "";
        var previousDate = new Date(previousEndDate);
        var noOfYearsAdd = 1;
        //previousDate.setYear(previousDate.getYear() + noOfYearsAdd);
        var previousYear = previousDate.getFullYear() + 1;
        var previousMonth = previousDate.getMonth();
        var previousDay = previousDate.getDate();
        var lastFinancialEndDate = new Date(previousYear, previousMonth, previousDay);
        var currentStartDate = new Date(currentDate);
        var flag = isFicalYearshown;
        if (currentStartDate < lastFinancialEndDate) {
            var noOfDaysAdded = 1;
            var currentDatePlusOneDay = new Date(currentStartDate);
            currentDatePlusOneDay.setDate(currentDatePlusOneDay.getDate() + 1);

            if (currentStartDate > new Date(currentDatePlusOneDay.getFullYear(), currentDatePlusOneDay.getMonth(), currentDatePlusOneDay.getDate())) {
                if (flag == "false") {
                    return "SFY";
                }
                else {
                    return "";
                }
            }
            else if (currentStartDate < new Date(currentDatePlusOneDay.getFullYear(), currentDatePlusOneDay.getMonth(), currentDatePlusOneDay.getDate())) {
                return "SDgPnD";//Accounting start date should be greater then latest financial history end date.
            }
            else {
                return "";
            }
        }
        else {
            // msg = msg + " Short accounting due can not be greater than one year.";
            return "Y1Plus";
        }
    };

    // Check whether it is a short fiscal year
    function checkForShortFiscalYear(currentStartDateForAmendment, previousStartDate, previousEndDate) {

        var previousEndingDate = new Date(previousEndDate);
        var previousYear = previousEndingDate.getFullYear();
        var previousYearPlusOne = previousEndingDate.getFullYear() + 1;

        var previousMonth = previousEndingDate.getMonth();
        var previousDay = previousEndingDate.getDate();

        var futureDate = new Date(previousYearPlusOne, previousMonth, previousDay);

        var numberOfDaysMore = 1;
        previousEndingDate.setDate(previousEndingDate.getDate() + numberOfDaysMore);

        var date = previousEndingDate.getDate();

        var shortFiscalYearGapDate = new Date(previousYear, previousMonth, date);

        var currentDate = new Date(previousStartDate);
        var previousStartYear = currentDate.getFullYear();
        var previousStartMonth = currentDate.getMonth();
        var previousStartDay = currentDate.getDate();
        var previousStartDate = new Date(previousStartYear, previousStartMonth, previousStartDay);

        var currentStartDate = new Date(currentStartDateForAmendment);
        //if (currentStartDate < futureDate && currentStartDate > previousStartDate) {
        if (currentStartDate < futureDate && currentStartDate > previousEndingDate) {
            return true
        }
        else {
            return false;
        }
    };

    function checkForShortFinancialYear(newbeginDate, lastendDate) {
        var days = 0;
        if (lastendDate != null) {
            var From_date = new Date(lastendDate);
            var To_date = new Date(newbeginDate);
            var diff_date = To_date - From_date;
            var years = Math.floor(diff_date / 31536000000);
            var months = Math.floor((diff_date % 31536000000) / 2628000000);
            days = Math.floor(((diff_date % 31536000000) % 2628000000) / 86400000);
        }
        return days > 0;
    }

    //Get Fiscal Year Start Date
    function getShortYearStartDate(prevDate) {
        var previousDate = new Date(prevDate);
        var previousYear = previousDate.getFullYear();
        var previousMonth = previousDate.getMonth();
        var previousDay = previousDate.getDate();
        var strtDate = new Date(previousYear, previousMonth, previousDay + 1);
        return strtDate;
    };

    //Get Fiscal Year End Date
    function getShortYearEndDate(prevDate) {
        var previousDate = new Date(prevDate);
        var previousYear = previousDate.getFullYear();
        var previousMonth = previousDate.getMonth();
        var previousDay = previousDate.getDate();
        var endDate = new Date(previousYear, previousMonth, previousDay - 1);
        return endDate;
    };

    //Check Whether Financial Is Mandetory
    function compareCurrentDate(accYearEndDate) {
        var currentDate = new Date(jQuery.now());
        var endDate = new Date(accYearEndDate);
        if (endDate < currentDate) {
            return true;
        }
        else {
            return false;
        }
    };

    //Add No Years For the Given Date
    function addYearsToGivenDate(oldDate, yrs) {
        var noOfYears = yrs;
        oldDate = new Date(oldDate);
        var resultYear = oldDate.getFullYear();
        var resultMonth = oldDate.getMonth();
        var resultDate = oldDate.getDate();
        var datePlusNoOfYears = new Date(resultYear + noOfYears, resultMonth, resultDate);
        return datePlusNoOfYears;
    };

    //Add No Days For the Given Date
    function addDaysToGivenDate(oldDate, days) {
        var noOfDays = days;
        oldDate = new Date(oldDate);
        var resultYear = oldDate.getFullYear();
        var resultMonth = oldDate.getMonth();
        var resultDate = oldDate.getDate();
        var datePlusNoOfDays = new Date(resultYear, resultMonth, resultDate + noOfDays);
        return datePlusNoOfDays;
    };

    //function fulladdress(addressData) {
    //    var address = {};
    //    address = addressData;
    //    var fullAddres = (address.StreetAddress1 || "") + PrependComa((address.StreetAddress2 || ""), ', ')
    //                    + PrependComa((address.City || ""), ', ')
    //                    + ((address.Country == 'USA') ? PrependComa((address.State || ""), ', ') : PrependComa((address.OtherState || ""), ', '))
    //                    + ((address.Country == 'USA') ? PrependComa((address.Zip5 || ""), ', ') + PrependComa((address.Zip4 || ""), "-") : PrependComa((address.PostalCode || ""), ', '))
    //                    + PrependComa((address.Country || ""), ', ');
    //    return (fullAddres == null || fullAddres == '') ? '' : fullAddres;
    //}

    var PrependComa = function (val, indicator) {
        return val == "" ? "" : indicator + val;
    };

    // Full Address 
    function fullAddressService(addScope) {
        // Other than Country and state fields are empty
        var isEmptyAddrss = (angular.isNullorEmpty(addScope.StreetAddress1) && angular.isNullorEmpty(addScope.StreetAddress2) && angular.isNullorEmpty(addScope.City) &&
                            angular.isNullorEmpty(addScope.OtherState) && angular.isNullorEmpty(addScope.Zip4) && angular.isNullorEmpty(addScope.Zip5))
        var fullAddress = "";
        if (!angular.isNullorEmpty(addScope.StreetAddress1))
            fullAddress = (addScope.StreetAddress1 || "");
        if (!angular.isNullorEmpty(addScope.StreetAddress2))
            fullAddress += angular.isNullorEmpty(fullAddress) ? (addScope.StreetAddress2 || "") : PrependComa((addScope.StreetAddress2 || ""), ', ');
        if (!angular.isNullorEmpty(addScope.City))
            fullAddress += angular.isNullorEmpty(fullAddress) ? (addScope.City || "") : PrependComa((addScope.City || ""), ', ');
        if (!angular.isNullorEmpty(addScope.State))
            fullAddress += angular.isNullorEmpty(fullAddress) ? ((addScope.Country == 'USA' || addScope.Country == 'CAN') ? PrependComa((addScope.State || ""), ' ') : PrependComa((addScope.OtherState || ""), ' '))
                : ((addScope.Country == 'USA' || addScope.Country == 'CAN') ? PrependComa((addScope.State || ""), ', ') : PrependComa((addScope.OtherState || ""), ', '));
        if (!angular.isNullorEmpty(fullAddress))
            fullAddress += ((addScope.Country == 'USA') ? PrependComa((addScope.Zip5 || ""), ', ')
                 + PrependComa((addScope.Zip4 || ""), "-") : PrependComa((addScope.PostalCode || ""), ', '));
        if (!angular.isNullorEmpty(addScope.Country))
            fullAddress += angular.isNullorEmpty(fullAddress) ? PrependComa(((addScope.Country == 'USA' ? 'UNITED STATES' : addScope.Country) || ""), '') : PrependComa(((addScope.Country == 'USA' ? 'UNITED STATES' : addScope.Country) || ""), ', ');

        return isEmptyAddrss ? '' : fullAddress;
    }

    function cftFullAddressService(addScope) {
        var fullAddr = (addScope.StreetAddress1 || "") + PrependComa((addScope.StreetAddress2 || ""), ', ')
                 + PrependComa((addScope.City || ""), ', ')
                 + ((addScope.Country == 'USA' || addScope.Country == 'CAN') ? PrependComa((addScope.State || ""), ', ') : PrependComa((addScope.OtherState || ""), ', '))
                 + ((addScope.Country == 'USA' && addScope.State == 'WA') ? PrependComa((addScope.CountyName || ""), ', ') : "")
                 + ((addScope.Country == 'USA') ? PrependComa((addScope.Zip5 || ""), ', ')
                 + PrependComa((addScope.Zip4 || ""), "-") : PrependComa((addScope.PostalCode || ""), ', '))
                 + PrependComa(((addScope.Country == 'USA' ? 'UNITED STATES' : addScope.Country) || ""), ', ');
        return (fullAddr == null || fullAddr == '') ? '' : fullAddr;
    }

    function isValidIndicator(entity) {

        if ((entity.IsDBAInUse || entity.IsDBAInUse === true)) {
            if (entity.DBABusinessName == '' || !entity.isDBANameAvailable)
                return false;
            else
                return true;
        }

        var indicatorsCSV = null;
        var indicatorslist = null;
        var indicatorsMustNotCSV = null;
        var IndicatorsDisplay = null;
        indicatorsMustNotCSV = entity.Indicator.IndicatorsMustNotCSV;
        // is dental service checked true
        if (entity.Indicator.isDentalCheck) {
            indicatorsCSV = entity.Indicator.PSIndicatorsCSV;
            indicatorslist = entity.Indicator.PSIndicatorList;
            indicatorsDisplay = entity.Indicator.PSIndicatorsDisplay;
        }
        else {
            indicatorsCSV = entity.Indicator.IndicatorsCSV;
            indicatorslist = entity.Indicator.Indicators;
            indicatorsDisplay = entity.Indicator.IndicatorsDisplay;
        }
        var isValid = constant.ZERO;
        var isInValidIndicator = constant.ZERO;
        var entityName;

        if (entity.isUpdate != undefined && entity.isUpdate && entity.isUpdate != false) {
            entityName = entity.BusinessName + ' ' + indicatorsCSV;
            entityName = entityName.toLowerCase().replace(/[{|}|(|)|-|;|'|\"]/g, '');
        }
        else {
            entityName = entity.BusinessName != null ? entity.BusinessName.toLowerCase().replace(/[{|}|(|)|-|;|'|\"]/g, '') : null;
        }

        if (indicatorsCSV != null && indicatorsCSV != undefined && indicatorsCSV != '') {

            angular.forEach(indicatorslist, function (value) {

                value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                // isValid = new RegExp("^" + value + "\\s").test(entityName) ? isValid + constant.ONE : isValid;
                // Start With indicator
                if (new RegExp("^" + value + "\\s").test(entityName)) {
                    if (entityName.indexOf(value + ' ') != -1) {
                        isValid = isValid + constant.ONE;
                        return;
                    }
                }
            });

            if (isValid == constant.ZERO) {
                angular.forEach(indicatorslist, function (value) {
                    value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                    // isValid = new RegExp("\\s" + value + "\\s").test(entityName) ? isValid + constant.ONE : isValid;
                    // Middile With indicator
                    if (new RegExp("\\s" + value + "\\s").test(entityName)) {
                        if (entityName.indexOf(' ' + value + ' ') != -1) {
                            isValid = isValid + constant.ONE;
                            return;
                        }
                    }
                });
            }

            if (isValid == constant.ZERO) {
                angular.forEach(indicatorslist, function (value) {
                    value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                    // isValid = new RegExp("\\s" + value + "$").test(entityName) ? isValid + constant.ONE : isValid;
                    // Last With indicator
                    if (new RegExp("\\s" + value + "$").test(entityName)) {
                        if (entityName.indexOf(' ' + value) != -1) {
                            isValid = isValid + constant.ONE;
                            return;
                        }
                    }
                });
            }
        }
        else
        {
            isValid = constant.ONE; //For all entities we are not going to have Indicators, that's the reason default we are considering as true.
        }

        if (indicatorsMustNotCSV != null && indicatorsMustNotCSV != undefined && indicatorsMustNotCSV != '') {
            var isNonCorp = false;
            var aNonprofitCorp = "a nonprofit corporation";
            var aNonprofitMutualCorp = "a nonprofit mutual corporation";
            var corporation = "corporation";

            if (entityName != "" && entityName != null) {
                isNonCorp = new RegExp("^" + aNonprofitCorp + "\\s").test(entityName) || new RegExp("^" + aNonprofitMutualCorp + "\\s").test(entityName);

                if (!isNonCorp) {
                    isNonCorp = new RegExp("\\s" + aNonprofitCorp + "\\s").test(entityName) || new RegExp("\\s" + aNonprofitMutualCorp + "\\s").test(entityName);
                }

                if (!isNonCorp) {
                    isNonCorp = new RegExp("\\s" + aNonprofitCorp + "$").test(entityName) || new RegExp("\\s" + aNonprofitMutualCorp + "$").test(entityName);
                }
            }

            var indicatorsMustNot = indicatorsMustNotCSV.toLowerCase().split(',');
            angular.forEach(indicatorsMustNot, function (value) {

                value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                if (isNonCorp && value == corporation) {
                    isInValidIndicator = constant.ZERO;
                }
                else {
                    // isInValidIndicator = new RegExp("^" + value + "\\s").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                    // Start With indicator
                    if (new RegExp("^" + value + "\\s").test(entityName)) {
                        if (entityName.indexOf(value + ' ') != -1) {
                            isInValidIndicator = isInValidIndicator + constant.ONE;
                            return;
                        }
                    }
                }
            });

            if (isInValidIndicator >= constant.ZERO) {
                angular.forEach(indicatorsMustNot, function (value) {

                    value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                    if (isNonCorp && value == corporation) {
                        isInValidIndicator = constant.ZERO;
                    }
                    else
                    {
                        // isInValidIndicator = new RegExp("\\s" + value + "\\s").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                        // Middile With indicator
                        if (new RegExp("\\s" + value + "\\s").test(entityName)) {
                            if (entityName.indexOf(' ' + value + ' ') != -1) {
                                isInValidIndicator = isInValidIndicator + constant.ONE;
                                return;
                            }
                        }
                    }
                });
            }

            if (isInValidIndicator >= constant.ZERO) {

                angular.forEach(indicatorsMustNot, function (value) {

                    value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                    if (isNonCorp && value == corporation) {
                        isInValidIndicator = constant.ZERO;
                    }
                    else {
                        // isInValidIndicator = new RegExp("\\s" + value + "$").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                        // Last With indicator
                        if (new RegExp("\\s" + value + "$").test(entityName)) {
                            if (entityName.indexOf(' ' + value) != -1) {
                                isInValidIndicator = isInValidIndicator + constant.ONE;
                                return;
                            }
                        }
                    }
                });
            }
        }
        return isValid && isInValidIndicator == constant.ZERO;
    };

    //function isValidIndicator(entity) {
    //    var indicatorsCSV = null;
    //    var indicatorslist = null;

    //    // is dental service checked true
    //    if (entity.Indicator.isDentalCheck) {
    //        indicatorsCSV = entity.Indicator.PSIndicatorsCSV;
    //        indicatorslist = entity.Indicator.PSIndicatorList;
    //        indicatorsDisplay = entity.Indicator.PSIndicatorsDisplay;
    //    }
    //    else {
    //        indicatorsCSV = entity.Indicator.IndicatorsCSV;
    //        indicatorslist = entity.Indicator.Indicators;
    //        indicatorsDisplay = entity.Indicator.IndicatorsDisplay;

    //    }

    //    var isValid = 0;
    //    var entityName;
    //    if (indicatorsCSV != null && indicatorsCSV != undefined && indicatorsCSV != '') {

    //        if (entity.isUpdate != undefined && entity.isUpdate && entity.isUpdate != false) {
    //            entityName = entity.BusinessName + ' ' + indicatorsCSV;
    //            entityName = entityName.toLowerCase().replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '');
    //        }
    //        else
    //            entityName = entity.BusinessName != null ? entity.BusinessName.toLowerCase().replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '') : null;

    //        angular.forEach(indicatorslist, function (value) {
    //            value = value.replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
    //            isValid = new RegExp("^" + value + "\\s").test(entityName) ? isValid + 1 : isValid;
    //        });

    //        if (isValid == 0) {
    //            angular.forEach(indicatorslist, function (value) {
    //                value = value.replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
    //                isValid = new RegExp("\\s" + value + "\\s").test(entityName) ? isValid + 1 : isValid;
    //            });
    //        }

    //        if (isValid == 0) {
    //            angular.forEach(indicatorslist, function (value) {
    //                value = value.replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
    //                isValid = new RegExp("\\s" + value + "$").test(entityName) ? isValid + 1 : isValid;
    //            });
    //        }
    //    }
    //    else
    //        isValid = 1; //For all entities we are not going to have Indicators, that's the reason default we are considering as true.
    //    return entity.BusinessName != null && entity.BusinessName != "" && isValid > 0 ? true : false;
    //};

    function dateFormat(currentDate) {
        if (currentDate) {
            if (typeof currentDate == "string" && currentDate != "0001-01-01T00:00:00" && currentDate.indexOf('-') != -1) {
                var dateParts = currentDate.substring(0, 10).split('-');
                var timePart = currentDate.substr(11);
                currentDate = dateParts[1] + '/' + dateParts[2] + '/' + dateParts[0] + ' ' + timePart;
            }
            //var newDate = currentDate.replace(/-/g, "/");
            // To Check Whether the browser used is Safari Or Not -- TFS #3126
            //var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
            //if (isSafari) {
            var date = new Date(currentDate);
            if (date == "Invalid Date") {
                if (currentDate == "0001-01-01T00:00:00") {
                    return null;
                }
                else {
                    return currentDate;
                }
            }
            else if (date == "0001-01-01T00:00:00") {
                return null;
            }
            //}
            var date = new Date(currentDate);
            var year = date.getFullYear();
            var month = (1 + date.getMonth()).toString();
            month = month.length > 1 ? month : '0' + month;
            var day = date.getDate().toString();
            day = day.length > 1 ? day : '0' + day;
            var formattedDate = month + '/' + day + '/' + year;
            return (formattedDate == null || formattedDate == '' || formattedDate == "01/01/0001" || formattedDate == "01/01/1" || formattedDate == "00/00/0000" || formattedDate == "NaN/NaN/NaN" || formattedDate == "01/01/1970" || formattedDate == "01/01/70") ? null : formattedDate;
        } else {
            return null;
        }
    }

    function getFormattedDate(date) {
    }
    //this is to validate the screen parts in save functionality
    function AllScreenParts(obj) {
        var index = 0;
        angular.forEach(obj.AllScreenParts, function (value, key) {
            obj['AllScreenParts[' + index + '].Key'] = key;
            obj['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });
    }

    function EntityTypesWithScreens(obj) {
        var index = 0;
        angular.forEach(obj.AllScreenParts, function (value, key) {
            obj['EntityTypesWithScreens[' + index + '].Key'] = key;
            obj['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
    }

    //function isValidAddress(obj) {
    //    post(webservices.AddressValidation.ValidateAddress, obj,
    //        function (resp) {
    //            return obj.isValidAddress = resp.data;
    //        }, function (resp) {

    //        });
    //}

    function shortFisicalYearDataFormat(obj) {
        obj.AllContributionsReceivedForShortFY = parseInt(obj.AllContributionsReceivedForShortFY, 10) == 0 ? '' : obj.AllContributionsReceivedForShortFY;
        obj.AveragePercentToCharityForShortFY = parseInt(obj.AveragePercentToCharityForShortFY, 10) == 0 ? '' : obj.AveragePercentToCharityForShortFY;
        obj.AmountOfFundsForShortFY = parseInt(obj.AmountOfFundsForShortFY, 10) == 0 ? '' : obj.AmountOfFundsForShortFY;
        obj.BeginingGrossAssetsForShortFY = parseInt(obj.BeginingGrossAssetsForShortFY, 10) == 0 ? '' : obj.BeginingGrossAssetsForShortFY;
        obj.RevenueGDfromSolicitationsForShortFY = parseInt(obj.RevenueGDfromSolicitationsForShortFY, 10) == 0 ? '' : obj.RevenueGDfromSolicitationsForShortFY;
        obj.RevenueGDRevenueAllOtherSourcesForShortFY = parseInt(obj.RevenueGDRevenueAllOtherSourcesForShortFY, 10) == 0 ? '' : obj.RevenueGDRevenueAllOtherSourcesForShortFY;
        obj.TotalDollarValueofGrossReceiptsForShortFY = parseInt(obj.TotalDollarValueofGrossReceiptsForShortFY, 10) == 0 ? '' : obj.TotalDollarValueofGrossReceiptsForShortFY;
        obj.ExpensesGDExpendituresProgramServicesForShortFY = parseInt(obj.ExpensesGDExpendituresProgramServicesForShortFY, 10) == 0 ? '' : obj.ExpensesGDExpendituresProgramServicesForShortFY;
        obj.ExpensesGDValueofAllExpendituresForShortFY = parseInt(obj.ExpensesGDValueofAllExpendituresForShortFY, 10) == 0 ? '' : obj.ExpensesGDValueofAllExpendituresForShortFY;
        obj.EndingGrossAssetsForShortFY = parseInt(obj.EndingGrossAssetsForShortFY, 10) == 0 ? '' : obj.EndingGrossAssetsForShortFY;
        obj.PercentToProgramServicesForShortFY = parseInt(obj.PercentToProgramServicesForShortFY, 10) == 0 ? '' : obj.PercentToProgramServicesForShortFY;
        obj.TotalRevenueForShortFY = parseInt(obj.TotalRevenueForShortFY, 10) == 0 ? '' : obj.TotalRevenueForShortFY;
        obj.GrantContributionsProgramServiceForShortFY = parseInt(obj.GrantContributionsProgramServiceForShortFY, 10) == 0 ? '' : obj.GrantContributionsProgramServiceForShortFY;
        obj.CompensationForShortFY = parseInt(obj.CompensationForShortFY, 10) == 0 ? '' : obj.CompensationForShortFY;
        obj.TotalExpensesForShortFY = parseInt(obj.TotalExpensesForShortFY, 10) == 0 ? '' : obj.TotalExpensesForShortFY;
        return obj;
    }

    function validateAddressOnRegister(addressObj) {
        var defer = $q.defer();
        var successFunction = function (data) {
            //For Address Valid 
            defer.resolve(data);
        };
        if (isUSPSServiceValid && addressObj.StreetAddress1 != "") {
            var addressorg = {
                Address1: addressObj.StreetAddress1,
                Address2: addressObj.StreetAddress2,
                City: addressObj.City,
                State: addressObj.State,
                Zip5: addressObj.Zip5,
                Zip4: addressObj.Zip4,
                isUserNonCommercialRegisteredAgent: addressObj.isUserNonCommercialRegisteredAgent,
                IsButtonClick: true
            };

            var isvalusExist = (angular.isDefined(addressorg.Address1) && !angular.isNullorEmpty(addressorg.Address1)
                              && angular.isDefined(addressorg.City) && !angular.isNullorEmpty(addressorg.City)
                              && angular.isDefined(addressorg.State) && !angular.isNullorEmpty(addressorg.State))
                              && (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5))
                              && (angular.isDefined(addressorg.isUserNonCommercialRegisteredAgent) && !angular.isNullorEmpty(addressorg.isUserNonCommercialRegisteredAgent));

            var failureFunction = function (data) {
                //For Address InValid
                defer.reject(data);
            };
            if (addressObj.Country === codes.USA && isvalusExist) {
                var postResult = post(webservices.Common.getValidAddress, addressorg, function (response) {
                    var result = response.data;
                    if (result != undefined && result.HasErrors) {
                        //ngmodel.$setValidity('isvalidaddress', false);
                        //defer.reject(result);
                        failureFunction(result.ErrorDescription);

                    } else {
                        //ngmodel.$setValidity('isvalidaddress', true);
                        //defer.resolve(result);
                        successFunction(result);
                    }
                    //return defer.promise;
                }, function () {
                    failureFunction("Error!!!");
                });
                return defer.promise;
            }
            else {
                successFunction(addressObj);
                //return defer.promise;
            }
            return defer.promise;
        }
        else {
            successFunction(addressObj);
            return defer.promise;
        }
    };

    function IsAlphaNumeric(event) {
        return /^[a-z0-9]+$/i.test(String.fromCharCode(event.which || event.keyCode));
    };

    function validateOptionalQualifiers(integratedAux, politicalOrg, fundsForIndividual, raisingLessThan5000, anyOnePaid) {
        if (integratedAux) {
            return true;
        }
        else if (politicalOrg) {
            return true;
        }
        else if (fundsForIndividual && !anyOnePaid) {
            return true;
        }
        else if (raisingLessThan5000 && !anyOnePaid) {
            return true;
        }
        else {
            return false;
        }
    };

    function validateInitialBoardListWithEntityName(value) {
        var entityName = '';
        var firstName = '';
        var lastName = '';
        var fullName = '';
        var businessName = '';
        var result = '';
        var type = '';
        //businessName = $('#id-txtBusiessName').val();
        businessName = value;
        if (businessName) {
            businessName = businessName.replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim();
            $('#InitialBoardOfDirector_gridList table tbody').find('tr').each(function myfunction(i, ele) {
                var $tds = $(this).find('td'),
                    type = $tds.eq(1).text().toLowerCase(),
                entityName = $tds.eq(2).text().replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim(),
                firstName = $tds.eq(3).text(),
                lastName = $tds.eq(4).text();
                fullName = firstName + '' + lastName;
                fullName = fullName.replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim();
                if (entityName != "" && type == "entity") {
                    if (entityName == businessName)
                        return result = true;
                    else
                        return result = false;
                }
                else if (firstName != "" && lastName != "") {
                    if (fullName == businessName) {
                        return result = true;
                    }
                    else {
                        return result = false;
                    }
                }
            });
        }
        else
            return result = false;

        return result;
    }

    function validateIncorporatorListWithEntityName(value) {
        var entityName = '';
        var firstName = '';
        var lastName = '';
        var fullName = '';
        var businessName = '';
        var result = '';
        var type = '';
        var isValid = false;
        //businessName = $('#id-txtBusiessName').val();
        businessName = value;
        if (businessName) {
            businessName = businessName.replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim();
            $('#Incorporator_gridList table tbody').find('tr').each(function myfunction(i, ele) {
                var $tds = $(this).find('td'),
                    type = $tds.eq(1).text().toLowerCase(),
                entityName = $tds.eq(2).text().replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim(),
                firstName = $tds.eq(3).text(),
                lastName = $tds.eq(4).text();
                fullName = firstName + '' + lastName;
                fullName = fullName.replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim();
                if (entityName != "" && type == "entity") {
                    if (entityName == businessName)
                        return result = true;
                    else
                        return result = false;
                }
                else if (firstName != "" && lastName != "") {
                    if (fullName == businessName) {
                        return result = true;
                    }
                    else {
                        return result = false;
                    }
                }
            });
        }
        else
            return result = false;

        return result;
    }

    function validateExecutorListWithEntityName(value) {
        var entityName = '';
        var firstName = '';
        var lastName = '';
        var fullName = '';
        var businessName = '';
        var result = '';
        var type = '';
        //businessName = $('#id-txtBusiessName').val();
        businessName = value;
        if (businessName) {
            businessName = businessName.replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim();
            $('#Executor_gridList table tbody').find('tr').each(function myfunction(i, ele) {
                var $tds = $(this).find('td'),
                    type = $tds.eq(1).text().toLowerCase(),
                entityName = $tds.eq(2).text().replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim(),
                firstName = $tds.eq(3).text(),
                lastName = $tds.eq(4).text();
                fullName = firstName + '' + lastName;
                fullName = fullName.replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim();
                if (entityName != "" && type == "entity") {
                    if (entityName == businessName)
                        return result = true;
                    else
                        return result = false;
                }
                else if (firstName != "" && lastName != "") {
                    if (fullName == businessName) {
                        return result = true;
                    }
                    else {
                        return result = false;
                    }
                }
            });
        }
        else
            return result = false;

        return result;
    }

    function validateGeneralPartnerWithEntityName(value) {
        var entityName = '';
        var firstName = '';
        var lastName = '';
        var fullName = '';
        var businessName = '';
        var result = '';
        var type = '';
        //businessName = $('#id-txtBusiessName').val();
        businessName = value;
        if (businessName) {
            businessName = businessName.replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim();
            $('#GeneralPartner_gridList table tbody').find('tr').each(function myfunction(i, ele) {
                var $tds = $(this).find('td'),
                    type = $tds.eq(1).text().toLowerCase(),
                entityName = $tds.eq(2).text().replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim(),
                firstName = $tds.eq(3).text(),
                lastName = $tds.eq(4).text();
                fullName = firstName + '' + lastName;
                fullName = fullName.replace(/ /g, '').replace(/[^a-z0-9\s]/gi, '').trim();
                if (entityName != "" && type == "entity") {
                    if (entityName == businessName)
                        return result = true;
                    else
                        return result = false;
                }
                else if (firstName != "" && lastName != "") {
                    if (fullName == businessName) {
                        return result = true;
                    }
                    else {
                        return result = false;
                    }
                }
            });
        }
        else
            return result = false;

        return result;
    }

    // This method is validate the address compnent which we check in continue button of every filing
    function nullCheckAddressCompnent(modal, component) {
        if (modal)//Checking whether Modal data is exist.
        {
            //Assigning Type of Agent to particular default agent
            if (modal.Agent) {
                modal.Agent = modal.Agent;
            }
            if (!modal.Agent) {
                if (modal.CorpAgent) {//for corporation formation filing
                    modal.Agent = modal.CorpAgent;
                }
                if (modal.LLCAgent) {//for domestic and foreign LLC
                    modal.Agent = modal.LLCAgent;
                }
                if (modal.ReinstatementAgent) {//for reinstatement
                    modal.Agent = modal.ReinstatementAgent;
                }
                if (modal.RegisteredAgent) {//for commercial listing statement && for statement of termination
                    modal.Agent = modal.RegisteredAgent;
                }
                if (modal.PrevRegisteredAgent) {//for commercial statement of change && for statement of change
                    modal.Agent = modal.PrevRegisteredAgent;

                    if (!modal.Agent.MailingAddress.StreetAddress1 && !modal.Agent.MailingAddress.isAddressComponentKeyPressed) {
                        modal.Agent.MailingAddress.StreetAddress1 = null;
                        if (component.PrevRegisteredAgentForm && component.PrevRegisteredAgentForm.businessAddress) {
                            component.PrevRegisteredAgentForm.businessAddress.StreetAddress1.$setValidity("text", true);
                        }
                    }
                    else {
                        if (component.PrevRegisteredAgentForm && component.PrevRegisteredAgentForm.businessAddress) {
                            component.PrevRegisteredAgentForm.businessAddress.StreetAddress1.$setValidity("text", false);
                        }
                    }

                    if (!modal.Agent.StreetAddress.StreetAddress1 && !modal.Agent.StreetAddress.isAddressComponentKeyPressed) {
                        modal.Agent.StreetAddress.StreetAddress1 = null;
                        if (component.PrevRegisteredAgentForm && component.PrevRegisteredAgentForm.businessAddress) {
                            component.PrevRegisteredAgentForm.businessAddress.StreetAddress1.$setValidity("text", true);
                        }
                    }
                    else {
                        if (component.PrevRegisteredAgentForm && component.PrevRegisteredAgentForm.businessAddress) {
                            component.PrevRegisteredAgentForm.businessAddress.StreetAddress1.$setValidity("text", false);
                        }
                    }
                }
            }

            //If the user had given valid data,then we will bind valid data(modal.CorrespondenceAddress.StreetAddress1?modal.CorrespondenceAddress.StreetAddress1)
            //**else
            //If there is Invalid data and user has entered long key press,then we are assing null value.(We are doing this because the method ($scope.validateMailingAddress) functionality is affecting which is presented  in address component.
            //**else
            //If there is valid data and user didn't key pressed,then we are binding actual data

            var correspondenceAddress1 = (modal.CorrespondenceAddress.StreetAddress1 ? modal.CorrespondenceAddress.StreetAddress1 : (!modal.CorrespondenceAddress.StreetAddress1 && modal.CorrespondenceAddress.isAddressComponentKeyPressed ? null : modal.CorrespondenceAddress.StreetAddress1));
            var principalOfficeStreetAddress1 = (modal.PrincipalOffice.PrincipalStreetAddress.StreetAddress1 ? modal.PrincipalOffice.PrincipalStreetAddress.StreetAddress1 : (!modal.PrincipalOffice.PrincipalStreetAddress.StreetAddress1 && modal.PrincipalOffice.PrincipalStreetAddress.isAddressComponentKeyPressed ? null : modal.PrincipalOffice.PrincipalStreetAddress.StreetAddress1));
            var principalOfficeMailingAddress1 = (modal.PrincipalOffice.PrincipalMailingAddress.StreetAddress1 ? modal.PrincipalOffice.PrincipalMailingAddress.StreetAddress1 : (!modal.PrincipalOffice.PrincipalMailingAddress.StreetAddress1 && modal.PrincipalOffice.PrincipalMailingAddress.isAddressComponentKeyPressed ? null : modal.PrincipalOffice.PrincipalMailingAddress.StreetAddress1));
            var raStreetAddress1 = (modal.Agent.StreetAddress.StreetAddress1 ? modal.Agent.StreetAddress.StreetAddress1 : (!modal.Agent.StreetAddress.StreetAddress1 && modal.Agent.StreetAddress.isAddressComponentKeyPressed ? null : modal.Agent.StreetAddress.StreetAddress1));
            var raMailingAddress1 = (modal.Agent.MailingAddress.StreetAddress1 ? modal.Agent.MailingAddress.StreetAddress1 : (!modal.Agent.MailingAddress.StreetAddress1 && modal.Agent.MailingAddress.isAddressComponentKeyPressed ? null : modal.Agent.MailingAddress.StreetAddress1));
        }

        //checking address1 data,if it is invalid then we are invoking the validation of that particular component by taking from the Filing form.
        //component = this is a form name where u can find on the begining of the filing ex : <ng-form name="amendedAnnualReportForm" class="formClass" novalidate> //[ Main Component]
        //CorrespondenceAddress/PrincipalOffice/RegisteredAgent = this is the name of the directive or component ex : <ng-form name="PrincipalOffice" class="formClass" novalidate> //[Sub Component]
        //businessAddress = this is the name of the directive or component ex:<ng-form name="businessAddress" class="formClass" novalidate> //[Sub-sub-Component]

        if (correspondenceAddress1 != null && (correspondenceAddress1.trim() == "" || correspondenceAddress1 == undefined)) {
            modal.CorrespondenceAddress.StreetAddress2 = !modal.CorrespondenceAddress.StreetAddress2 ? "" : modal.CorrespondenceAddress.StreetAddress2;
            component.CorrespondenceAddress.businessAddress.StreetAddress1.$setValidity("text", false);
        }
        else if (principalOfficeStreetAddress1 != null && (principalOfficeStreetAddress1.trim() == "" || principalOfficeStreetAddress1 == undefined)) {
            if (component.PrincipalOffice && component.PrincipalOffice.businessAddress) {
                component.PrincipalOffice.businessAddress.StreetAddress1.$setValidity("text", false);
            }
        }
        else if (principalOfficeMailingAddress1 != null && (principalOfficeMailingAddress1.trim() == "" || principalOfficeMailingAddress1 == undefined)) {

            modal.PrincipalOffice.PrincipalMailingAddress.StreetAddress2 = !modal.PrincipalOffice.PrincipalMailingAddress.StreetAddress2 ? "" : modal.PrincipalOffice.PrincipalMailingAddress.StreetAddress2;
            if (component.PrincipalOffice && component.PrincipalOffice.businessAddress) {
                component.PrincipalOffice.businessAddress.StreetAddress1.$setValidity("text", false);
            }
        }
        else if (raStreetAddress1 != null && (raStreetAddress1.trim() == "" || raStreetAddress1 == undefined)) {

            if (component.RegisteredAgent && component.RegisteredAgent.businessAddress) {
                component.RegisteredAgent.businessAddress.StreetAddress1.$setValidity("text", false);
            }

            if (component.PrevRegisteredAgentForm && component.PrevRegisteredAgentForm.businessAddress) {
                component.PrevRegisteredAgentForm.businessAddress.StreetAddress1.$setValidity("text", false);
            }
        }
        else if (raMailingAddress1 != null && (raMailingAddress1.trim() == "" || raMailingAddress1 == undefined)) {

            modal.Agent.MailingAddress.StreetAddress2 = !modal.Agent.MailingAddress.StreetAddress2 ? "" : modal.Agent.MailingAddress.StreetAddress2;

            if (component.RegisteredAgent && component.RegisteredAgent.businessAddress) {
                component.RegisteredAgent.businessAddress.StreetAddress1.$setValidity("text", false);
            }
            if (component.PrevRegisteredAgentForm && component.PrevRegisteredAgentForm.businessAddress) {
                component.PrevRegisteredAgentForm.businessAddress.StreetAddress1.$setValidity("text", false);
            }
        }
        else {
            //If all the data is perfect,then no need of any validation,So we are making all the validations as true;

            if (component) {
                if (component.CorrespondenceAddress && component.CorrespondenceAddress.businessAddress) {
                    component.CorrespondenceAddress.businessAddress.StreetAddress1.$setValidity("text", true);
                }
                if (component.PrincipalOffice && component.PrincipalOffice.businessAddress) {
                    component.PrincipalOffice.businessAddress.StreetAddress1.$setValidity("text", true);
                }
                if (component.RegisteredAgent && component.RegisteredAgent.businessAddress) {
                    component.RegisteredAgent.businessAddress.StreetAddress1.$setValidity("text", true);
                }
                if (component.PrevRegisteredAgentForm && component.PrevRegisteredAgentForm.businessAddress) {
                    component.PrevRegisteredAgentForm.businessAddress.StreetAddress1.$setValidity("text", true);
                }
            }
        }
    }

    function enableEmailOpt(modal) {
        if (!modal.LLCAgent.EmailAddress || !modal.LLCAgent.ConfirmEmailAddress || !modal.PrincipalOffice.EmailAddress || !modal.PrincipalOffice.ConfirmEmailAddress) {
            return true;
        }
        else {
            return false;
        }
    }

    function setAgentObjForAllCorpFilings(modal) {
        var agentObject = {
            EmailAddress: "",
            IsNonCommercial: false
        };

        //var agentMailingAddress = "";
        //Assigning Type of Agent to particular default agent -- 2297

        if (modal.CorpAgent) {//for corporation formation filing
            agentObject.EmailAddress = modal.CorpAgent.EmailAddress;
            agentObject.IsNonCommercial = modal.CorpAgent.IsNonCommercial;
        }
        else if (modal.LLCAgent) {//for domestic and foreign LLC
            agentObject.EmailAddress = modal.LLCAgent.EmailAddress;
            agentObject.IsNonCommercial = modal.LLCAgent.IsNonCommercial;
        }
        else if (modal.ReinstatementAgent) {//for reinstatement
            agentObject.EmailAddress = modal.ReinstatementAgent.EmailAddress;
            agentObject.IsNonCommercial = modal.ReinstatementAgent.IsNonCommercial;
        }
        else if (modal.Agent) {
            agentObject.EmailAddress = modal.Agent.EmailAddress;
            agentObject.IsNonCommercial = modal.Agent.IsNonCommercial;
        }
        else if (modal.AgentEntity) {//for statement of termination && Non Commercial statement of resignation
            agentObject.EmailAddress = modal.AgentEntity.EmailAddress;
            agentObject.IsNonCommercial = modal.AgentEntity.IsNonCommercial;
        }
        else {
            if (modal.RegisteredAgent) {//for commercial listing statement && for statement of termination
                agentObject.EmailAddress = modal.RegisteredAgent.EmailAddress;
                agentObject.IsNonCommercial = modal.RegisteredAgent.IsNonCommercial;
            }

            if (modal.PrevRegisteredAgent) {//for commercial statement of change && for statement of change
                agentObject.EmailAddress = modal.PrevRegisteredAgent.EmailAddress;
                agentObject.IsNonCommercial = modal.PrevRegisteredAgent.IsNonCommercial;
            }
        }
        return agentObject;
    }

    function isRAStreetAddressValid(address) {

        if ((address.StreetAddress1 == null || address.StreetAddress1 == undefined || address.StreetAddress1 == "")
            || (address.Zip5 == null || address.Zip5 == undefined || address.Zip5 == "")
            || (address.City == null || address.City == undefined || address.City == ""))
            return status = false;
        else
            return status = true;
    }

    function isRAMailingAddressValid() {//11/30/2018

        if ((address.StreetAddress1 == null || address.StreetAddress1 == undefined || address.StreetAddress1 == "")
            || (address.Zip5 == null || address.Zip5 == undefined || address.Zip5 == "")
            || (address.City == null || address.City == undefined || address.City == ""))
            return status = false;
        else
            return status = true;
    }

    function compareAddress(streetAdd, mailingAdd) { // to compare street & mailing address data

        if (streetAdd != undefined && mailingAdd != undefined && streetAdd != null && mailingAdd != null) {
            if (streetAdd.StreetAddress1 != mailingAdd.StreetAddress1
            || streetAdd.StreetAddress2 != mailingAdd.StreetAddress2
             || streetAdd.City != mailingAdd.City
                || streetAdd.State != mailingAdd.State
                || streetAdd.OtherState != mailingAdd.OtherState
                || streetAdd.Country != mailingAdd.Country
                || streetAdd.Zip5 != mailingAdd.Zip5
                || streetAdd.Zip4 != mailingAdd.Zip4
                || streetAdd.PostalCode != mailingAdd.PostalCode)
                return true;
            else
                return false;
        }
    }
    return service;
});

wacorpApp.filter('padLeftZeros', function () {
    return function (str, max) {
        var pad = "";
        while (pad.length < max) {
            pad += "0";
        }
        str = str.toString();
        return pad.substring(0, pad.length - str.length) + str
    };
});

wacorpApp.filter('uBIFormat', function () {
    return function (str) {
        var pad = "";
        if (str != null && str != undefined) {
            str = str.replace(/\s/g, '');
            pad = str.substring(0, 3) + ' ';
            pad = pad + str.substring(3, 6) + ' ';
            pad = pad + str.substring(6, 9);
        }
        return pad;
    };
});

wacorpApp.filter('FEINFormat', function () {
    return function (str) {
        var pad = "";
        if (str != null && str != undefined) {
            pad = str.substring(0, 2) + ' ';
            pad = pad + str.substring(2, 9);
        }

        return pad;
    };
});

//This filter is for Title Case for Business Type(ex:Foreign Limited Liability Company) 
wacorpApp.filter('businessTypeFormat', function () {
    return function (input) {
        input = input || '';
        input = input.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
        var patt = new RegExp("^Wa ");
        var res = patt.test(input);
        if (res) {
            input = input.replace(/^Wa /g, 'WA ');
        }
        return input;
    };
}),

//to remove spaces
wacorpApp.filter('removeSpace', function () {
    return function (input) {
        input = input || '';
        input = input.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
        if (input) {
            input = input.replace(/[\s]/g, '');
        }
        return input;
    };
}),

//This filter is for Title Case for Business Type(ex:Foreign Limited Liability Company) 
wacorpApp.filter('businessTypeFormatRemoveWA', function () {
    return function (input) {
        input = input || '';
        input = input.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
        var patt = new RegExp(/^Wa\s|^WA\s/g);
        var res = patt.test(input);
        if (res) {
            input = input.replace(/^Wa\s|^WA\s/g, ' ');
        }
        return input;
    };
})
wacorpApp.factory('dataService', function ($resource) {
    var serviceUrl = aPIURL.serviceUrl;             // local
    // var serviceUrl = "https://wacorpapi.pcctg.net/api";       // dev
     //var serviceUrl = "http://wacorptestapi.pcctg.net/api";   // test
    //var serviceUrl = "https://wacorppcctestapi.pcctg.net/api";   // pcc test

    //var header = "{Content-Type': 'application/json"

    return {
        userAccount: $resource('' + '/UserAccount/', {}, {
            getLogin: { method: 'POST', url: serviceUrl + "/UserAccount/GetLogin" },
            saveUserRegistration: { method: 'POST', url: serviceUrl + "/UserAccount/SaveUserRegistration" },
            updateAccount: { method: 'POST', url: serviceUrl + "/UserAccount/UpdateAccount", IsArray: false },
            resetPassword: { method: 'POST', url: serviceUrl + "/UserAccount/GetResetPassword" },
            sendUserId: { method: 'POST', url: serviceUrl + "/UserAccount/GetSendUserId" },
            resendEmail: { method: 'POST', url: serviceUrl + "/UserAccount/ResendEmailVerification" },
            verifyEmail: { method: 'POST', url: serviceUrl + "/UserAccount/EmailVerification" }

        }),
        Home: $resource('' + '/Home1/', {}, {
            getStatistics: { method: 'GET', url: serviceUrl + "/Home1/GetStatistics", IsArray: true },
        }),
        lookup: $resource('' + '/Lookup/', {}, {
           // getLookUpData: { method: 'GET', url: serviceUrl + "/Lookup/GetLookUpData?name=:name&country=:country" },
            getLookUpData: { method: 'GET', url: serviceUrl + "/Lookup/GetLookUpData?name=:name" },
        }),

        CommercialAgents: $resource('' + '/CommercialRegisteredAgents/', {}, {
            getCommercialAgentsList: { method: 'GET', url: serviceUrl + "/CommercialRegisteredAgents/GetCommercialAgentsList", IsArray: true },
        }),
    }
});
function getFileNameFromHeader(header) {
    if (!header) return null;

    var result = header.split(";")[1].trim().split("=")[1];

    return result.replace(/"/g, '');
}
wacorpApp.factory('membershipService', function membershipService(wacorpService, $http, $base64, $cookieStore, $rootScope, $window) {

    this.login = function (user, completed) {
        wacorpService.post(webservices.UserAccount.getLogin, user, completed, loginFailed);
        function loginFailed(response) {
            wacorpService.alertDialog(response.data);
        }
    }
    this.saveCredentials = function (user) {
        var membershipData = $base64.encode(user.Username + ':' + user.Password);

        $rootScope.repository = {
            loggedUser: {
                userfullname: user.FullName,
                firstname: user.FirstName,
                lastname: user.LastName,
                username: user.Username,
                membershipid: user.MemberShipID,
                authdata: membershipData,
                userid: user.ID,
                agentid: user.AgentID,
                filerTypeId: user.FilerTypeId,
                FullUserName:user.FullUserName,
                t:user.Token.AcccessToken
            }
        };

        $http.defaults.headers.common['Authorization'] = 'Basic ' + membershipData;
        $window.sessionStorage.setItem('repository', angular.toJson($rootScope.repository));
        // call session idel watch 
        $rootScope.$broadcast('SessionIdleStart');

    }
    this.removeCredentials = function () {
        $rootScope.repository = {};
        $window.sessionStorage.removeItem('repository');
        $http.defaults.headers.common.Authorization = '';
    }

    this.removeUserData = function()
    {
        $window.sessionStorage.removeItem('repository');
    }

    this.isUserLoggedIn = function () {
        return $rootScope.repository.loggedUser != null;
    }

    this.updateRepository = function () {
        $window.sessionStorage.removeItem('repository');
        $window.sessionStorage.setItem('repository', angular.toJson($rootScope.repository));
    }
    this.resetPassword = function (user, completed, failed) {
        wacorpService.post(webservices.RESET_PASSWORD, user, completed, failed);
    }

    this.sendUserId = function (user, completed, failed) {
        wacorpService.post(webservices.SEND_USERID, user, completed, failed);
    }

    // Resend email
    this.resendEmail = function () {
        wacorpService.post(webservices.resendEmail, 1, completed, failed);
    }
    // verification
    this.verifyEmail = function () {
        wacorpService.post(webservices.verifyEmail, "key", completed, failed);
    }



    return this;
});

wacorpApp.factory('lookupService', function lookupService(wacorpService, $http, $rootScope) {
    this.countriesList = function (success) {
        var config = { params: { name: 'COUNTRIES' } };
        wacorpService.get(webservices.Lookup.getLookUpData, config, success);
    };
    this.statesList = function (success) {
        var config = { params: { name: 'STATE' } };
        wacorpService.get(webservices.Lookup.getLookUpData, config, success);
    };
    this.jurisdictionsList = function (success) {
        var config = { params: { name: 'JURISDICTION' } };
        wacorpService.get(webservices.Lookup.getLookUpData, config, success);
    };
    this.businessTypesList = function (completed) {
        var config = { params: { name: 'BusinessType' } };
        wacorpService.get(webservices.LOOKUP_DATA, type, completed);
    };
    this.NaicsCodes = function (success) {
        var config = { params: { name: 'NaicsCodes' } };
        wacorpService.get(webservices.Lookup.getLookUpData, config, success);
    };

    this.NaicsCodesNonProfit = function (success) {
        var config = { params: { name: 'NAICSCODESNONPROFIT' } };
        wacorpService.get(webservices.Lookup.getLookUpData, config, success);
    };

    this.filingTypesList = function (completed, businessTypeId) {
        var config = { params: { name: 'businessfilingtype', businessTypeID: businessTypeId } };
        wacorpService.get(webservices.LOOKUP_DATA, type, completed);
    };

    this.businessStatusList = function (completed) {
        var config = { params: { name: 'BusinessStatus' } };
        wacorpService.get(webservices.LOOKUP_DATA, type, completed);
    };

    this.ItemizedServiceFeesList = function (completed) {
        var config = { params: { name: 'ItemizedServiceFees' } };
        wacorpService.get(webservices.Lookup.getLookUpData, config, completed);
    };

    this.SolicitServiceTypes = function (completed) {
        var config = { params: { name: 'CONTRIBUTIONS' } };
        wacorpService.get(webservices.CFT.getOrganizationSolicitServiceTypes, config, completed);
    };

    this.FederalTaxTypes = function (completed) {
        var config = { params: { name: 'FEDERALTAX' } };
        wacorpService.get(webservices.CFT.getFederalTaxTypes, config, completed);
    };

    this.countiesList = function (completed) {
        var config = { params: { name: 'COUNTY' } };
        wacorpService.get(webservices.CFT.getCounties, config, completed);
    };

    this.CFTStatusList = function (completed) {
        //CFTStatus
        var config = { params: { name: 'CFTPublicStatus' } };
        wacorpService.get(webservices.CFT.getCFTStatus, config, completed);
    };

    //***** Added re: CCFS TFS ticket# 3034 - KK, 9/10/2019 
    //this.TaxExStatus = function (completed) {
    //    var config = { params: { name: 'TaxExStatus' } };
    //    wacorpService.get(webservices.CFT.getCFTTaxExStatus, config, completed);
    //};

    this.trustPurposeList = function (completed) {
        var config = { params: { name: 'TRUSTPURPOSE' } };
        wacorpService.get(webservices.CFT.getTrustPurposeList, config, completed);
    };

    this.irsDocumentsList = function (completed) {
        var config = { params: { name: 'TRUSTIRSDOCUMENT' } };
        wacorpService.get(webservices.CFT.getIRSDocumentList, config, completed);
    };

    this.canShowScreenPart = function (screenPart, obj, businessTypeID) {
        if (obj != undefined)
        {
             return ($.inArray(parseInt(businessTypeID), obj.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
        }
        return false;
    };

    //this.getFormationBusinessType = function (businessTypeID) {
    //    var config = { ID: businessTypeID } ;
    //  return  wacorpService.post(webservices.Lookup.getBusinessFilingType, config);
    //};
    
    
    this.getFullAddress = function (addressData) {
        var address = {};
        address = addressData;
        var fullAddres = (address.StreetAddress1 || "") + PrependComa((address.StreetAddress2 || ""), ', ')
                        + PrependComa((address.City || ""), ', ')
                        + ((address.Country == 'USA') ? PrependComa((address.State || ""), ', ') : PrependComa((address.OtherState || ""), ', '))
                        + ((address.Country == 'USA') ? PrependComa((address.Zip5 || ""), ', ') + PrependComa((address.Zip4 || ""), "-") : PrependComa((address.PostalCode || ""), ', '))
                        + PrependComa((address.Country || ""), ', ');
        return (fullAddres == null || fullAddres == '') ? '' : fullAddres;
    };
    //Prepped comma indicator in front of a object
   function PrependComa(val, indicator) {
        return val == "" ? "" : indicator + val;
    }
    return this;
});

/**
* This page contains the list of common directives used in the application.
*/

/**
 * Directive for Zip code format
 **/
wacorpApp.directive('zipCode', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, el, atts, ngModel) {

            /* called when model is changed from the input element */
            ngModel.$parsers.unshift(function (viewValue) {

                var numbers = viewValue.replace(/\D/g, ''),
                    char = {
                        0: '',
                        5: '-',
                        6: ''
                    };
                numbers = numbers.slice(0, 9);
                viewValue = '';

                for (var i = 0; i < numbers.length; i++) {
                    viewValue += (char[i] || '') + numbers[i];
                }

                // set the input to formatted value
                el.val(viewValue);

                return viewValue;
            });

            /* called when model is changed outside of the input element */
            ngModel.$formatters.push(function (modelValue) {
                return modelValue;
            });

            /* called when the model changes, if validation fails the model value won't be assigned */
            ngModel.$validators.phone = function (modelValue, viewValue) {
                if (modelValue) {
                    return modelValue.match(/\d/g).length === 5 || modelValue.match(/\d/g).length > 5 || modelValue.match(/\d/g).length === 9;
                } else {
                    return false;
                }
            }
        }
    }
});

/**
 * Directive to validate currency
 **/
wacorpApp.directive('validatepobox', function ($q, $timeout) {
    var poBoxExists = function (value, validatepo) {
        value = angular.lowercase(value);
        var status = false;
        if (validatepo) {
            var address = new Array("po box", "pobox", "post office box", "post office", "p.o.box", "p.o. box", "p o box", "p. o. box", "po. box", "box", "p. o box", "pmb", "p.m.b", "p m b", "private mailbox", "private mail box");
            if (value != "") {

                angular.forEach(address, function (key, data) {
                    var patt = new RegExp("^(" + key + ")$|^(" + key + ")\\W|\\W(" + key + ")\\W|\\W(" + key + ")$");
                    var flg = patt.test(value);
                    if (flg) {
                        status = true;
                    }
                });
            }
        }
        return status;
    };
    return {
        restrict: "A",
        require: "ngModel",
        scope: {
            validatepo: "=",
            isAcpAddress: "="
        },
        link: function (scope, element, attributes, ngModel) {
            ngModel.$asyncValidators.pobox = function (modelValue) {
                var defer = $q.defer();
                if (scope.isAcpAddress) {
                    defer.resolve();
                    return defer.promise;
                }
                else {
                    var flag = modelValue != '' && poBoxExists(modelValue, scope.validatepo);
                    if (flag) {
                        defer.reject();
                    } else {
                        defer.resolve();
                    }
                    return defer.promise;
                }
            }
        }
    }
});

/**
 * Directive to validate currency
 **/
wacorpApp.directive('validateForeignForUbi', function ($q, $timeout) {
    var foreignExists = function (value) {
        value = angular.lowercase(value);
        var status = false;

        return status;
    };
    return {
        restrict: "A",
        require: "ngModel",
        scope: {
            validateforeign: "="
        },
        link: function (scope, element, attributes, ngModel) {
            if (scope.validateforeign) {
                ngModel.$asyncValidators.validateforeign = function (modelValue, scope) {
                    var defer = $q.defer();
                    var flag = modelValue != '' && foreignExists(modelValue);
                    if (flag) {
                        defer.reject();
                    } else {
                        defer.resolve();
                    }
                    return defer.promise;
                }
            }
        }
    };
});


wacorpApp.directive('validateaddress', function ($q, $timeout) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, element, attributes, ngModel) {
            var self = scope;
            ngModel.$validators.isvalidaddress = function (modelValue) {

                var defer = $q.defer();
                self.address.City = modelValue;
                self.getValidAddressWithnoAlerts(defer, ngModel);
                //if (flag != undefined && flag.HasErrors) {
                //    defer.resolve();
                //} else {
                //    defer.reject();
                //}
                return defer.promise;

                //$timeout(function () {

                //  }, 2000);

            }
        }
    };
});



/**
 * Directive to validate currency
 **/
wacorpApp.directive('validate', function () {
    var validations = {

        currency: /(\.((?=[^\d])|\d{2}(?![^,\d.]))|,((?=[^\d])|\d{3}(?=[^,.$])|(?=\d{1,2}[^\d]))|\$(?=.)|\d{4,}(?=,)).|[^\d,.$]|^\$/,

    };
    return {
        require: 'ngModel',

        scope: {
            validate: '@'
        },
        link: function (scope, element, attrs, modelCtrl) {
            var pattern = validations[scope.validate] || scope.validate;

            modelCtrl.$parsers.push(function (inputValue) {
                var transformedInput = inputValue.replace(pattern, '$1');

                if (transformedInput != inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }

                return transformedInput;
            });
        }
    };
});



wacorpApp.directive('numberFormat', ['$filter', '$parse', function ($filter, $parse) {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelController) {

            var decimals = 2;

            ngModelController.$parsers.push(function (data) {
                // Attempt to convert user input into a numeric type to store
                // as the model value (otherwise it will be stored as a string)
                // NOTE: Return undefined to indicate that a parse error has occurred
                //       (i.e. bad user input)
                var parsed = parseFloat(data);
                return !isNaN(parsed) ? parsed : undefined;
            });

            ngModelController.$formatters.push(function (data) {
                //convert data from model format to view format
                return $filter('number')(data, decimals); //converted
            });

            element.bind('focus', function () {
                element.val(ngModelController.$modelValue);
            });

            element.bind('blur', function () {
                // Apply formatting on the stored model value for display
                var formatted = $filter('number')(ngModelController.$modelValue, decimals);
                element.val(formatted);
            });
        }
    }
}]);

wacorpApp.directive('diHref', ['$location', '$route', function ($location, $route) {
    return function (scope, element, attrs) {
        scope.$watch('diHref', function () {
            if (attrs.diHref) {
                element.attr('href', attrs.diHref);
                element.bind('click', function (event) {
                    scope.$apply(function () {
                        if ($location.path() == attrs.diHref) {
                            $rootScope.pageReload();
                        } else {
                            $location.path(attrs.diHref);
                        }
                    });
                });
            }
        });
    }
}]);

wacorpApp.directive('realTimeCurrency', function ($filter, $locale) {
    var decimalSep = $locale.NUMBER_FORMATS.DECIMAL_SEP;
    console.log(decimalSep);
    var toNumberRegex = '/^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$/';
    var trailingZerosRegex = new RegExp('\\' + decimalSep + '0+$');
    var filterFunc = function (value) {
        return $filter('currency')(value, "");
    };
    function getCaretPosition(input) {
        if (!input) return 0;
        if (input.selectionStart !== undefined) {
            return input.selectionStart;
        } else if (document.selection) {
            // Curse you IE
            input.focus();
            var selection = document.selection.createRange();
            selection.moveStart('character', input.value ? -input.value.length : 0);
            return selection.text.length;
        }
        return 0;
    }

    function setCaretPosition(input, pos) {
        if (!input) return 0;
        if (input.offsetWidth === 0 || input.offsetHeight === 0) {
            return; // Input's hidden
        }
        if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(pos, pos);
        }
        else if (input.createTextRange) {
            // Curse you IE
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }

    function toNumber(currencyStr) {
        return parseFloat(currencyStr.replace(toNumberRegex, ''), 10);
    }

    return {
        restrict: 'A',
        require: 'ngModel',
        link: function postLink(scope, elem, attrs, modelCtrl) {
            modelCtrl.$formatters.push(filterFunc);
            modelCtrl.$parsers.push(function (newViewValue) {
                var oldModelValue = modelCtrl.$modelValue;
                var newModelValue = toNumber(newViewValue);
                modelCtrl.$viewValue = filterFunc(newModelValue);
                var pos = getCaretPosition(elem[0]);
                elem.val(modelCtrl.$viewValue);
                var newPos = pos + modelCtrl.$viewValue.length -
                                   newViewValue.length;
                if ((oldModelValue === undefined) || isNaN(oldModelValue)) {
                    newPos -= 3;
                }
                setCaretPosition(elem[0], newPos);
                return newModelValue;
            });
        }
    };
});

/* for phone number*/
wacorpApp.directive('phoneInput', function ($filter, $browser) {
    return {
        require: 'ngModel',
        link: function ($scope, $element, $attrs, ngModelCtrl) {
            var listener = function () {
                var value = $element.val().replace(/[^0-9]/g, '');
                $element.val($filter('tel')(value, false));
            };

            // This runs when we update the text field
            ngModelCtrl.$parsers.push(function (viewValue) {
                return viewValue.replace(/[^0-9]/g, '').slice(0, 10);
            });

            // This runs when the model gets updated on the scope directly and keeps our view in sync
            ngModelCtrl.$render = function () {
                $element.val($filter('tel')(ngModelCtrl.$viewValue, false));
            };

            $element.bind('change', listener);
            $element.bind('keydown', function (event) {
                var key = event.keyCode;
                // If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing.
                // This lets us support copy and paste too
                if (key == 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) {
                    return;
                }
                $browser.defer(listener); // Have to do this or changes don't get picked up properly
            });

            $element.bind('paste cut', function () {
                $browser.defer(listener);
            });
        }

    };
});

wacorpApp.filter('tel', function () {
    return function (tel) {
        if (!tel) { return ''; }

        var value = tel.toString().trim().replace(/^\+/, '');

        if (value.match(/[^0-9]/)) {
            return tel;
        }

        var country, city, number;

        switch (value.length) {
            case 1:
            case 2:
            case 3:
                city = value;
                break;

            default:
                city = value.slice(0, 3);
                number = value.slice(3);
        }

        if (number) {
            if (number.length > 3) {
                number = number.slice(0, 3) + '-' + number.slice(3, 7);
            }
            else {
                number = number;
            }

            return ("(" + city + ") " + number).trim();
        }
        else {
            return "(" + city;
        }

    };
});

/* Directives */
wacorpApp.directive('passwordMatch', [function () {
    return {
        restrict: 'A',
        scope: true,
        require: 'ngModel',
        link: function (scope, elem, attrs, control) {
            var checker = function () {
                //get the value of the first password
                var e1 = scope.$eval(attrs.ngModel);
                //get the value of the other password  
                var e2 = angular.isNullorEmpty(scope.$eval(attrs.passwordMatch)) ? "" : scope.$eval(attrs.passwordMatch);
                return e1 == e2 || e2 == "";
            };
            scope.$watch(checker, function (n) {
                //set the form control to valid if both 
                //passwords are the same, else invalid
                control.$setValidity("unique", n);
            });
        }
    };
}
]);

wacorpApp.directive('emailMatch', [function () {
    return {
        restrict: 'A',
        scope: true,
        require: 'ngModel',
        link: function (scope, elem, attrs, control) {
            var checker = function () {
                //get the value of the first password
                var e1 = scope.$eval(attrs.ngModel);
                //get the value of the other password  
                var e2 = angular.isNullorEmpty(scope.$eval(attrs.emailMatch)) ? "" : scope.$eval(attrs.emailMatch);
                return (angular.isNullorEmpty(e1) && angular.isNullorEmpty(e2)) || (e1 != null && (e1.toLowerCase() == e2.toLowerCase() || e2.toLowerCase() == ""));
            };
            scope.$watch(checker, function (n) {
                //set the form control to valid if both 
                //passwords are the same, else invalid
                control.$setValidity("unique", n);
            });
        }
    };
}
]);

wacorpApp.directive('validatePassword', [
  function () {
      return {
          restrict: 'A',
          scope: true,
          require: 'ngModel',
          link: function (scope, elem, attrs, control) {
              var checker = function () {
                  var password = angular.isNullorEmpty(scope.$eval(attrs.ngModel)) ? "" : scope.$eval(attrs.ngModel);
                  var username = angular.isNullorEmpty(scope.$eval(attrs.validatePassword)) ? "" : scope.$eval(attrs.validatePassword);
                  var re = /^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])|(?=.*[a-z])(?=.*[A-Z])(?=.*?[#?!@@$%^&*-])|(?=.*[a-z])(?=.*[0-9])(?=.*?[#?!@@$%^&*-])(?=.*[A-Z])(?=.*[0-9])(?=.*?[#?!@@$%^&*-])).{10,30}$/
                  //var re = /^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])|(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&\/=?_.,:;\\-])|(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%&\/=?_.,:;\\-])|(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%&\/=?_.,:;\\-])).{8,}$/;
                  var result = re.test(password)
                  var pwd = password.toLowerCase();
                  var User = username.toLowerCase();
                  var index = pwd.indexOf(User);
                  if (index >= 0) {
                      control.$setValidity("uidpwddiff", false);
                      control.$setValidity("validatepassword", true);
                  }
                  else if (!result) {
                      control.$setValidity("uidpwddiff", true);
                      control.$setValidity("validatepassword", false);
                  }
                  else if (!result) {
                      control.$setValidity("uidpwddiff", true);
                      control.$setValidity("validatepassword", false);
                  }
                  else {
                      control.$setValidity("uidpwddiff", true);
                      control.$setValidity("validatepassword", true);
                  }
                  //return result || password === undefined || index<=0;
              };
              scope.$watch(checker, function (n) {
                  //control.$setValidity("validatepassword", n);
              });
          }
      };
  }
]);

wacorpApp.directive('numValidation', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, el, atts, ngModel) {
            /* called when model is changed from the input element */
            ngModel.$parsers.unshift(function (viewValue) {
                var param = scope.$eval(atts.numValidation);
                var numbers = viewValue.replace(/\D/g, ''),
                numbers = numbers.slice(0, param);
                viewValue = numbers;
                // set the input to formatted value
                el.val(viewValue);

                return viewValue;
            });

            /* called when model is changed outside of the input element */
            ngModel.$formatters.push(function (modelValue) {
                return modelValue;
            });

            /* called when the model changes, if validation fails the model value won't be assigned */
            ngModel.$validators.phone = function (modelValue, viewValue, numValidation) {
                if (modelValue) {
                    return modelValue.match(/\d/g).length.toString() === atts.numValidation;
                } else {
                    return false;
                }
            }
        }
    }
});


wacorpApp.directive('capitalize', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            var capitalize = function (inputValue) {
                if (inputValue == undefined) inputValue = '';
                var capitalized = inputValue.toUpperCase();
                if (capitalized !== inputValue) {
                    modelCtrl.$setViewValue(capitalized);
                    modelCtrl.$render();
                }
                return capitalized;
            }
            modelCtrl.$parsers.push(capitalize);
            capitalize(scope[attrs.ngModel]); // capitalize initial value
        }
    };
});


wacorpApp.directive('validNumber', function () {
    return {
        require: 'ngModel',
        restrict: "A",
        compile: function (tElement, tAttrs) {
            return function (scope, element, attrs) {
                // I handle key events
                element.bind("keypress", function (event) {
                    var key = event.key;
                    var keyCode = event.which || event.keyCode; // I safely get the keyCode pressed from the event.
                    if (!(keyCode == 8 || keyCode == 46 || keyCode == 37 || keyCode == 39 || keyCode == 9)) {
                        var keyCodeChar = String.fromCharCode(keyCode); // I determine the char from the keyCode.

                        // If the keyCode char does not match the allowed Regex Pattern, then don't allow the input into the field.
                        if (keyCodeChar && !keyCodeChar.match(new RegExp("[0-9]", "i")) && !event.ctrlKey) {
                            event.preventDefault();
                            return false;
                        }
                    }
                    else {
                        if (keyCode == 8 || keyCode == 46 || key == "ArrowLeft" || key == "ArrowRight")//allow back space to clear the text
                        {
                            var keyCodeChar = String.fromCharCode(keyCode); // I determine the char from the keyCode.
                            if (angular.isNumber(keyCodeChar)) {
                                if (keyCodeChar && !keyCodeChar.match(new RegExp("[0-9]", "i"))) {

                                    event.preventDefault();
                                    return false;
                                }
                            }
                        }
                        else {
                            if (key == "Tab")
                            { }
                            else {
                                event.preventDefault();
                                return false;
                            }
                        }
                    }
                });
            };
        }
    };
});

wacorpApp.directive('validDecimalNumber', ['$filter', '$parse', function ($filter, $parse) {
    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 != null ? val.replace(/[^-0-9\.]/g, '') : "";
                var negativeCheck = clean.split('-');
                var decimalCheck = clean.split('.');
                if (!angular.isUndefined(negativeCheck[1])) {
                    negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
                    clean = negativeCheck[0] + '-' + negativeCheck[1];
                    if (negativeCheck[0].length > 0) {
                        clean = negativeCheck[0];
                    }
                }

                if (!angular.isUndefined(decimalCheck[1])) {
                    decimalCheck[1] = decimalCheck[1].slice(0, 2);
                    clean = decimalCheck[0] + '.' + decimalCheck[1];
                }
                if (val !== clean) {
                    ngModelCtrl.$setViewValue(clean);
                    ngModelCtrl.$render();
                }
                return clean;
            });

            element.bind('keypress', function (event) {
                if (event.keyCode === 32) {
                    event.preventDefault();
                }
            });
            element.bind('blur', function () {
                var decimals = 2;
                // Apply formatting on the stored model value for display
                var formatted = $filter('number')(ngModelCtrl.$modelValue, decimals);
                element.val(formatted);
                ngModelCtrl.$setViewValue(formatted);
                scope.$apply();
            });
        }
    };
}]);


wacorpApp.directive("moveNextOnMaxlength", function () {
    return {
        restrict: "A",
        link: function ($scope, element) {
            element.on("input", function (e) {
                if (element.val().length == element.attr("maxlength")) {
                    var $nextElement = element.next();
                    if ($nextElement.length) {
                        $nextElement[0].focus();
                    }
                }
            });
        }
    }
});


wacorpApp.directive('validateUserid', [
  function () {
      return {
          restrict: 'A',
          scope: true,
          require: 'ngModel',
          link: function (scope, elem, attrs, control) {
              var checker = function () {
                  var userid = scope.$eval(attrs.ngModel);
                  var re = /^\w*([a-zA-Z0-9@\-_\.]){1,32}$/
                  var result = re.test(userid)
                  return result || userid === undefined;
              };
              scope.$watch(checker, function (n) {
                  control.$setValidity("validateuserid", n);
              });
          }
      };
  }


]);

wacorpApp.directive('allowPattern', [allowPatternDirective]);

function allowPatternDirective() {

    return {
        restrict: "A",
        compile: function (tElement, tAttrs) {
            return function (scope, element, attrs) {
                // I handle key events
                element.bind("keypress", function (event) {
                    var keyCode = event.which || event.keyCode; // I safely get the keyCode pressed from the event.
                    var keyCodeChar = String.fromCharCode(keyCode); // I determine the char from the keyCode.

                    // If the keyCode char does not match the allowed Regex Pattern, then don't allow the input into the field.
                    if (!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))) {
                        event.preventDefault();
                        return false;
                    }

                });
            };
        }
    };
}

wacorpApp.directive('customDatepicker', function ($compile, $timeout) {
    return {
        replace: true,
        templateUrl: 'custom-datepicker.html',
        scope: {
            ngModel: '=',
            dateOptions: '@',
            dateDisabled: '@',
            opened: '=',
            min: '@',
            max: '@',
            popup: '@',
            options: '@',
            name: '@',
            id: '@'
        },
        link: function ($scope, $element, $attrs, $controller) {

        }
    };
});

wacorpApp.directive("loader", function ($rootScope) {
    return function ($scope, element, attrs) {
        $scope.$on("loader_show", function () {
            return element.show();
        });
        return $scope.$on("loader_hide", function () {
            return element.hide();
        });
    };
});


wacorpApp.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    }
});
wacorpApp.factory('focus', function ($timeout, $window) {
    return function (id) {
        // timeout makes sure that it is invoked after any other event has been triggered.
        // e.g. click events that need to run before the focus or
        // inputs elements that are in a disabled state but are enabled when those events
        // are triggered.
        $timeout(function () {
            var element = $window.document.getElementById(id);
            if (element)
                element.focus();
        });
    };
});
wacorpApp.directive('eventFocus', function (focus) {
    return function (scope, elem, attr) {
        elem.on(attr.eventFocus, function () {
            focus(attr.eventFocus);
        });
        // Removes bound events in the element itself
        // when the scope is destroyed
        scope.$on('$destroy', function () {
            elem.off(attr.eventFocus);
        });
    };
});


// custom calendar
wacorpApp.directive('dateCalender', function ($parse, $filter) {
    return {
        restrict: 'A',
        scope: {
            ngModel: "="
        },
        replace: false,
        link: function (scope, elem, attr) {
            var input = $(elem);
            $(elem).attr("maxlength", "10");

            function slahes(e) {
                var selector = '#' + e.id;
                if (e.keyCode != 8) {
                    if ($(selector).val() != null && $(selector).val() != undefined && $(selector).val().length == 2) {
                        $(selector).val($(selector).val() + "/");
                    } else if ($(selector).val() != null && $(selector).val() != undefined && $(selector).val().length == 5) {
                        $(selector).val($(selector).val() + "/");
                    }
                }
            }

            // Set defaults
            $.fn.datepicker.defaults = {
                autoclose: true,
                format: "mm/dd/yyyy",
                startDate: new Date("01/01/1753"),
                endDate: new Date("12/31/9999")
            };

            // For date 

            $(elem).datepicker({
                autoclose: true,
                startDate: input.attr("data-start-date") || input.attr("start-date") || $.fn.datepicker.defaults.startDate,
                endDate: input.attr("data-end-date") || input.attr("end-date") || $.fn.datepicker.defaults.endDate
            });

            if (scope.ngModel) {
                var fdate = $filter('date')(scope.ngModel, 'MM/dd/yyyy');
                $(elem).datepicker('update', fdate);
            }

            elem.bind("keypress", function (e) {
                e = e || window.event;
                var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
                var charStr = String.fromCharCode(charCode);
                var keyCode = event.which || event.keyCode;
                
                if (/\d/.test(charStr)) {
                    slahes(this);
                }
                else if (!/\//.test(charStr)) {
                    if (!(keyCode == 8 || keyCode == 46 || keyCode == 37 || keyCode == 39 || keyCode == 9)) {
                        if (keyCode == 97)
                        { }
                    }
                    else if (e.key == "Delete" || e.key == "Del") {
                        //this.value="";
                    }
                    else if (e.key != "Tab" && charCode != "97" && e.key != "Backspace") {
                        e.preventDefault();
                    }
                }
            });
            elem.bind("blur", function (e) {
                e = e || window.event;
                var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
                var charStr = String.fromCharCode(charCode);
                var keyCode = event.which || event.keyCode;
                var data='#'+ e.currentTarget.id;
                if (data != undefined && $(data).val() != "")
                {
                    slahes(this);
                }

            });
        }
    };
});


wacorpApp.directive('passwordStrength', [
    function () {
        return {
            require: 'ngModel',
            restrict: 'E',
            scope: {
                password: '=ngModel'
            },

            link: function (scope, elem, attrs, ctrl) {
                scope.$watch('password', function (newVal) {
                    var re = /^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])|(?=.*[a-z])(?=.*[A-Z])(?=.*?[#?!@@$%^&*-])|(?=.*[a-z])(?=.*[0-9])(?=.*?[#?!@@$%^&*-])(?=.*[A-Z])(?=.*[0-9])(?=.*?[#?!@@$%^&*-])).{10,30}$/
                    var result = re.test(newVal)
                    var index = scope.username.indexOf(newVal);
                    var passwordLength = newVal == undefined ? 0 : newVal.length;
                    scope.strength = isSatisfied(passwordLength > 0) + isSatisfied(index < 0) +
                      isSatisfied(result);
                    function isSatisfied(criteria) {
                        return criteria ? 1 : 0;
                    }
                }, true);
            },
            template: '<div class="progress">' +
              '<div class="progress-bar progress-bar-danger" style="width: {{strength >= 1 ? 25 : 0}}%"></div>' +
              '<div class="progress-bar progress-bar-warning" style="width: {{strength >= 2 ? 25 : 0}}%"></div>' +
              '<div class="progress-bar progress-bar-warning" style="width: {{strength >= 3 ? 25 : 0}}%"></div>' +
              '<div class="progress-bar progress-bar-success" style="width: {{strength >= 4 ? 25 : 0}}%"></div>' +
              '</div>'
        }
    }
])

wacorpApp.directive('ngMin', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elem, attr, ctrl) {
            scope.$watch(attr.ngMin, function () {
                ctrl.$setViewValue(ctrl.$viewValue);
            });
            var minValidator = function (value) {
                var min = attr.ngMin || 0;
                if (!angular.isNullorEmpty(value) && value < min) {
                    ctrl.$setValidity('ngMin', false);
                    return undefined;
                } else {
                    ctrl.$setValidity('ngMin', true);
                    return value;
                }
            };

            ctrl.$parsers.push(minValidator);
            ctrl.$formatters.push(minValidator);
        }
    };
});

wacorpApp.directive('ngMax', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elem, attr, ctrl) {
            scope.$watch(attr.ngMax, function () {
                ctrl.$setViewValue(ctrl.$viewValue);
            });
            var maxValidator = function (value) {
                var max = scope.$eval(attr.ngMax) || Infinity;
                if (!angular.isNullorEmpty(value) && value > max) {
                    ctrl.$setValidity('ngMax', false);
                    return undefined;
                } else {
                    ctrl.$setValidity('ngMax', true);
                    return value;
                }
            };

            ctrl.$parsers.push(maxValidator);
            ctrl.$formatters.push(maxValidator);
        }
    };
});
wacorpApp.directive('phoneNumber', function ($window) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, el, atts, ngModel) {
            /* called when model is changed from the input element */

            el.bind("keypress", function (event) {
                var keyCode = event.which || event.keyCode; // I safely get the keyCode pressed from the event.

                // verify browser type
                //var browsers = { chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer/i };
                //var browser = /firefox/i;
                // var userAgent = $window.navigator.userAgent;

                if (!(keyCode == 8 || keyCode == 46 || keyCode == 37 || keyCode == 39 || keyCode == 9)) {

                    var keyCodeChar = String.fromCharCode(keyCode); // I determine the char from the keyCode.

                    // If the keyCode char does not match the allowed Regex Pattern, then don't allow the input into the field.
                    if (keyCode == 97)
                    { }
                    else if (!keyCodeChar.match(new RegExp("[0-9]", "i"))) {
                        event.preventDefault();
                        return false;
                    }
                    if (event.target.value.replace(/\D/g, '').length == 10) {
                        if (keyCode != 97) {
                            event.preventDefault();
                            return false;
                        }

                    }
                }

            });

            el.bind("blur", function (event) {
                var numbers = event.target.value.replace(/\D/g, '');
                if (numbers.length < 10)
                    event.target.value = "";
            });

            ngModel.$parsers.unshift(function (viewValue) {
                viewValue = viewValue || '';
                var numbers = viewValue.replace(/\D/g, ''),
                    char = { 0: '', 3: '-', 6: '-' };
                numbers = numbers.slice(0, 10);
                viewValue = '';
                for (var i = 0; i < numbers.length; i++) {
                    viewValue += (char[i] || '') + numbers[i];
                }
                // set the input to formatted value
                el.val(viewValue);
                return viewValue;
            });

            /* called when model is changed outside of the input element */
            ngModel.$formatters.push(function (modelValue) {
                modelValue = modelValue || '';
                var numbers = modelValue.replace(/\D/g, ''),
                    char = { 0: '', 3: '-', 6: '-' };
                numbers = numbers.slice(0, 10);
                modelValue = '';
                for (var i = 0; i < numbers.length; i++) {
                    modelValue += (char[i] || '') + numbers[i];
                }
                // set the input to formatted value
                el.val(modelValue);
                return modelValue;
            });

            /* called when the model changes, if validation fails the model value won't be assigned */
            ngModel.$validators.phone = function (modelValue, viewValue) {
                var checker = true;
                if (modelValue) {
                    checker = modelValue.match(/\d/g).length == 10;
                    ngModel.$setValidity("ngphone", checker);
                } else {
                    ngModel.$setValidity("ngphone", checker);
                }
                return checker;
            }
        }
    }
});

wacorpApp.directive('ubiNumber', function ($window) {
    return {
        require: 'ngModel',
        link: function (scope, el, atts, ngModel) {
            /* called when model is changed from the input element */

            el.bind("keypress", function (event) {
                var keyCode = event.which || event.keyCode; // I safely get the keyCode pressed from the event.

                // verify browser type
                //var browsers = { chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer/i };
                //var browser = /firefox/i;
                // var userAgent = $window.navigator.userAgent;

                if (!(keyCode == 8 || keyCode == 46 || keyCode == 37 || keyCode == 39 || keyCode == 9)) {

                    var keyCodeChar = String.fromCharCode(keyCode); // I determine the char from the keyCode.

                    // If the keyCode char does not match the allowed Regex Pattern, then don't allow the input into the field.
                    if (!keyCodeChar.match(new RegExp("[0-9]", "i"))) {
                        event.preventDefault();
                        return false;
                    }
                    if (event.target.value.replace(/\D/g, '').length == 12) {
                        event.preventDefault();
                        return false;
                    }
                }

            });


            ngModel.$parsers.unshift(function (viewValue) {
                viewValue = viewValue || '';
                var numbers = viewValue.replace(/\D/g, ''),
                    char = { 3: ' ', 6: ' ' };
                numbers = numbers.slice(0, 12);
                viewValue = '';
                for (var i = 0; i < numbers.length; i++) {
                    viewValue += (char[i] || '') + numbers[i];
                }
                // set the input to formatted value
                el.val(viewValue);
                return viewValue;
            });

            /* called when model is changed outside of the input element */
            ngModel.$formatters.push(function (modelValue) {
                modelValue = modelValue || '';
                var numbers = modelValue.replace(/\D/g, ''),
                    char = { 3: ' ', 6: ' ' };
                numbers = numbers.slice(0, 12);
                modelValue = '';
                for (var i = 0; i < numbers.length; i++) {
                    modelValue += (char[i] || '') + numbers[i];
                }
                // set the input to formatted value
                el.val(modelValue);
                return modelValue;
            });

            ///* called when the model changes, if validation fails the model value won't be assigned */
            //ngModel.$validators.phone = function (modelValue, viewValue) {
            //    var checker = true;
            //    if (modelValue) {
            //        checker = modelValue.match(/\d/g).length == 9;
            //        ngModel.$setValidity("ngphone", checker);
            //    } else {
            //        ngModel.$setValidity("ngphone", checker);
            //    }
            //    return checker;
            //}
        }
    }
});

wacorpApp.directive('feinNumber', function ($window) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, el, atts, ngModel) {
            /* called when model is changed from the input element */

            el.bind("keypress", function (event) {
                var keyCode = event.which || event.keyCode; // I safely get the keyCode pressed from the event.

                // verify browser type
                //var browsers = { chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer/i };
                //var browser = /firefox/i;
                // var userAgent = $window.navigator.userAgent;

                if (!(keyCode == 8 || keyCode == 46 || keyCode == 37 || keyCode == 39 || keyCode == 9)) {

                    var keyCodeChar = String.fromCharCode(keyCode); // I determine the char from the keyCode.

                    // If the keyCode char does not match the allowed Regex Pattern, then don't allow the input into the field.
                    if (keyCode == 97) {
                    }
                    else if (!keyCodeChar.match(new RegExp("[0-9]", "i"))) {
                        event.preventDefault();
                        return false;
                    }
                    if (event.target.value.replace(/\D/g, '').length == 9) {
                        if (keyCode != 97) {
                            event.preventDefault();
                            return false;
                        }
                    }
                }

            });

            //el.bind("blur", function (event) {
            //    var numbers = event.target.value.replace(/\D/g, '');
            //    //if (numbers.length < 9)
            //       // event.target.value = "";
            //});

            ngModel.$parsers.unshift(function (viewValue) {
                viewValue = viewValue || '';
                var numbers = viewValue.replace(/\D/g, ''),
                    char = { 0: '', 2: '-' };
                numbers = numbers.slice(0, 9);
                viewValue = '';
                for (var i = 0; i < numbers.length; i++) {
                    viewValue += (char[i] || '') + numbers[i];
                }
                // set the input to formatted value
                el.val(viewValue);
                return viewValue;
            });


        }
    }
});

wacorpApp.directive('validFile', function () {
    return {
        require: 'ngModel',
        link: function (scope, el, attrs, ngModel) {
            //change event is fired when file is selected
            el.bind('change', function () {
                scope.$apply(function () {
                    ngModel.$setViewValue(el.val());
                    ngModel.$render();
                });
            });
        }
    }
});

wacorpApp.directive('convertToNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function (val) {
                return parseInt(val, 10);
            });
            ngModel.$formatters.push(function (val) {
                return '' + val;
            });
        }
    };
});
wacorpApp.directive('downloadFile', function ($compile, $window, wacorpService, $rootScope) {
    return {
        restrict: 'A',
        replace: false,
        //template: '<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>',
        scope: {
            params: "=",
            filename: "="
        },
        link: function (scope, element, attr) {
            var isClickable = angular.isDefined(attr.ngClick);
            if (!isClickable) {
                attr.$set('ngClick', 'downloadPdf()');
                $compile(element)(scope);
            }

            // When the download starts, disable the link
            //scope.$on('download-start', function () {});

            // When the download finishes, attach the data to the link. Enable the link and change its appearance.
            //scope.$on('downloaded', function (event, data) {

            //});
        },
        controller: ['$scope', '$attrs', '$http', function ($scope, $attrs, $http) {
            $scope.downloadPdf = function () {
                var params = $scope.params;
                //$scope.$emit('download-start');
                var url = baseUrl + $attrs.url;

                if ($rootScope.repository.loggedUser != undefined)
                    $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                $http({
                    method: "POST",
                    url: url,
                    data: params,
                    headers: {
                        accept: 'application/octet-stream' //or whatever you need
                    },
                    responseType: 'arraybuffer',
                    cache: false,
                    transformResponse: function (data, headers) {
                        headers = headers();
                        if (headers['content-type'] == undefined || headers['content-type'] != 'application/octet-stream') {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog("File Not Found");
                        }
                        else {
                            var file = new Blob([data], {
                                type: 'application/octet-stream' //or whatever you need, should match the 'accept headers' above
                            });
                            //if (headers['content-disposition'] == null || headers['content-disposition'] == undefined) {
                            //    alert("File cannot found in the system");
                            //}
                            //else {
                            //    if ($scope.params.Filename == undefined)
                            //    saveAs(file, headers['content-disposition'].replace(/attachment; filename=/g, ''));
                            //else

                            saveAs(file, $scope.params.FileName || $scope.filename);
                            //}
                        }
                    },
                })
                .then(function (result) {

                }, function (error) {

                });
            };
        }]
    }
});

wacorpApp.directive('focusElement', function ($timeout, $parse) {
    return {
        link: function (scope, element, attrs) {
            var model = $parse(attrs.focusMe);
            scope.$watch(model, function (value) {
                if (value === true) {
                    $timeout(function () { element[0].focus(); });
                }
            });
            element.bind('blur', function () {
                scope.$apply(model.assign(scope, false));
            });
        }
    };
});

wacorpApp.directive('focusName', function () {
    return {
        restrict: 'A',
        link: function ($scope, element, attributes) {
            $scope.focusRegistry = $scope.focusRegistry || {};
            $scope.focusRegistry[attributes.focusName] = element[0];
        }
    }
});

wacorpApp.directive('nextFocus', function () {
    return {
        restrict: 'A',
        link: function ($scope, element, attributes) {
            element.bind('keydown keypress', function (event) {
                if (event.which === 9) { // Tab
                    var focusElement = $scope.focusRegistry[attributes.nextFocus];
                    if (focusElement) {
                        if (!focusElement.hidden && !focusElement.disabled) {
                            focusElement.focus();
                            event.preventDefault();
                            return;
                        }
                    }
                    console.log('Unable to focus on target: ' + attributes.nextFocus);
                }
            });
        }
    }
});

wacorpApp.directive('dateValidation', [function () {
    return {
        restrict: 'A',
        scope: true,
        require: 'ngModel',
        link: function (scope, elem, attrs, control) {
            var checker = function () {
                var isDateValid = true;
                //get the value of the first date
                var dtEnd = scope.$eval(attrs.ngModel);
                //get the value of the second dtae password  
                var dtStart = angular.isNullorEmpty(scope.$eval(attrs.dateValidation)) ? "" : scope.$eval(attrs.dateValidation);
                if (!angular.isNullorEmpty(dtEnd) && !angular.isNullorEmpty(dtStart) && new Date(dtEnd) < new Date(dtStart))
                    isDateValid = false;
                return isDateValid;
            };
            scope.$watch(checker, function (n) {
                //set the form control to valid if both 
                //passwords are the same, else invalid
                control.$setValidity("validdate", n);
            });
        }
    };
}
]);

///Not allowed even Paste charactors
wacorpApp.directive('numericOnly', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {

            modelCtrl.$parsers.push(function (inputValue) {
                var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g, '') : null;

                if (transformedInput != inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }

                return transformedInput;
            });
        }
    };
});

///Allows only alpha numeric value
wacorpApp.directive('alphaNumeric', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {

            modelCtrl.$parsers.push(function (inputValue) {
                var transformedInput = inputValue ? inputValue.replace(/[^a-z0-9\s]/gi, '') : null;

                if (transformedInput != inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }

                return transformedInput;
            });
        }
    };
});

wacorpApp.directive('roundDeci', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elem, attrs, ngModelCtrl) {
            function roundNumber(val) {
                var parsed = parseFloat(val, 10);
                if (parsed !== parsed) { return null; } // check for NaN
                var rounded = Math.round(parsed);
                return rounded;
            }
            ngModelCtrl.$parsers.push(roundNumber); // Parsers take the view value and convert it to a model value.
        }
    };
});

wacorpApp.directive('resrictpasswordspace', function () {
    return {
        restrict: 'A',

        link: function ($scope, $element) {
            $element.bind('input', function () {
                $(this).val($(this).val().replace(/ /g, ''));
            });
        }
    };
});
wacorpApp.directive('multiSelectDropdown', ['$filter', '$document', '$compile', '$parse',
 function ($filter, $document, $compile, $parse) {
     return {
         restrict: 'AE',
         scope: {
             selectedModel: '=?selectedModel',
             options: '=?options',
             settings: '=?settings',
         },
         template: function (element, attrs) {
             var template = '<div class="{{settings.width}}">';
             template += '<div class="row"><div class="form-control input-medium" ng-click="toggleDropdown()"><i class="fa fa-chevron-down pull-right" aria-hidden="true"></i><label ng-show="selectedModel.length==1||selectedModel.length==options.length">{{text}}</label><label ng-show="selectedModel.length>0">{{selectedModel.length}} item(s) selected</label><label ng-show="selectedModel.length==0">--Select--</label></div></div>';
             template += '<ul class="dropdown-menu col-xs-12" ng-style="{display: open ? \'block\' : \'none\', height : settings.scrollable ? settings.scrollableHeight : \'auto\' }" style="overflow-y: scroll" >';
             template += '<li class="dropdown-header" ng-if="settings.selectall"><input type="checkbox" class="myChkbox" ng-click="selectAll(isAllChecked)" ng-model="isAllChecked"/>&nbsp;SELECT ALL</li>';
             template += '<li class="divider" ng-if="settings.selectall"></li>';
             template += '<li ng-repeat="option in options">';
             template += '<a ng-click="setSelectedItem(getPropertyForObject(option))">';
             template += '<div class="checkbox"><label><input type="checkbox" ng-click="checkboxClick($event, getPropertyForObject(option))" ng-checked="isChecked(getPropertyForObject(option))" />{{getPropertyForObject(option,settings.key)}}</label></div></a>';
             template += '</li></ul></div>';
             element.html(template);
         },

         link: function ($scope, $element, $attrs) {

             //Initialize the drop down attributes with default values
             var settingScope = { scrollableHeight: settings.SCROLLHEIGHT, scrollable: true, key: settings.KEY, value: settings.VALUE, isKeyList: false, width: 'multiselect-parent col-md-5', selectall: true };
             $scope.settings = $scope.settings ? angular.extend(settingScope, $scope.settings) : angular.copy(settingScope);
             $scope.selectedModel = $scope.selectedModel || [];
             $scope.options = $scope.options || [];
             $scope.text = '';

             //Get Current drop down element
             var $dropdownTrigger = $element.children()[constant.ZERO];

             //Open the drop down on drop down click
             $scope.toggleDropdown = function () {
                 $scope.open = !$scope.open;
             };

             //Close the drop down on clicking on document
             $document.on('click', function (e) {
                 var target = e.target.parentElement;
                 var parentFound = false;
                 while (angular.isDefined(target) && target != null && !parentFound) {
                     if (_.contains(target.className.split(' '), 'multiselect-parent') && !parentFound) {
                         if (target == $dropdownTrigger)
                             parentFound = true;
                     }
                     target = target.parentElement;
                 }
                 if (!parentFound) {
                     $scope.$apply(function () { $scope.open = false; });
                 }
             });

             //Select and un select all options
             $scope.selectAll = function (isAllChecked) {
                 var items = Array.isArray($scope.selectedModel);
                 if (!items) { $scope.selectedModel = $scope.selectedModel.split(","); }
                 $scope.selectedModel.splice(constant.ZERO, $scope.selectedModel.length);
                 if (isAllChecked) {
                     if ($scope.settings.isKeyList) {
                         angular.forEach($scope.options, function (value) {
                             $scope.setSelectedItem(value[$scope.settings.key], true); // setSelectedItem method is available in this file only.
                         });
                     }
                     else {
                         angular.forEach($scope.options, function (value) {
                             $scope.setSelectedItem(value[$scope.settings.value], true);  // setSelectedItem method is available in this file only.
                         });
                     }
                 }
             };

             //get selected Item in to a list
             $scope.setSelectedItem = function (id, dontRemove) {
                 var items = Array.isArray($scope.selectedModel);
                 if (!items) { $scope.selectedModel = $scope.selectedModel.split(","); }
                 //var findObj = {};
                 //findObj[$scope.settings.value] = id;
                 dontRemove = dontRemove || false;
                 var exists = $scope.selectedModel.indexOf(id) != constant.NEGATIVE;//var exists = _.findIndex($scope.selectedModel, findObj) != -1;
                 if (!dontRemove && exists) {
                     $scope.selectedModel.splice($scope.selectedModel.indexOf(id), constant.ONE);//$scope.selectedModel.splice(_.findIndex($scope.selectedModel, findObj), 1);
                     angular.noop(id);//angular.noop(findObj);
                 } else if (!exists) {
                     $scope.selectedModel.push(id);//$scope.selectedModel.push(findObj);
                     angular.noop(id);//angular.noop(findObj);
                 }
                 $scope.isAllChecked = $scope.options.length == $scope.selectedModel.length;
                 if ($scope.isAllChecked) {
                     $scope.text = 'All ';
                 }
                 else if ($scope.selectedModel.length == constant.ZERO) {
                     var text = "";
                     angular.forEach($scope.options, function (option) {
                         if (option.Key == $scope.selectedModel)
                             text = option.Value;
                     });
                     if (text == "") {
                         if ($scope.options[$scope.selectedModel - constant.ONE] != undefined)
                             text = $scope.options[$scope.selectedModel - constant.ONE].Value;
                     }


                     $scope.text = text;
                 }
             };

             //Clear the selected properties of drop down object
             function clearObject(object) {
                 for (var prop in object) {
                     delete object[prop];
                 }
             }

             //Click on dropdown check boxes
             $scope.checkboxClick = function ($event, id) {
                 $scope.setSelectedItem(id);  // setSelectedItem method is available in this file only.
                 $event.stopImmediatePropagation();
             };

             $scope.getPropertyForObject = function (object, property) {
                 property = property || $scope.settings.isKeyList ? $scope.settings.key : $scope.settings.value;
                 return angular.isDefined(object) && object.hasOwnProperty(property) ? object[property] : '';
             };

             $scope.isChecked = function (id) {
                 //var findObj = {};
                 //findObj[$scope.settings.value] = id;
                 //return _.findIndex($scope.selectedModel, findObj) != -1;
                 var items = Array.isArray($scope.selectedModel);
                 if (!items) { $scope.selectedModel = $scope.selectedModel.split(","); }

                 $scope.isAllChecked = $scope.options.length == $scope.selectedModel.length;
                 return $scope.selectedModel.indexOf(id) != constant.NEGATIVE;
             };
         }
     };
 }]);
angular.module('autoComplete', [])

    .run(["$templateCache", function ($templateCache) {
        $templateCache.put("autoComplete-match.html",
          "<a tabindex=\"-1\" bind-html=\"match.label | autoCompleteHighlight:query\"></a>");
    }])

    .run(["$templateCache", function ($templateCache) {
        $templateCache.put("autoComplete-popup.html",
          "<ul class=\"dropdown-menu\" ng-style=\"{display: isOpen()&&'block' || 'none', top: position.top+'px', left: position.left+'px'}\">\n" +
          "    <li ng-repeat=\"match in matches\" ng-class=\"{active: isActive($index) }\" ng-mouseenter=\"selectActive($index)\" ng-click=\"selectMatch($index)\">\n" +
          "        <div auto-complete-match index=\"$index\" match=\"match\" query=\"query\" template-url=\"templateUrl\"></div>\n" +
          "    </li>\n" +
          "</ul>");
    }])

    .directive('bindHtml', function () {
        return function (scope, element, attr) {
            element.addClass('ng-binding').data('$binding', attr.bindHtml);
            scope.$watch(attr.bindHtml, function bindHtmlWatchAction(value) {
                element.html(value || '');
            });
        };
    })

    .factory('$position', ['$document', '$window', function ($document, $window) {
        function getStyle(el, cssprop) {
            if (el.currentStyle) { //IE
                return el.currentStyle[cssprop];
            } else if ($window.getComputedStyle) {
                return $window.getComputedStyle(el)[cssprop];
            }
            // finally try and get inline style
            return el.style[cssprop];
        }
        function isStaticPositioned(element) { //Checks if a given element is statically positioned and @param element - raw DOM element
            return (getStyle(element, "position") || 'static') === 'static';
        }
        var parentOffsetEl = function (element) {  //returns the closest, non-statically positioned parentOffset of a given element @param element
            var docDomEl = $document[0];
            var offsetParent = element.offsetParent || docDomEl;
            while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent)) {
                offsetParent = offsetParent.offsetParent;
            }
            return offsetParent || docDomEl;
        };

        return {
            position: function (element) {
                var elBCR = this.offset(element);
                var offsetParentBCR = { top: 0, left: 0 };
                var offsetParentEl = parentOffsetEl(element[0]);
                if (offsetParentEl != $document[0]) {
                    offsetParentBCR = this.offset(angular.element(offsetParentEl));
                    offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
                    offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
                }

                var boundingClientRect = element[0].getBoundingClientRect();
                return {
                    width: boundingClientRect.width || element.prop('offsetWidth'),
                    height: boundingClientRect.height || element.prop('offsetHeight'),
                    top: elBCR.top - offsetParentBCR.top,
                    left: elBCR.left - offsetParentBCR.left
                };
            },
            offset: function (element) {
                var boundingClientRect = element[0].getBoundingClientRect();
                return {
                    width: boundingClientRect.width || element.prop('offsetWidth'),
                    height: boundingClientRect.height || element.prop('offsetHeight'),
                    top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop),
                    left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft)
                };
            }
        };
    }])

    .factory('autoCompleteParser', ['$parse', function ($parse) {
        var AUTOCOMPLETE_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+(.*)$/;
        return {
            parse: function (input) {
                var match = input.match(AUTOCOMPLETE_REGEXP), modelMapper, viewMapper, source;
                if (!match) {
                    throw new Error(
                      "Expected auto Complete specification in form of '_modelValue_ (as _label_)? for _item_ in _collection_'" +
                        " but got '" + input + "'.");
                }
                return {
                    itemName: match[3],
                    source: $parse(match[4]),
                    viewMapper: $parse(match[2] || match[1]),
                    modelMapper: $parse(match[1])
                };
            }
        };
    }])

    .directive('autoComplete', ['$compile', '$parse', '$q', '$timeout', '$document', '$position', 'autoCompleteParser',
    function ($compile, $parse, $q, $timeout, $document, $position, autoCompleteParser) {
        var HOT_KEYS = [9, 13, 27, 38, 40];
        return {
            require: 'ngModel',
            link: function (originalScope, element, attrs, modelCtrl) {

                //SUPPORTED ATTRIBUTES (OPTIONS)

                //minimal no of characters that needs to be entered before auto Complete kicks-in
                var minSearch = originalScope.$eval(attrs.autoCompleteMinLength) || 1;

                //minimal wait time after last character typed before auto Complete kicks-in
                var waitTime = originalScope.$eval(attrs.autoCompleteWaitMs) || 0;

                //should it restrict model values to the ones selected from the popup only?
                var isEditable = originalScope.$eval(attrs.autoCompleteEditable) !== false;

                //binding to a variable that indicates if matches are being retrieved asynchronously
                var isLoadingSetter = $parse(attrs.autoCompleteLoading).assign || angular.noop;

                //a callback executed when a match is selected
                var onSelectCallback = $parse(attrs.autoCompleteOnSelect);

                var inputFormatter = attrs.autoCompleteInputFormatter ? $parse(attrs.autoCompleteInputFormatter) : undefined;

                var appendToBody = attrs.autoCompleteAppendToBody ? $parse(attrs.autoCompleteAppendToBody) : false;

                //INTERNAL VARIABLES

                //model setter executed upon match selection
                var $setModelValue = $parse(attrs.ngModel).assign;

                //expressions used by auto Complete
                var parserResult = autoCompleteParser.parse(attrs.autoComplete);

                var hasFocus;

                //pop-up element used to display matches
                var popUpEl = angular.element('<div auto-complete-popup></div>');
                popUpEl.attr({
                    matches: 'matches',
                    active: 'activeIdx',
                    select: 'select(activeIdx)',
                    query: 'query',
                    position: 'position'
                });
                //custom item template
                if (angular.isDefined(attrs.autoCompleteTemplateUrl)) {
                    popUpEl.attr('template-url', attrs.autoCompleteTemplateUrl);
                }

                //create a child scope for the auto Complete directive so we are not polluting original scope
                //with autoComplete-specific data (matches, query etc.)
                var scope = originalScope.$new();
                originalScope.$on('$destroy', function () {
                    scope.$destroy();
                });

                var resetMatches = function () {
                    scope.matches = [];
                    scope.activeIdx = -1;
                };

                var getMatchesAsync = function (inputValue) {

                    var locals = { $viewValue: inputValue };
                    isLoadingSetter(originalScope, true);
                    $q.when(parserResult.source(originalScope, locals)).then(function (matches) {

                        //it might happen that several async queries were in progress if a user were typing fast
                        //but we are interested only in responses that correspond to the current view value
                        if (inputValue === modelCtrl.$viewValue && hasFocus) {
                            if (matches.length > 0) {

                                scope.activeIdx = 0;
                                scope.matches.length = 0;

                                //transform labels
                                for (var i = 0; i < matches.length; i++) {
                                    locals[parserResult.itemName] = matches[i];
                                    scope.matches.push({
                                        label: parserResult.viewMapper(scope, locals),
                                        model: matches[i]
                                    });
                                }

                                scope.query = inputValue;
                                //position pop-up with matches - we need to re-calculate its position each time we are opening a window
                                //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
                                //due to other elements being rendered
                                scope.position = appendToBody ? $position.offset(element) : $position.position(element);
                                scope.position.top = scope.position.top + element.prop('offsetHeight');

                            } else {
                                resetMatches();
                            }
                            isLoadingSetter(originalScope, false);
                        }
                    }, function () {
                        resetMatches();
                        isLoadingSetter(originalScope, false);
                    });
                };

                resetMatches();

                //we need to propagate user's query so we can higlight matches
                scope.query = undefined;

                //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later 
                var timeoutPromise;

                //plug into $parsers pipeline to open a auto Complete on view changes initiated from DOM
                //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
                modelCtrl.$parsers.unshift(function (inputValue) {

                    hasFocus = true;

                    if (inputValue && inputValue.length >= minSearch) {
                        if (waitTime > 0) {
                            if (timeoutPromise) {
                                $timeout.cancel(timeoutPromise);//cancel previous timeout
                            }
                            timeoutPromise = $timeout(function () {
                                getMatchesAsync(inputValue);
                            }, waitTime);
                        } else {
                            getMatchesAsync(inputValue);
                        }
                    } else {
                        isLoadingSetter(originalScope, false);
                        resetMatches();
                    }

                    if (isEditable) {
                        return inputValue;
                    } else {
                        if (!inputValue) {
                            // Reset in case user had typed something previously.
                            modelCtrl.$setValidity('editable', true);
                            return inputValue;
                        } else {
                            modelCtrl.$setValidity('editable', false);
                            return undefined;
                        }
                    }
                });

                modelCtrl.$formatters.push(function (modelValue) {

                    var candidateViewValue, emptyViewValue;
                    var locals = {};

                    if (inputFormatter) {

                        locals['$model'] = modelValue;
                        return inputFormatter(originalScope, locals);

                    } else {

                        //it might happen that we don't have enough info to properly render input value
                        //we need to check for this situation and simply return model value if we can't apply custom formatting
                        locals[parserResult.itemName] = modelValue;
                        candidateViewValue = parserResult.viewMapper(originalScope, locals);
                        locals[parserResult.itemName] = undefined;
                        emptyViewValue = parserResult.viewMapper(originalScope, locals);

                        return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue;
                    }
                });

                scope.select = function (activeIdx) {
                    //called from within the $digest() cycle
                    var locals = {};
                    var model, item;

                    locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
                    model = parserResult.modelMapper(originalScope, locals);
                    $setModelValue(originalScope, model);
                    modelCtrl.$setValidity('editable', true);

                    onSelectCallback(originalScope, {
                        $item: item,
                        $model: model,
                        $label: parserResult.viewMapper(originalScope, locals)
                    });

                    resetMatches();

                    //return focus to the input element if a mach was selected via a mouse click event
                    element[0].focus();
                };

                //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
                element.bind('keydown', function (evt) {

                    //auto Complete is open and an "interesting" key was pressed
                    if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
                        return;
                    }

                    evt.preventDefault();

                    if (evt.which === 40) {
                        scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
                        scope.$digest();

                    } else if (evt.which === 38) {
                        scope.activeIdx = (scope.activeIdx ? scope.activeIdx : scope.matches.length) - 1;
                        scope.$digest();

                    } else if (evt.which === 13 || evt.which === 9) {
                        scope.$apply(function () {
                            scope.select(scope.activeIdx);
                        });

                    } else if (evt.which === 27) {
                        evt.stopPropagation();

                        resetMatches();
                        scope.$digest();
                    }
                });

                element.bind('blur', function (evt) {
                    hasFocus = false;
                });

                // Keep reference to click handler to unbind it.
                var dismissClickHandler = function (evt) {
                    if (element[0] !== evt.target) {
                        resetMatches();
                        scope.$digest();
                    }
                };

                $document.bind('click', dismissClickHandler);

                originalScope.$on('$destroy', function () {
                    $document.unbind('click', dismissClickHandler);
                });

                var $popup = $compile(popUpEl)(scope);
                if (appendToBody) {
                    $document.find('body').append($popup);
                } else {
                    element.after($popup);
                }
            }
        };
    }])

    .directive('autoCompletePopup', function () {
        return {
            restrict: 'EA',
            scope: {
                matches: '=',
                query: '=',
                active: '=',
                position: '=',
                select: '&'
            },
            replace: true,
            templateUrl: 'autoComplete-popup.html',
            link: function (scope, element, attrs) {

                scope.templateUrl = attrs.templateUrl;

                scope.isOpen = function () {
                    return scope.matches.length > 0;
                };

                scope.isActive = function (matchIdx) {
                    return scope.active == matchIdx;
                };

                scope.selectActive = function (matchIdx) {
                    scope.active = matchIdx;
                };

                scope.selectMatch = function (activeIdx) {
                    scope.select({ activeIdx: activeIdx });
                };
            }
        };
    })

    .directive('autoCompleteMatch', ['$http', '$templateCache', '$compile', '$parse', function ($http, $templateCache, $compile, $parse) {
        return {
            restrict: 'EA',
            scope: {
                index: '=',
                match: '=',
                query: '='
            },
            link: function (scope, element, attrs) {
                var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'autoComplete-match.html';
                $http.get(tplUrl, { cache: $templateCache }).success(function (tplContent) {
                    element.replaceWith($compile(tplContent.trim())(scope));
                });
            }
        };
    }])

    .filter('autoCompleteHighlight', function () {
        function escapeRegexp(queryToEscape) {
            return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
        }
        return function (matchItem, query) {
            return query ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
        };
    });

(function () {
    /* Config */
    var moduleName = 'angularUtils.directives.dirPagination';
    var DEFAULT_ID = '__default';
    /* Module */
    angular.module(moduleName, [])
        .directive('dirPaginate', ['$compile', '$parse', 'paginationService', dirPaginateDirective])
        .directive('dirPaginateNoCompile', noCompileDirective)
        .directive('dirPaginationControls', ['paginationService', 'paginationTemplate', dirPaginationControlsDirective])
        .filter('itemsPerPage', ['paginationService', itemsPerPageFilter])
        .service('paginationService', paginationService)
        .provider('paginationTemplate', paginationTemplateProvider)
        .run(['$templateCache', dirPaginationControlsTemplateInstaller]);

    function dirPaginateDirective($compile, $parse, paginationService) {

        return {
            terminal: true,
            multiElement: true,
            priority: 100,
            compile: dirPaginationCompileFn
        };

        function dirPaginationCompileFn(tElement, tAttrs) {
            var expression = tAttrs.dirPaginate;
            var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
            var filterPattern = /\|\s*itemsPerPage\s*:\s*(.*\(\s*\w*\)|([^\)]*?(?=\s+as\s+))|[^\)]*)/;
            if (match[2].match(filterPattern) === null) {
                throw 'pagination directive: the \'itemsPerPage\' filter must be set.';
            }
            var itemsPerPageFilterRemoved = match[2].replace(filterPattern, '');
            var collectionGetter = $parse(itemsPerPageFilterRemoved);
            addNoCompileAttributes(tElement); // addNoCompileAttributes method is available in this file only.
            // If any value is specified for paginationId, we register the un-evaluated expression at this stage for the benefit of any
            // dir-pagination-controls directives that may be looking for this ID.
            var rawId = tAttrs.paginationId || DEFAULT_ID;
            paginationService.registerInstance(rawId); // registerInstance method is available in this file only.
            return function dirPaginationLinkFn(scope, element, attrs) {
                // Now that we have access to the `scope` we can interpolate any expression given in the paginationId attribute and
                // potentially register a new ID if it evaluates to a different value than the rawId.
                var paginationId = $parse(attrs.paginationId)(scope) || attrs.paginationId || DEFAULT_ID;
                // (TODO: this seems sound, but I'm reverting as many bug reports followed it's introduction in 0.11.0.
                // Needs more investigation.)
                // In case rawId != paginationId we deregister using rawId for the sake of general cleanliness
                // before registering using paginationId
                // paginationService.deregisterInstance(rawId);
                paginationService.registerInstance(paginationId); // registerInstance method is available in this file only.

                var repeatExpression = getRepeatExpression(expression, paginationId); // getRepeatExpression method is available in this controller only.
                addNgRepeatToElement(element, attrs, repeatExpression); // addNgRepeatToElement method is available in this file only.

                removeTemporaryAttributes(element); // addNgRepeatToElement method is available in this file only.
                var compiled = $compile(element);

                var currentPageGetter = makeCurrentPageGetterFn(scope, attrs, paginationId); // makeCurrentPageGetterFn method is available in this file only.
                paginationService.setCurrentPageParser(paginationId, currentPageGetter, scope); // setCurrentPageParser method is available in this file only.

                if (typeof attrs.totalItems !== 'undefined') {
                    paginationService.setAsyncModeTrue(paginationId);  // setAsyncModeTrue method is available in this file only.
                    scope.$watch(function () {
                        return $parse(attrs.totalItems)(scope);
                    }, function (result) {
                        if (0 <= result) {
                            paginationService.setCollectionLength(paginationId, result); // setCollectionLength method is available in this file only.
                        }
                    });
                } else {
                    paginationService.setAsyncModeFalse(paginationId); // setAsyncModeFalse method is available in this file only.
                    scope.$watchCollection(function () {
                        return collectionGetter(scope);
                    }, function (collection) {
                        if (collection) {
                            var collectionLength = (collection instanceof Array) ? collection.length : Object.keys(collection).length;
                            paginationService.setCollectionLength(paginationId, collectionLength);  // setCollectionLength method is available in this file only.
                        }
                    });
                }
                // Delegate to the link function returned by the new compilation of the ng-repeat
                compiled(scope);
            };
        }

        /**
         * If a pagination id has been specified, we need to check that it is present as the second argument passed to
         * the itemsPerPage filter. If it is not there, we add it and return the modified expression.
         *
         * @param expression
         * @param paginationId
         * @returns {*}
         */
        function getRepeatExpression(expression, paginationId) {
            var repeatExpression,
                idDefinedInFilter = !!expression.match(/(\|\s*itemsPerPage\s*:[^|]*:[^|]*)/);

            if (paginationId !== DEFAULT_ID && !idDefinedInFilter) {
                repeatExpression = expression.replace(/(\|\s*itemsPerPage\s*:\s*[^|\s]*)/, "$1 : '" + paginationId + "'");
            } else {
                repeatExpression = expression;
            }

            return repeatExpression;
        }

        /**
         * Adds the ng-repeat directive to the element. In the case of multi-element (-start, -end) it adds the
         * appropriate multi-element ng-repeat to the first and last element in the range.
         * @param element
         * @param attrs
         * @param repeatExpression
         */
        function addNgRepeatToElement(element, attrs, repeatExpression) {
            if (element[0].hasAttribute('dir-paginate-start') || element[0].hasAttribute('data-dir-paginate-start')) {
                // using multiElement mode (dir-paginate-start, dir-paginate-end)
                attrs.$set('ngRepeatStart', repeatExpression);
                element.eq(element.length - 1).attr('ng-repeat-end', true);
            } else {
                attrs.$set('ngRepeat', repeatExpression);
            }
        }

        /**
         * Adds the dir-paginate-no-compile directive to each element in the tElement range.
         * @param tElement
         */
        function addNoCompileAttributes(tElement) {
            angular.forEach(tElement, function (el) {
                if (el.nodeType === 1) {
                    angular.element(el).attr('dir-paginate-no-compile', true);
                }
            });
        }

        /**
         * Removes the variations on dir-paginate (data-, -start, -end) and the dir-paginate-no-compile directives.
         * @param element
         */
        function removeTemporaryAttributes(element) {
            angular.forEach(element, function (el) {
                if (el.nodeType === 1) {
                    angular.element(el).removeAttr('dir-paginate-no-compile');
                }
            });
            element.eq(0).removeAttr('dir-paginate-start').removeAttr('dir-paginate').removeAttr('data-dir-paginate-start').removeAttr('data-dir-paginate');
            element.eq(element.length - 1).removeAttr('dir-paginate-end').removeAttr('data-dir-paginate-end');
        }

        /**
         * Creates a getter function for the current-page attribute, using the expression provided or a default value if
         * no current-page expression was specified.
         *
         * @param scope
         * @param attrs
         * @param paginationId
         * @returns {*}
         */
        function makeCurrentPageGetterFn(scope, attrs, paginationId) {
            var currentPageGetter;
            if (attrs.currentPage) {
                currentPageGetter = $parse(attrs.currentPage);
            } else {
                // If the current-page attribute was not set, we'll make our own.
                // Replace any non-alphanumeric characters which might confuse
                // the $parse service and give unexpected results.
                // See https://github.com/michaelbromley/angularUtils/issues/233
                var defaultCurrentPage = (paginationId + '__currentPage').replace(/\W/g, '_');
                scope[defaultCurrentPage] = 1;
                currentPageGetter = $parse(defaultCurrentPage);
            }
            return currentPageGetter;
        }
    }

    /**
     * This is a helper directive that allows correct compilation when in multi-element mode (ie dir-paginate-start, dir-paginate-end).
     * It is dynamically added to all elements in the dir-paginate compile function, and it prevents further compilation of
     * any inner directives. It is then removed in the link function, and all inner directives are then manually compiled.
     */
    function noCompileDirective() {
        return {
            priority: 5000,
            terminal: true
        };
    }

    function dirPaginationControlsTemplateInstaller($templateCache) {
        $templateCache.put('angularUtils.directives.dirPagination.template', '<ul class="pagination" ng-if="1 < pages.length || !autoHide"><li ng-if="boundaryLinks" ng-class="{ disabled : pagination.current == 1 }"><a href="" ng-click="setCurrent(1)">&laquo;</a></li><li ng-if="directionLinks" ng-class="{ disabled : pagination.current == 1 }"><a href="" ng-click="setCurrent(pagination.current - 1)">&lsaquo;</a></li><li ng-repeat="pageNumber in pages track by tracker(pageNumber, $index)" ng-class="{ active : pagination.current == pageNumber, disabled : pageNumber == \'...\' || ( ! autoHide && pages.length === 1 ) }"><a href="" ng-click="setCurrent(pageNumber)">{{ pageNumber }}</a></li><li ng-if="directionLinks" ng-class="{ disabled : pagination.current == pagination.last }"><a href="" ng-click="setCurrent(pagination.current + 1)">&rsaquo;</a></li><li ng-if="boundaryLinks"  ng-class="{ disabled : pagination.current == pagination.last }"><a href="" ng-click="setCurrent(pagination.last)">&raquo;</a></li></ul>');
    }

    function dirPaginationControlsDirective(paginationService, paginationTemplate) {
        var numberRegex = /^\d+$/;
        var DDO = {
            restrict: 'AE',
            scope: {
                maxSize: '=?',
                onPageChange: '&?',
                paginationId: '=?',
                autoHide: '=?'
            },
            link: dirPaginationControlsLinkFn
        };

        // We need to check the paginationTemplate service to see whether a template path or
        // string has been specified, and add the `template` or `templateUrl` property to
        // the DDO as appropriate. The order of priority to decide which template to use is
        // (highest priority first):
        // 1. paginationTemplate.getString()
        // 2. attrs.templateUrl
        // 3. paginationTemplate.getPath()
        var templateString = paginationTemplate.getString();
        if (templateString !== undefined) {
            DDO.template = templateString;
        } else {
            DDO.templateUrl = function (elem, attrs) {
                return attrs.templateUrl || paginationTemplate.getPath();
            };
        }
        return DDO;

        function dirPaginationControlsLinkFn(scope, element, attrs) {

            // rawId is the un-interpolated value of the pagination-id attribute. This is only important when the corresponding dir-paginate directive has
            // not yet been linked (e.g. if it is inside an ng-if block), and in that case it prevents this controls directive from assuming that there is
            // no corresponding dir-paginate directive and wrongly throwing an exception.
            var rawId = attrs.paginationId || DEFAULT_ID;
            var paginationId = scope.paginationId || attrs.paginationId || DEFAULT_ID;
            // isRegistered method is available in this controlle only.
            if (!paginationService.isRegistered(paginationId) && !paginationService.isRegistered(rawId)) {
                var idMessage = (paginationId !== DEFAULT_ID) ? ' (id: ' + paginationId + ') ' : ' ';
                if (window.console) {
                    console.warn('Pagination directive: the pagination controls' + idMessage + 'cannot be used without the corresponding pagination directive, which was not found at link time.');
                }
            }

            if (!scope.maxSize) { scope.maxSize = 9; }
            scope.autoHide = scope.autoHide === undefined ? true : scope.autoHide;
            scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : true;
            scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : false;

            var paginationRange = Math.max(scope.maxSize, 5);
            scope.pages = [];
            scope.pagination = {
                last: 1,
                current: 1
            };
            scope.range = {
                lower: 1,
                upper: 1,
                total: 1
            };

            scope.$watch('maxSize', function (val) {
                if (val) {
                    paginationRange = Math.max(scope.maxSize, 5);
                    generatePagination(); // generatePagination method is available in this file only.
                }
            });

            scope.$watch(function () {
                // isRegistered method is available in this file only.
                if (paginationService.isRegistered(paginationId)) {
                    // getCollectionLength method is available in this file only.
                    // getItemsPerPage method is available in this file only.
                    return (paginationService.getCollectionLength(paginationId) + 1) * paginationService.getItemsPerPage(paginationId);
                }
            }, function (length) {
                if (0 < length) {
                    generatePagination(); // generatePagination method is available in this file only.S
                }
            });

            scope.$watch(function () {
                // isRegistered method is available in this file only.
                if (paginationService.isRegistered(paginationId)) {
                    // getItemsPerPage method is available in this file only.
                    return (paginationService.getItemsPerPage(paginationId));
                }
            }, function (current, previous) {
                if (current != previous && typeof previous !== 'undefined') {
                    goToPage(scope.pagination.current);  // goToPage method is available in this file only.
                }
            });

            scope.$watch(function () {
                // isRegistered method is available in this controlle only.
                if (paginationService.isRegistered(paginationId)) {
                    return paginationService.getCurrentPage(paginationId); // getCurrentPage method is available in this file only.
                }
            }, function (currentPage, previousPage) {
                if (currentPage != previousPage) {
                    goToPage(currentPage); // goToPage method is available in this file only.
                }
            });

            scope.setCurrent = function (num) {
                // isRegistered method is available in this file only.
                if (paginationService.isRegistered(paginationId) && isValidPageNumber(num)) {
                    num = parseInt(num, 10);
                    paginationService.setCurrentPage(paginationId, num); // setCurrentPage method is available in this file only.
                }
            };
            scope.tracker = function (id, index) {
                return id + '_' + index;
            };

            function goToPage(num) {
                // isRegistered method is available in this file only.
                if (paginationService.isRegistered(paginationId) && isValidPageNumber(num)) {
                    var oldPageNumber = scope.pagination.current;
                    // getCollectionLength method is available in this file only.
                    // getItemsPerPage method is available in this file only.
                    scope.pages = generatePagesArray(num, paginationService.getCollectionLength(paginationId), paginationService.getItemsPerPage(paginationId), paginationRange);
                    scope.pagination.current = num;
                    updateRangeValues(); // updateRangeValues method is available in this file only.

                    // if a callback has been set, then call it with the page number as the first argument
                    // and the previous page number as a second argument
                    if (scope.onPageChange) {
                        scope.onPageChange({
                            newPageNumber: num,
                            oldPageNumber: oldPageNumber
                        });
                    }
                }
            }

            function generatePagination() {
                // isRegistered method is available in this file only.
                if (paginationService.isRegistered(paginationId)) {
                    var page = parseInt(paginationService.getCurrentPage(paginationId)) || 1;  // getCurrentPage method is available in this file only.
                    // getCollectionLength method is available in this file only.
                    // getItemsPerPage method is available in this file only.
                    scope.pages = generatePagesArray(page, paginationService.getCollectionLength(paginationId), paginationService.getItemsPerPage(paginationId), paginationRange);
                    scope.pagination.current = page;
                    scope.pagination.last = scope.pages[scope.pages.length - 1];
                    if (scope.pagination.last < scope.pagination.current) {
                        scope.setCurrent(scope.pagination.last);
                    } else {
                        updateRangeValues(); // updateRangeValues method is available in this file only.
                    }
                }
            }

            /**
             * This function updates the values (lower, upper, total) of the `scope.range` object, which can be used in the pagination
             * template to display the current page range, e.g. "showing 21 - 40 of 144 results";
             */
            function updateRangeValues() {
                // isRegistered method is available in this file only.
                if (paginationService.isRegistered(paginationId)) {
                    var currentPage = paginationService.getCurrentPage(paginationId),  // getCurrentPage method is available in this file only.
                        itemsPerPage = paginationService.getItemsPerPage(paginationId), // getItemsPerPage method is available in this file only.
                        totalItems = paginationService.getCollectionLength(paginationId); // getCollectionLength method is available in this file only.

                    scope.range.lower = (currentPage - 1) * itemsPerPage + 1;
                    scope.range.upper = Math.min(currentPage * itemsPerPage, totalItems);
                    scope.range.total = totalItems;
                }
            }
            function isValidPageNumber(num) {
                return (numberRegex.test(num) && (0 < num && num <= scope.pagination.last));
            }
        }

        /**
         * Generate an array of page numbers (or the '...' string) which is used in an ng-repeat to generate the
         * links used in pagination
         *
         * @param currentPage
         * @param rowsPerPage
         * @param paginationRange
         * @param collectionLength
         * @returns {Array}
         */
        function generatePagesArray(currentPage, collectionLength, rowsPerPage, paginationRange) {
            var pages = [];
            var totalPages = Math.ceil(collectionLength / rowsPerPage);
            var halfWay = Math.ceil(paginationRange / 2);
            var position;

            if (currentPage <= halfWay) {
                position = 'start';
            } else if (totalPages - halfWay < currentPage) {
                position = 'end';
            } else {
                position = 'middle';
            }

            var ellipsesNeeded = paginationRange < totalPages;
            var i = 1;
            while (i <= totalPages && i <= paginationRange) {
                var pageNumber = calculatePageNumber(i, currentPage, paginationRange, totalPages);

                var openingEllipsesNeeded = (i === 2 && (position === 'middle' || position === 'end'));
                var closingEllipsesNeeded = (i === paginationRange - 1 && (position === 'middle' || position === 'start'));
                if (ellipsesNeeded && (openingEllipsesNeeded || closingEllipsesNeeded)) {
                    pages.push('...');
                } else {
                    pages.push(pageNumber);
                }
                i++;
            }
            return pages;
        }

        /**
         * Given the position in the sequence of pagination links [i], figure out what page number corresponds to that position.
         *
         * @param i
         * @param currentPage
         * @param paginationRange
         * @param totalPages
         * @returns {*}
         */
        function calculatePageNumber(i, currentPage, paginationRange, totalPages) {
            var halfWay = Math.ceil(paginationRange / 2);
            if (i === paginationRange) {
                return totalPages;
            } else if (i === 1) {
                return i;
            } else if (paginationRange < totalPages) {
                if (totalPages - halfWay < currentPage) {
                    return totalPages - paginationRange + i;
                } else if (halfWay < currentPage) {
                    return currentPage - halfWay + i;
                } else {
                    return i;
                }
            } else {
                return i;
            }
        }
    }

    /**
     * This filter slices the collection into pages based on the current page number and number of items per page.
     * @param paginationService
     * @returns {Function}
     */
    function itemsPerPageFilter(paginationService) {

        return function (collection, itemsPerPage, paginationId) {
            if (typeof (paginationId) === 'undefined') {
                paginationId = DEFAULT_ID;
            }
            // isRegistered method is available in this file only.
            if (!paginationService.isRegistered(paginationId)) {
                throw 'pagination directive: the itemsPerPage id argument (id: ' + paginationId + ') does not match a registered pagination-id.';
            }
            var end;
            var start;
            if (angular.isObject(collection)) {
                itemsPerPage = parseInt(itemsPerPage) || 9999999999;
                if (paginationService.isAsyncMode(paginationId)) {
                    start = 0;
                } else {
                    // getCurrentPage method is available in this file only
                    start = (paginationService.getCurrentPage(paginationId) - 1) * itemsPerPage;
                }
                end = start + itemsPerPage;
                paginationService.setItemsPerPage(paginationId, itemsPerPage); // setItemsPerPage method is available in this file only

                if (collection instanceof Array) {
                    // the array just needs to be sliced
                    return collection.slice(start, end);
                } else {
                    // in the case of an object, we need to get an array of keys, slice that, then map back to
                    // the original object.
                    var slicedObject = {};
                    angular.forEach(keys(collection).slice(start, end), function (key) {
                        slicedObject[key] = collection[key];
                    });
                    return slicedObject;
                }
            } else {
                return collection;
            }
        };
    }

    /**
     * Shim for the Object.keys() method which does not exist in IE < 9
     * @param obj
     * @returns {Array}
     */
    function keys(obj) {
        if (!Object.keys) {
            var objKeys = [];
            for (var i in obj) {
                if (obj.hasOwnProperty(i)) {
                    objKeys.push(i);
                }
            }
            return objKeys;
        } else {
            return Object.keys(obj);
        }
    }

    /**
     * This service allows the various parts of the module to communicate and stay in sync.
     */
    function paginationService() {

        var instances = {};
        var lastRegisteredInstance;

        this.registerInstance = function (instanceId) {
            if (typeof instances[instanceId] === 'undefined') {
                instances[instanceId] = {
                    asyncMode: false
                };
                lastRegisteredInstance = instanceId;
            }
        };

        this.deregisterInstance = function (instanceId) {
            delete instances[instanceId];
        };

        this.isRegistered = function (instanceId) {
            return (typeof instances[instanceId] !== 'undefined');
        };

        this.getLastInstanceId = function () {
            return lastRegisteredInstance;
        };

        this.setCurrentPageParser = function (instanceId, val, scope) {
            instances[instanceId].currentPageParser = val;
            instances[instanceId].context = scope;
        };
        this.setCurrentPage = function (instanceId, val) {
            instances[instanceId].currentPageParser.assign(instances[instanceId].context, val);
        };
        this.getCurrentPage = function (instanceId) {
            var parser = instances[instanceId].currentPageParser;
            return parser ? parser(instances[instanceId].context) : 1;
        };

        this.setItemsPerPage = function (instanceId, val) {
            instances[instanceId].itemsPerPage = val;
        };
        this.getItemsPerPage = function (instanceId) {
            return instances[instanceId].itemsPerPage;
        };

        this.setCollectionLength = function (instanceId, val) {
            instances[instanceId].collectionLength = val;
        };
        this.getCollectionLength = function (instanceId) {
            return instances[instanceId].collectionLength;
        };

        this.setAsyncModeTrue = function (instanceId) {
            instances[instanceId].asyncMode = true;
        };

        this.setAsyncModeFalse = function (instanceId) {
            instances[instanceId].asyncMode = false;
        };

        this.isAsyncMode = function (instanceId) {
            return instances[instanceId].asyncMode;
        };
    }

    /**
     * This provider allows global configuration of the template path used by the dir-pagination-controls directive.
     */
    function paginationTemplateProvider() {

        var templatePath = 'angularUtils.directives.dirPagination.template';
        var templateString;

        /**
         * Set a templateUrl to be used by all instances of <dir-pagination-controls>
         * @param {String} path
         */
        this.setPath = function (path) {
            templatePath = path;
        };

        /**
         * Set a string of HTML to be used as a template by all instances
         * of <dir-pagination-controls>. If both a path *and* a string have been set,
         * the string takes precedence.
         * @param {String} str
         */
        this.setString = function (str) {
            templateString = str;
        };

        this.$get = function () {
            return {
                getPath: function () {
                    return templatePath;
                },
                getString: function () {
                    return templateString;
                }
            };
        };
    }
})();
wacorpApp.directive('customPager', function () {
    return {
            scope: {
                page: '=?page',
                pagesCount: '=?pagesCount',
                totalCount: '=?totalCount',
                searchFunc: '&?searchFunc',
                customPath: '=?customPath'
            },
            replace: true,
            restrict: 'E',
            templateUrl: 'ng-app/directives/pager/pager.html',
            controller: ['$scope', function ($scope) {
                $scope.search = function (i) {
                    if ($scope.searchFunc) {
                        $scope.searchFunc({ page: i });
                    }
                };

                $scope.range = function () {
                    if (!$scope.pagesCount) { return []; }
                    var step = constant.TWO;
                    var doubleStep = step * constant.TWO;
                    var start = Math.max(constant.ZERO, $scope.page - step);
                    var end = start + constant.ONE + doubleStep;
                    if (end > $scope.pagesCount) { end = $scope.pagesCount; }

                    var ret = [];
                    for (var i = start; i != end; ++i) {
                        ret.push(i);
                    }

                    return ret;
                };

                $scope.pagePlus = function(count)
                {
                    return +$scope.page + count;
                }
            }]
        }
});
wacorpApp.directive('businessAddress', function () {
    return {
        templateUrl: 'ng-app/directives/businessAddress/_businessAddress.html',
        restrict: 'A',
        scope: {
            address: '=?address',
            isAgentAddress: '=?isAgentAddress',
            isStreetAddress: '=?isStreetAddress',
            showErrorMessage: '=?showErrorMessage',
            isRaAddress: '=?isRaAddress',
            isRaAddress2: '=?isRaAddress2',
            isPoAddress: '=?isPoAddress',
            isPoAddress2: '=?isPoAddress2',
            isRaMailing: '=?isRaMailing',
            isForeignCanAllow: '=?isForeignCanAllow',
            isDisabled: '=?isDisabled',
            isAcpAddress: '=?isAcpAddress',
            isPoMailing: '=?isPoMailing',
            isRafAddress: '=?isRafAddress',
            isNotNeeded: '=?isNotNeeded',
            isValidAddressForZip: '=?isValidAddressForZip',
            showvalidationMessage: '=?showvalidationMessage',
            isCommercial: '=?isCommercial',
            userAccount: '=?userAccount',
            isStatementChange: '=?isStatementChange',
            userRegStreetAdd: '=?userRegStreetAdd',
            userRegMailingAdd: '=?userRegMailingAdd',
            isCraReg: '=?isCraReg',
            isCorrpAdd: '=?isCorrpAdd',
            isMandatory: '=?isMandatory'

        },
        controller: function ($scope, lookupService, wacorpService, $timeout, $rootScope) {

            $scope.messages = messages;
            var addressScope = {
                ZipExtension: null, AddressEntityType: null, IsAddressSame: false, IsValidAddress: false, isUserNonCommercialRegisteredAgent: false, IsInvalidState: false,
                baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
            };

            //Set default values of scope variables
            $scope.address = $scope.address ? angular.extend(addressScope, $scope.address) : angular.copy(addressScope);
            $scope.address.Zip5 = $scope.address.Zip5 != undefined ? $scope.address.Zip5.trim() : $scope.address.Zip5;
            $scope.isAgentAddress = $scope.isAgentAddress || false;
            $scope.isStreetAddress = $scope.isStreetAddress || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isRaAddress = $scope.isRaAddress || false;
            $scope.isPoAddress = $scope.isPoAddress || false;
            $scope.isAcpAddress = $scope.isAcpAddress || false;
            $scope.isNotNeeded = $scope.isNotNeeded || false;
            $scope.poAddress = false;
            $scope.isDisabled = $scope.isDisabled || false;
            $scope.isRafAddress = $scope.isRafAddress || false;
            //$scope.address.isValidAddress = $scope.address.isValidAddress || true;
            $scope.isValidAddressForZip = $scope.isValidAddressForZip || false;
            //$scope.address.invalidZip = $scope.address.Zip5 == undefined ? false : true;
            $scope.isRaMailingFlag = false;
            $scope.isCommercialFlag = false;
            $scope.userAccountFlag = false;
            $scope.isStatementChangeFlag = false;
            $scope.isPoMailingFlag = false;
            //Prepped comma indicator in front of a object
            $scope.PrependComa = function (val, indicator) {
                return val == "" ? "" : indicator + val;
            };

            $scope.Init = function () {
                if ($scope.isRaMailing != undefined && !$scope.isRaMailing) {
                    if ($scope.businessAddress.ValidAddressCheck)
                        $scope.businessAddress.ValidAddressCheck.$setValidity("text", true);
                    $scope.address.StreetAddress1 = $scope.address.StreetAddress1 ? angular.copy($scope.address.StreetAddress1.trim()) : (($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") ? $scope.address.StreetAddress1 = null : $scope.address.StreetAddress1);
                    $scope.address.Zip5 = $scope.address.Zip5 ? angular.copy($scope.address.Zip5.trim()) : (($scope.address.Zip5 == undefined || $scope.address.Zip5 == "") ? $scope.address.Zip5 = null : $scope.address.Zip5);
                    $scope.address.Zip4 = $scope.address.Zip4 ? angular.copy($scope.address.Zip4.trim()) : (($scope.address.Zip4 == undefined || $scope.address.Zip4 == "") ? $scope.address.Zip4 = null : $scope.address.Zip4);
                    $scope.address.City = $scope.address.City ? angular.copy($scope.address.City.trim()) : (($scope.address.City == undefined || $scope.address.City == "") ? $scope.address.City = null : $scope.address.City);
                    //$scope.address.City = (($scope.address.City && (!$scope.address.StreetAddress1 || !$scope.address.Zip5)) ? null : $scope.address.City);
                    $scope.validateRAMailingAddress();
                }
            }


            //Get Full Address
            $scope.$parent.fullAddress = function (addScope) {
                var fullAddres = (addScope.StreetAddress1 || "") + $scope.PrependComa((addScope.StreetAddress2 || ""), ', ')
                         + $scope.PrependComa((addScope.City || ""), ', ')
                         + ((addScope.Country == codes.USA || addScope.Country == 'CAN') ? $scope.PrependComa((addScope.State || ""), ', ') : $scope.PrependComa((addScope.OtherState || ""), ', '))
                         + ((addScope.Country == codes.USA) ? $scope.PrependComa((addScope.Zip5 || ""), ', ')
                         + $scope.PrependComa((addScope.Zip4 || ""), "-") : $scope.PrependComa((addScope.PostalCode || ""), ', '))
                         + $scope.PrependComa((addScope.Country || ""), ', ');
                return (fullAddres == null || fullAddres == '') ? ResultStatus.NONE : fullAddres;
            };

            $scope.Countries = [];
            $scope.States = [];

            //$scope.businessAddress.ValidAddressCheck.$setValidity("text", true);

            //Get Countries List
            $scope.getCountries = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.countriesList(function (response) { $scope.Countries = response.data; });
            };

            //Get States List
            $scope.getStates = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.statesList(function (response) {
                    $scope.States = response.data;
                    $scope.initLoadCountry(); // initLoadCountry method is available in this file only.
                });
            };

            $scope.getCountries(); // getCountries method is available in this file only.
            $scope.getStates(); // getStates method is available in this file only.

            $scope.isRunning = false;
            $scope.isAddressValidated = false;

            $scope.$watch('address', function () {
                $scope.isAddressValidated = false;
            }, true);

            //USPS Address Validation on city blur
            $scope.getValidAddress = function (isRaMailing, isCommercial, userAccount, isStatementChange, isPoMailing) {
                   
                if ($scope.address.IsACPChecked) {
                    $scope.businessAddress.ValidAddressCheck.$setValidity("text", true);
                    return true;
                }
                $scope.businessAddress.ValidAddressCheck.$setValidity("text", true);
                $scope.isValidAddressForZip = true;
                if ($scope.isRunning || $scope.isAddressValidated) return false;
                if (isUSPSServiceValid && $scope.address.StreetAddress1 != "") {
                    var addressorg = {
                        Address1: $scope.address.StreetAddress1,
                        Address2: $scope.address.StreetAddress2,
                        City: $scope.address.City,
                        State: $scope.address.State,
                        Zip5: $scope.address.Zip5,
                        Zip4: $scope.address.Zip4,
                        isUserNonCommercialRegisteredAgent: $scope.isAgentAddress ? true : false,
                        IsButtonClick: false
                        //isUserNonCommercialRegisteredAgent: $scope.address.isUserNonCommercialRegisteredAgent,
                    };

                    var isvalusExist = (angular.isDefined(addressorg.Address1) && !angular.isNullorEmpty(addressorg.Address1)
                                      && angular.isDefined(addressorg.City) && !angular.isNullorEmpty(addressorg.City)
                                      && angular.isDefined(addressorg.State) && !angular.isNullorEmpty(addressorg.State))
                                      && (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5))
                                      && (angular.isDefined(addressorg.isUserNonCommercialRegisteredAgent) && !angular.isNullorEmpty(addressorg.isUserNonCommercialRegisteredAgent));

                    if ($scope.isAgentAddress) {
                        $scope.address.Country = codes.USA;
                    }

                    if ($scope.address.Country === codes.USA && isvalusExist) {
                        $scope.isRunning = true;
                        // getValidAddress method is available in constants.js
                        wacorpService.post(webservices.Common.getValidAddress, addressorg, function (response) {
                            var result = response.data;
                            if (result.HasErrors) {
                                if (result.ErrorDescription.trim() == "Invalid City." || result.ErrorDescription.trim() == "Invalid Zip Code.") {
                                    wacorpService.alertDialog(result.ErrorDescription);
                                    $scope.address.Zip5 = '';
                                    $scope.address.Zip4 = '';
                                    //$scope.address.City = '';
                                }
                                else {
                                    if ($scope.isAgentAddress) {
                                        $scope.isValidAddressForZip = true;
                                        $scope.businessAddress.ValidAddressCheck.$setValidity("text", false);
                                        $scope.clearRAAddress(isRaMailing, isCommercial, userAccount, isStatementChange);
                                    }
                                    else {
                                        $scope.isValidAddressForZip = false;
                                        $scope.businessAddress.ValidAddressCheck.$setValidity("text", true);
                                        //$scope.businessAddress.ValidAddressCheck.$setValidity("invalid", false);
                                    }
                                    //to test when usps service is down
                                    if (result.ErrorDescription && result.ErrorDescription == "usps service is down") {
                                        $scope.isValidAddressForZip = true;
                                    }
                                    else {
                                        // Service Folder: services
                                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                                        wacorpService.alertDialog(result.ErrorDescription);
                                        $scope.address.isRAStreetAddressValid = false;
                                    }

                                }
                            }
                            else if (result.IsAddressModifed) {
                                $scope.isValidAddressForZip = true;
                                if ($scope.isAgentAddress) {
                                    if (result.State == codes.WA) {
                                        // Folder Name: app Folder
                                        // Alert Name: invalidAddressData method is available in alertMessages.js
                                        wacorpService.confirmDialog($scope.messages.Address.invalidAddressData, function () {
                                            $scope.address.Zip5 = result.Zip5;
                                            $scope.address.Zip4 = result.Zip4;
                                            $scope.address.City = result.City;
                                            $scope.address.State = result.State;
                                            $scope.address.StreetAddress1 = result.Address1;

                                            $timeout(function () {
                                                $scope.isAddressValidated = true;
                                            }, 1000);
                                        });
                                    }
                                        //to test when usps service is down
                                    else if (result.ErrorDescription && result.ErrorDescription == "usps service is down") {
                                        $scope.isAddressValidated = true;
                                    }
                                    else {
                                        // Folder Name: app Folder
                                        // Alert Name: notWashingtonAddress method is available in alertMessages.js
                                        wacorpService.alertDialog($scope.messages.Address.notWashingtonAddress);
                                    }

                                }
                                else {
                                    // Folder Name: app Folder
                                    // Alert Name: invalidAddressData method is available in alertMessages.js
                                    wacorpService.confirmDialog($scope.messages.Address.invalidAddressData, function () {
                                        $scope.address.Zip5 = result.Zip5;
                                        $scope.address.Zip4 = result.Zip4;
                                        $scope.address.City = result.City;
                                        $scope.address.State = result.State;
                                        $scope.address.StreetAddress1 = result.Address1;

                                        $timeout(function () {
                                            $scope.isAddressValidated = true;
                                        }, 1000);
                                    });
                                }
                            }
                                //to test when usps service is down
                            else if (result.ErrorDescription && result.ErrorDescription == "usps service is down")
                            {
                                $scope.address.IsValidAddress = true;
                            }
                            else {
                                $scope.address.IsValidAddress = false;
                                $scope.address.Zip4 = result.Zip4;
                                if (isPoMailing!=undefined && !isPoMailing) {
                                    $scope.clearPOMailingAddress();
                                }
                                else {
                                    $scope.clearRAAddress(isRaMailing, isCommercial, userAccount, isStatementChange);// to un check RA,PO mailing address
                                }

                                $timeout(function () {
                                    $scope.isAddressValidated = true;
                                }, 1000);
                            }
                            $timeout(function () {
                                $scope.isRunning = false;
                            }, 1000);

                        }, function (response) {
                            $scope.isRunning = false;
                        });
                    }
                }
            }

            //USPS Address Validation on city blur
            var sentRequest = false;
            $scope.getValidAddressWithnoAlerts = function (defer, ngmodel) {
                if (sentRequest) {
                    return false;
                }

                if (isUSPSServiceValid && $scope.address.StreetAddress1 != "") {
                    var addressorg = {
                        Address1: $scope.address.StreetAddress1,
                        Address2: $scope.address.StreetAddress2,
                        City: $scope.address.City,
                        State: $scope.address.State,
                        Zip5: $scope.address.Zip5,
                        Zip4: $scope.address.Zip4,
                        isUserNonCommercialRegisteredAgent: $scope.isAgentAddress ? true : false,
                        //isUserNonCommercialRegisteredAgent: $scope.address.isUserNonCommercialRegisteredAgent,
                    };

                    if ($scope.isAgentAddress) {
                        $scope.address.Country = codes.USA;
                    }

                    var isvalusExist = (angular.isDefined(addressorg.Address1) && !angular.isNullorEmpty(addressorg.Address1)
                                      && angular.isDefined(addressorg.City) && !angular.isNullorEmpty(addressorg.City)
                                      && angular.isDefined(addressorg.State) && !angular.isNullorEmpty(addressorg.State))
                                      && (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5))
                                      && (angular.isDefined(addressorg.isUserNonCommercialRegisteredAgent) && !angular.isNullorEmpty(addressorg.isUserNonCommercialRegisteredAgent));
                    if ($scope.address.Country === codes.USA && isvalusExist) {
                        //$timeout(function () {
                        sentRequest = true;
                        // getValidAddress method is available in constants.js
                        wacorpService.post(webservices.Common.getValidAddress, addressorg, function (response) {
                            var result = response.data;
                            if (result != undefined && result.HasErrors) {
                                ngmodel.$setValidity('isvalidaddress', false);
                                defer.reject();

                            } else {
                                ngmodel.$setValidity('isvalidaddress', true);
                                defer.resolve();
                            }
                            //return result;
                            sentRequest = false;
                        }, function (response) { });
                        // }, 1000);
                    }
                }
            }

            //Get City State on Zip5 blur
            $scope.getCityStateAddress = function (isRaMailing, isCommercial, userAccount, isStatementChange, isPoMailing) {
                     
                //$scope.address.invalidZip = false;

                if ($scope.isRunning || $scope.isAddressValidated) return false;
                var addressorg = {
                    Address1: $scope.address.StreetAddress1,
                    Address2: $scope.address.StreetAddress2,
                    City: $scope.address.City,
                    State: $scope.address.State,
                    Zip5: $scope.address.Zip5,
                    Zip4: "",
                    isUserNonCommercialRegisteredAgent: $scope.isAgentAddress ? true : false,
                    //isUserNonCommercialRegisteredAgent: $scope.address.isUserNonCommercialRegisteredAgent,
                };

                var isvalusExist = (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5) && addressorg.Zip5.length==5);

                if ($scope.address.Zip5 == undefined) {
                    $scope.address.City = '';
                    $scope.address.Zip4 = '';
                    $scope.address.invalidZip = true;
                }

                if (isvalusExist) {
                    $scope.address.IsInvalidState = false;
                    $scope.isRaMailingFlag = isRaMailing;
                    $scope.isCommercialFlag = isCommercial;
                    $scope.userAccountFlag = userAccount;
                    $scope.isStatementChangeFlag = isStatementChange;
                    $scope.isPoMailingFlag = isPoMailing;

                    // getCityStateZip method is available in constants.js
                    wacorpService.post(webservices.Common.getCityStateZip, addressorg, function (response) {
                        var result = response.data;
                        if (result.HasErrors) {
                            // Folder Name: app Folder
                            // Alert Name: validZipExtension method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.Address.validZipExtension);
                            $scope.address.Zip5 = '';
                            $scope.address.Zip4 = '';
                            $scope.address.City = '';
                            $scope.address.State = 'WA';
                            $scope.address.isRAStreetAddressValid =false;
                        }
                            //else if (result.IsAddressModifed) {
                        else if ($scope.isAgentAddress) {
                            if (result.State == codes.WA) {
                                $scope.address.Zip5 = result.Zip5;
                                $scope.address.Zip4 = result.Zip4;
                                $scope.address.City = result.City;
                                $scope.address.State = result.State;
                                $scope.address.StreetAddress1 = result.Address1;
                                $scope.address.isRAStreetAddressValid =true;
                                $scope.address.IsInvalidState = false;
                                if (result.ErrorDescription && result.ErrorDescription.toLowerCase() == "usps service is down") {
                                    $scope.address.invalidZip = false;
                                    $scope.address.IsInvalidState = false;
                                    $scope.isAddressValidated = true;
                                }
                                else {
                                    $scope.getValidAddress($scope.isRaMailingFlag, $scope.isCommercialFlag, $scope.userAccountFlag, $scope.isStatementChangeFlag, !$scope.isPoMailingFlag); // getValidAddress method is available in this file only.
                                }
                            }
                                //to test when usps service is down.
                            else if (result.ErrorDescription && result.ErrorDescription.toLowerCase() == "usps service is down")
                            {
                                $scope.address.invalidZip = false;
                                $scope.address.IsInvalidState = false;
                                $scope.isAddressValidated = true;
                            }
                            else {
                                $scope.address.IsInvalidState = true;
                                // Folder Name: app Folder
                                // Alert Name: notWashingtonAddress method is available in alertMessages.js
                                wacorpService.alertDialog($scope.messages.Address.notWashingtonAddress);
                            }
                        }
                        else {
                            $scope.address.Zip5 = result.Zip5;
                            $scope.address.Zip4 = result.Zip4;
                            $scope.address.City = result.City;
                            $scope.address.State = result.State;
                            $scope.address.StreetAddress1 = result.Address1;
                            //to test when usps service is down
                            if (result.ErrorDescription && result.ErrorDescription.toLowerCase() == "usps service is down") {
                                $scope.address.invalidZip = false;
                                $scope.address.IsInvalidState = false;
                                $scope.isAddressValidated = true;
                            }
                            else {
                                $scope.getValidAddress($scope.isRaMailingFlag, $scope.isCommercialFlag, $scope.userAccountFlag, $scope.isStatementChangeFlag, $scope.isPoMailingFlag); // getValidAddress method is available in this file only.
                            }
                        }
                        //to test when usps service is down
                        if (result.ErrorDescription && result.ErrorDescription.toLowerCase() == "usps service is down")
                        {
                            $scope.address.invalidZip = false;
                            $scope.address.IsInvalidState = false;
                            $scope.isAddressValidated = true;
                        }
                        else {
                            $scope.validateMailingAddress();  // validateMailingAddress method is available in this file only.
                        }
                        //}
                        //else {
                        //    $scope.address.invalidZip = false;
                        //    $scope.address.IsInvalidState = false;
                        //    $scope.isAddressValidated = true;
                        //}
                        // }
                    }, function (response) {

                    });
                }

            }

            $scope.$watch('address', function () {
                if (angular.isNullorEmpty($scope.address))
                    return;
                else {
                    var fullAddr = ($scope.address.StreetAddress1 || "") + PrependComa(($scope.address.StreetAddress2 || ""), ', ')
                                + PrependComa(($scope.address.City || ""), ', ')
                                + (($scope.address.Country == 'USA') ? PrependComa(($scope.address.State || ""), ', ') : ($scope.address.Country == 'CAN' ? PrependComa(($scope.address.State || ""), ', ') : PrependComa(($scope.address.OtherState || ""), ', ')))
                                + (($scope.address.Country == 'USA') ? PrependComa(($scope.address.Zip5 || ""), ', ')
                                + PrependComa(($scope.address.Zip4 || ""), "-") : PrependComa(($scope.address.PostalCode || ""), ', '))
                                + PrependComa(($scope.address.Country || ""), ', ');
                    $scope.address.FullAddress = (fullAddr == null || fullAddr == '') ? '' : fullAddr;
                }
            }, true);

            var PrependComa = function (val, indicator) {
                return val == "" ? "" : indicator + val;
            };

            //to validate PO BOX for Agent Address1
            $scope.validateAgentPoBox = function (value, flag) {
                value = angular.lowercase(value);
                var status = false;
                var address = new Array("po box", "pobox", "post office box", "post office", "p.o.box", "p.o. box", "p o box", "p. o. box", "po. box", "box", "p. o box", "pmb", "p.m.b", "p m b", "private mailbox", "private mail box");
                if (value != "" && flag) {
                    angular.forEach(address, function (key, data) {
                        if (value.indexOf(key) > -1) {
                            status = true;
                            $scope.isRaAddress = true;
                            //$scope.isPoAddress = true;
                            $scope.address.StreetAddress1 = '';
                            $scope.address.invalidPoBoxAddress = true;
                        }

                    });
                    if (!status) {
                        $scope.isRaAddress = false;
                        //$scope.isPoAddress = false;
                        $scope.address.invalidPoBoxAddress = false;
                    }
                }
                else {
                    $scope.isRaAddress = false;
                    $scope.address.invalidPoBoxAddress = false;
                }
            };

            //to validate PO BOX for Agent Address2
            $scope.validateAgentPoBox2 = function (value, flag) {
                value = angular.lowercase(value);
                var status = false;
                var address = new Array("po box", "pobox", "post office box", "post office", "p.o.box", "p.o. box", "p o box", "p. o. box", "po. box", "box", "p. o box", "pmb", "p.m.b", "p m b", "private mailbox", "private mail box");
                if (typeof value != typeof undefined && value != null && value != "" && flag) {
                    angular.forEach(address, function (key, data) {
                        if (value.indexOf(key) > -1) {
                            status = true;
                            $scope.isRaAddress2 = true;
                            //$scope.isPoAddress = true;
                            $scope.address.StreetAddress2 = '';
                            $scope.address.invalidPoBoxAddress = true;
                        }

                    });
                    if (!status) {
                        $scope.isRaAddress2 = false;
                        $scope.address.invalidPoBoxAddress = false;
                        //$scope.isPoAddress = false;
                    }
                }
                else {
                    $scope.isRaAddress2 = false;
                    $scope.address.invalidPoBoxAddress = false;
                }
            };

            //to validate PO BOX for PrinciaplOffice Address1
            $scope.validatePoBox = function (value, flag) {
                if ($scope.isPoAddress) {
                    value = angular.lowercase(value);
                    var status = false;
                    var address = new Array("po box", "pobox", "post office box", "post office", "p.o.box", "p.o. box", "p o box", "p. o. box", "po. box", "box", "p. o box", "pmb", "p.m.b", "p m b", "private mailbox", "private mail box");
                    if (typeof value != typeof undefined && value != null && value != "" && flag) {
                        angular.forEach(address, function (key, data) {
                            if (value.indexOf(key) > -1) {
                                status = true;
                                $scope.poAddress = true;
                                $scope.address.StreetAddress1 = '';
                            }

                        });
                        if (!status) {
                            $scope.poAddress = false;
                        }
                    }
                    else {
                        $scope.poAddress = false;
                    }
                }
            };

            //to validate PO BOX for PrinciaplOffice Address2
            $scope.validatePoBox2 = function (value, flag) {
                if ($scope.isPoAddress) {
                    value = angular.lowercase(value);
                    var status = false;
                    var address = new Array("po box", "pobox", "post office box", "post office", "p.o.box", "p.o. box", "p o box", "p. o. box", "po. box", "box", "p. o box", "pmb", "p.m.b", "p m b", "private mailbox", "private mail box");
                    if (typeof value != typeof undefined && value != null && value != "" && flag) {
                        angular.forEach(address, function (key, data) {
                            if (value.indexOf(key) > -1) {
                                status = true;
                                $scope.poAddress2 = true;
                                $scope.address.StreetAddress2 = '';
                            }

                        });
                        if (!status) {
                            $scope.poAddress2 = false;
                        }
                    }
                    else {
                        $scope.poAddress2 = false;
                    }
                }
            };

            /* New chagnes for Canada */

            $scope.requiredStatesForCountry = ["USA", "CAN"];
            var canadaStates = ["AB", "BC", "MB", "NB", "NL", "NS", "NT", "NU", "ON", "PE", "QC", "SK", "YT"];
            $scope.statesArray = [];

            $scope.changeCountry = function () {
                var $country = angular.element(event.target);
                if ($country.val() != "USA")
                {
                    $scope.address.invalidZip = false;
                    if ($scope.businessAddress.Zip5 != undefined && $scope.businessAddress.Zip5!="")
                         $scope.businessAddress.Zip5.$viewValue = "";
                }
                    
                if ($scope.requiredStatesForCountry.indexOf($country.val()) > -1) {

                    if ($scope.statesArray.length == 0)
                        angular.copy($scope.States, $scope.statesArray);

                    $scope.States.length = 0;

                    angular.forEach($scope.statesArray, function (data, index) {
                        if (canadaStates.indexOf(data.Key) > -1 && $country.val() == "CAN") {
                            $scope.States.push(data);
                        }
                        else if (canadaStates.indexOf(data.Key) == -1 && $country.val() == "USA") {
                            $scope.States.push(data);
                        }
                    });

                    // set default state
                    $timeout(function () {
                        //if ($scope.address.State == "" && $country.val() == "USA")
                        if ((canadaStates.indexOf($scope.address.State) > -1 || $scope.address.State == "") && $country.val() == "USA")
                        {
                            $scope.address.State = "WA";
                            $scope.address.PostalCode = '';
                        }
                            
                        else if ($country.val() == "CAN")
                            //$scope.address.State = $scope.address.State || "";
                            $scope.address.State = "";
                        else if (canadaStates.indexOf($scope.address.State) == -1 && $country.val() == "USA") {
                            $scope.address.PostalCode = '';
                        }
                    }, 200);
                    $scope.address.OtherState = '';
                    //$scope.address.PostalCode = '';
                }
                $rootScope.$broadcast("InvokeServiceAddress");
                $scope.clearPOMailingAddress();
                if ($scope.isPoMailing != undefined && $scope.isPoMailing)
                {
                    if ($country.val() != "USA" && $scope.businessAddress.Zip5.$viewValue == "" && !$scope.validateData($scope.address.City))
                        $scope.validateMailingAddressForStreet1();
                        $scope.address.invalidZip = false;
                }
                else if ($scope.isRafAddress != undefined && $scope.isRafAddress)
                {
                    if ($country.val() != "USA" && $scope.businessAddress.Zip5.$viewValue == "" && !$scope.validateData($scope.address.City)) {
                        $scope.validateMailingAddressForStreet1();
                        $scope.address.invalidZip = false;
                    }
                }
                else if ($scope.isCraReg != undefined && $scope.isCraReg) {

                    if ($country.val() != "USA" && $scope.businessAddress.Zip5.$viewValue == "" && !$scope.validateData($scope.address.City)) {
                        $scope.validateMailingAddressForStreet1();
                        $scope.address.invalidZip = false;
                    }
                }
                else if ($scope.isCraReg != undefined && $scope.isCraReg) {

                    if ($country.val() != "USA" && $scope.businessAddress.Zip5.$viewValue == "" && !$scope.validateData($scope.address.City)) {
                        $scope.validateMailingAddressForStreet1();
                        $scope.address.invalidZip = false;
                    }
                }
            }

            $scope.initLoadCountry = function () {
                if ($scope.requiredStatesForCountry.indexOf($scope.address.Country) > -1) {

                    if ($scope.statesArray.length == 0)
                        angular.copy($scope.States, $scope.statesArray);

                    $scope.States.length = 0;

                    angular.forEach($scope.statesArray, function (data, index) {
                        if (canadaStates.indexOf(data.Key) > -1 && $scope.address.Country == "CAN") {
                            $scope.States.push(data);
                        }
                        else if (canadaStates.indexOf(data.Key) == -1 && $scope.address.Country == "USA") {
                            $scope.States.push(data);
                        }
                    });

                    // set default state
                    $timeout(function () {
                        //if ($scope.address.State == "" && $scope.address.Country == "USA")
                        if ((canadaStates.indexOf($scope.address.State) > -1 || $scope.address.State == "") && $scope.address.Country == "USA")
                            $scope.address.State = "WA";
                        else if ($scope.address.Country == "CAN")
                            $scope.address.State = $scope.address.State || "";
                    }, 200);
                }
            }

            $scope.validatePoBox = function () {
                if ($scope.isPoAddress)
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.isAcpAddress = wacorpService.validatePoBoxAddress($scope.address);
            }

            $scope.validatePoBox(); // validatePoBox method is available in this file only.

            $scope.$watch('address.Country', function () {
                $scope.initLoadCountry(); // initLoadCountry method is available in this file only.
            });


            var registerAddress = $rootScope.$on("InvokeMethod", function () {
                $scope.getCityStateAddress(); // getCityStateAddress method is available in this file only.
            });

            $scope.$on('$destroy', function () {

                registerAddress(); // registerAddress method is available in this file only.
            });

            $scope.IsInvalidStateTrue = function (e) {
                 
                $scope.address.IsInvalidState = false;

                //Remove validations if For RA Mailing Address zip5 is empty
                if ($scope.isRaMailing != undefined && !$scope.isRaMailing) {
                    if (e.key == "Delete" || e.key == "Del" || e.which == 46 || e.which==8 && ($scope.businessAddress != undefined && $scope.businessAddress.Zip5.$viewValue != undefined)) {
                        $scope.address.Zip5 = null;
                        $scope.address.StreetAddress1 = "";
                        $scope.address.StreetAddress2 = '';
                        $scope.address.PostalCode = '';
                        $scope.address.City = '';
                        $scope.RemoveValidationForZip5();
                    }
                    else if (e.key == "Backspace" && ($scope.businessAddress != undefined && $scope.businessAddress.Zip5.$viewValue != undefined && $scope.businessAddress.Zip5.$viewValue.length == 1)) {
                        $scope.address.StreetAddress1 = "";
                        $scope.address.StreetAddress2 = '';
                        $scope.address.PostalCode = '';
                        $scope.address.City = '';
                        $scope.RemoveValidationForZip5();
                    }
                }
                else {
                    if (e.key == "Delete" || e.key == "Del" || e.which == 46 || e.which == 8) {
                        $scope.address.isRAStreetAddressValid = false;
                    }
                    else if ($scope.address.Zip5 == undefined) {
                        $scope.address.isRAStreetAddressValid = false;
                    }
                }
            };

            $scope.RemoveValidationForZip5 = function () {
                
                $scope.address.isAddressComponentKeyPressed = false;

                $scope.address.invalidZip = false;

                if(angular.isUndefined($scope.address.Zip5)) {
                    $scope.address.invalidZip = true
                }


                //This condition is to help the method nullCheckAddressCompnent(modal,component) which is presented in service(wacorpService.nullCheckAddressCompnent($scope.modal, $scope[amendedAnnualReportForm]))
                //purpose of this condition is If the user had entered the data and removed the data immediately then no need of any validation which we handle this in service
                if ($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") {
                    $scope.address.isAddressComponentKeyPressed = true;
                    //When there is not data in streetaddress1 then we are removing zip5 and zip4 becausing that are creating lot of mess and we are making zip5 validation false
                    $scope.address.invalidZip = false;
                    $scope.address.Zip5 = '';
                    $scope.address.Zip4 = '';
                    $scope.address.City = '';
                    //$scope.address.isRAStreetAddressValid = false;
                }


                if ($scope.address.StreetAddress1 && $scope.address.Zip5 && $scope.address.Zip4) {
                    $scope.address.Zip4 = "";
                    $scope.isAddressValidated = false;
                }

                if ($scope.isNotNeeded) {
                    return true;
                }

                //This section is validate RA Mailing Address
                if ($scope.isRaMailing != undefined && !$scope.isRaMailing)
                {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        //$scope.showErrorMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                        //to remove RA Mailing address alert when no address is present.
                        $scope.address.IsInvalidState = false;
                    }
                }

                //This section is to validate Prinicipal office Mailing Address
                if ($scope.isPoMailing != undefined && $scope.isPoMailing) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
                //This section is to validate Filing Correspondence Address
                if ($scope.isRafAddress != undefined && $scope.isRafAddress) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
            };

            $scope.$watch('address.Country', function () {
                $scope.initLoadCountry(); // initLoadCountry method is available in this file only.
            });


            $scope.$watch('address.raisezip5KeyEvent', function (newvalue, oldvalue) {
                if (newvalue) {
                    $scope.getCityStateAddress(); // getCityStateAddress method is available in this file only.
                }
            });



            var acpCheckBoxChecked = $rootScope.$on("InvokeValidAddressCheck", function () {
                //$scope.address.IsACPChecked =true;
                $scope.getValidAddress(); // getValidAddress method is available in this file only.
            });

            $scope.$on('$destroy', function () {

                acpCheckBoxChecked(); // acpCheckBoxChecked method is available in this file only.
            });

            var removeValidationPOMailing = $scope.$on("IsMailingPOAddress", function (evt, data) {
                var flag = data ? 1 : 2;
                switch (flag) {
                    case 1:
                        $scope.RemovePoValidation(data); // RemovePoValidation method is available in this file only.
                        break;
                    case 2:
                        $scope.RemovePoValidation(data); // RemovePoValidation method is available in this file only.
                        break;
                    default:
                        break;

                }
                evt.defaultPrevented = true;
            });

            $scope.$on('$destroy', removeValidationPOMailing);


            var checkRAValidation = $scope.$on("IsMailingRAAddress", function (evt, data,agent) {
                switch (data) {
                    case data:
                        //if (data) 11/28/2018
                        $scope.setValidation(data,agent);  // setValidation method is available in this file only.
                        break;
                    case !data:
                        $scope.setValidation(data,agent);// setValidation method is available in this file only.
                        break;
                    default:
                        break;

                }
                evt.defaultPrevented = true;
            });

            $scope.$on('$destroy', checkRAValidation);


            //This is for zip5 textbox(We have divided this same method in two parts(one is for streetadddress1 and another is for zip5,we did this
            //because both creating conflicts and had lot impact
            $scope.validateMailingAddress = function (flag,e) {
                  
                $scope.address.isAddressComponentKeyPressed = false;

                $scope.address.invalidZip = false;

                //This condition is to help the method nullCheckAddressCompnent(modal,component) which is presented in service(wacorpService.nullCheckAddressCompnent($scope.modal, $scope[amendedAnnualReportForm]))
                //purpose of this condition is If the user had entered the data and removed the data immediately then no need of any validation which we handle this in service
                if ($scope.address.StreetAddress1 == undefined) {
                    $scope.address.isAddressComponentKeyPressed = true;

                }
                //var x = angular.element(document.getElementById("txtZip5"));
                //var holdZip5=x.val();
                //Zip5 is undefined untill user had given 5 values(max length).When zip5 is undefined we are invoking a validation by using (invalidzip flag)
                if ($scope.address.Zip5 == undefined) {
                    $scope.address.City = '';
                    $scope.address.Zip4 = '';
                    $scope.address.invalidZip = true;
                }
                else {
                    $scope.address.City = angular.copy($scope.address.City);
                    $scope.address.Zip4 = angular.copy($scope.address.Zip4);
                    $scope.address.Zip5 = angular.copy($scope.address.Zip5);
                    $scope.address.invalidZip = false;
                }
                $scope.address.StreetAddress1 = $scope.address.StreetAddress1 ? angular.copy($scope.address.StreetAddress1.trim()) : (($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") ? $scope.address.StreetAddress1 = null : $scope.address.StreetAddress1);

                if ($scope.address.StreetAddress1 && $scope.isAgentAddress) {
                    $scope.businessAddress.ValidAddressCheck.$setValidity("text", true);
                }
                if ($scope.address.StreetAddress1 && $scope.address.Zip5 && $scope.address.Zip4) {
                    $scope.address.Zip4 = "";
                    $scope.isAddressValidated = false;
                }

                if ($scope.isNotNeeded) {
                    return true;
                }

                //This section is validate RA Mailing Address
                if ($scope.isRaMailing != undefined && !$scope.isRaMailing) {
                    if ($scope.businessAddress.Zip5 != undefined && $scope.businessAddress.Zip5 != "" && $scope.businessAddress.Zip5.$viewValue != "")
                        $scope.address.Zip5 = $scope.businessAddress.Zip5.$viewValue;
                    if ($scope.address.StreetAddress1  || $scope.address.Zip5) {
                        $scope.isStreetAddress = false;
                        //$scope.showErrorMessage = true;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }

                //This section is to validate Prinicipal office Mailing Address
                if ($scope.isPoMailing != undefined && $scope.isPoMailing) {
                    if ($scope.businessAddress.Zip5 != undefined && $scope.businessAddress.Zip5 != "" && $scope.businessAddress.Zip5.$viewValue != "")
                        $scope.address.Zip5 = $scope.businessAddress.Zip5.$viewValue;
                    if ($scope.address.StreetAddress1  || $scope.address.Zip5) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                        $scope.showErrorMessage = false;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }

                //!$scope.isNotNeeded
                //This flag is to say no need of any validation because it might have validation alreay ex: Statement of withdrawal filing
                //If we make this flag true in filing level then it wont validate(For any reference check Statement of withdrawal filing)

                //This section is to validate Filing Correspondence Address
                //if (!$scope.isNotNeeded)
                if (($scope.userRegStreetAdd || $scope.userRegMailingAdd) && ($scope.isRafAddress != undefined && $scope.isRafAddress))
                {
                    if ($scope.validateData($scope.address.StreetAddress1) || $scope.validateData($scope.businessAddress.Zip5.$viewValue)|| $scope.validateData($scope.address.City)) {
                        $scope.isStreetAddress = false;
                        $scope.showErrorMessage = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
                else if ($scope.isRafAddress != undefined && $scope.isRafAddress) {
                    if ($scope.validateData($scope.address.StreetAddress1) || $scope.validateData($scope.businessAddress.Zip5.$viewValue)) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                        $scope.showErrorMessage = false;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
                //This is for Commercial Listig Statement
                //if (!$scope.isNotNeeded) {
                if (($scope.isRafAddress != undefined && !$scope.isRaAddress && !$scope.isPoAddress && !$scope.isRafAddress)) {
                    if ($scope.validateData($scope.address.StreetAddress1) || $scope.validateData($scope.businessAddress.Zip5.$viewValue)) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
                //}
                if (flag)
                {
                    //Remove validations if zip5 is empty
                    if (($scope.isPoMailing != undefined && $scope.isPoMailing) || ($scope.isRafAddress != undefined && $scope.isRafAddress))
                    {

                        if (e.key == "Delete" || e.key == "Del" || e.which == 46 || e.which == 8 && ($scope.businessAddress != undefined && $scope.businessAddress.Zip5.$viewValue != undefined && $scope.businessAddress.Zip5.$viewValue.length == 0)) {

                            $scope.address.Zip5 = null;

                            $scope.address.StreetAddress1 = "";

                            $scope.address.StreetAddress2 = '';

                            $scope.address.PostalCode = '';

                            $scope.address.City = '';

                            $scope.RemoveValidationForZip5();

                        }

                        else if (e.key == "Backspace" && ($scope.businessAddress != undefined && $scope.businessAddress.Zip5.$viewValue != undefined && $scope.businessAddress.Zip5.$viewValue.length == 0)) {

                            $scope.address.StreetAddress1 = "";

                            $scope.address.StreetAddress2 = '';

                            $scope.address.PostalCode = '';

                            $scope.address.City = '';

                            $scope.RemoveValidationForZip5();

                        }
                    }
                }
            }



            ////This is for Only street address 1 textbox
            $scope.validateMailingAddressForStreet1 = function () {
                 
                 
                $scope.address.isAddressComponentKeyPressed = false;

                $scope.address.invalidZip = false;

                if (angular.isUndefined($scope.address.Zip5)) {
                    if ($scope.address.Country != "USA")
                        $scope.address.invalidZip = false;
                    else
                       $scope.address.invalidZip = true
                }


                //This condition is to help the method nullCheckAddressCompnent(modal,component) which is presented in service(wacorpService.nullCheckAddressCompnent($scope.modal, $scope[amendedAnnualReportForm]))
                //purpose of this condition is If the user had entered the data and removed the data immediately then no need of any validation which we handle this in service
                if ($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "" || $scope.address.StreetAddress1 == null) {
                    $scope.address.isAddressComponentKeyPressed = true;
                    //When there is not data in streetaddress1 then we are removing zip5 and zip4 becausing that are creating lot of mess and we are making zip5 validation false
                    $scope.address.invalidZip = false;
                    $scope.address.Zip5 = '';
                    $scope.address.Zip4 = '';
                    $scope.address.City = '';
                    $scope.address.StreetAddress2 = '';
                    $scope.address.PostalCode = '';
                    $scope.address.OtherState = '';
                    $scope.address.isRAStreetAddressValid = false;
                }

                //********
                var poboxData = $scope.businessAddress.StreetAddress1.$viewValue;
                var boolValuse = false;
                var address = new Array("po box", "pobox", "post office box", "post office", "p.o.box", "p.o. box", "p o box", "p. o. box", "po. box", "box", "p. o box", "pmb", "p.m.b", "p m b", "private mailbox", "private mail box");
                if (poboxData) {
                    angular.forEach(address, function (key, data) {
                        var patt = new RegExp("^(" + key + ")$|^(" + key + ")\\W|\\W(" + key + ")\\W|\\W(" + key + ")$");
                        var flg = patt.test(poboxData.toLowerCase());
                        //var flg = address.indexOf(poboxData.toLowerCase());
                        if (flg) {
                            boolValuse = true;
                            $scope.address.StreetAddress1 = poboxData;
                        }
                    });
                }
                //*******
                $scope.address.StreetAddress1 = $scope.address.StreetAddress1 ? angular.copy($scope.address.StreetAddress1.trim()) : (($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") ? $scope.address.StreetAddress1 = null : $scope.address.StreetAddress1);

                //$scope.address.Zip5 = $scope.address.Zip5 ? angular.copy($scope.address.Zip5.trim()) : (($scope.address.Zip5 == undefined || $scope.address.Zip5 == "") ? $scope.address.Zip5 = null : $scope.address.Zip5);
                //$scope.address.Zip4 = $scope.address.Zip4 ? angular.copy($scope.address.Zip4.trim()) : (($scope.address.Zip4 == undefined || $scope.address.Zip4 == "") ? $scope.address.Zip4 = null : $scope.address.Zip4);
                //    if ($scope.address.StreetAddress1 && $scope.isAgentAddress && !$scope.address.Zip5) {
                //        $scope.businessAddress.ValidAddressCheck.$setValidity("text", true);
                //    }
                //else {
                //      $scope.isValidAddressForZip = false;
                //    }

                if ($scope.address.StreetAddress1 && $scope.address.Zip5 && $scope.address.Zip4) {
                    $scope.address.Zip4 = "";
                    $scope.isAddressValidated = false;
                }

                if ($scope.isNotNeeded) {
                    return true;
                }

                //This section is validate RA Mailing Address
                if ($scope.isRaMailing != undefined && !$scope.isRaMailing) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        //$scope.showErrorMessage = true;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                        //to remove RA Mailing address alert when no address is present.
                        $scope.address.IsInvalidState = false;
                    }
                }

                //This section is to validate Prinicipal office Mailing Address
                if ($scope.isPoMailing != undefined && $scope.isPoMailing) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }


                //!$scope.isNotNeeded
                //This flag is to say no need of any validation because it might have validation alreay ex: Statement of withdrawal filing
                //If we make this flag true in filing level then it wont validate(For any reference check Statement of withdrawal filing)

                //This section is to validate Filing Correspondence Address
                //if (!$scope.isNotNeeded)
                if ($scope.isRafAddress != undefined && $scope.isRafAddress) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
                //This is for Commercial Listig Statement
                //if (!$scope.isNotNeeded) {
                if (($scope.isRafAddress != undefined && !$scope.isRaAddress && !$scope.isPoAddress && !$scope.isRafAddress)) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
                //}

            }



            //to check RA mailing Address contains any data to fire validations.
            $scope.validateRAMailingAddress = function () {
                //This section is validate RA Mailing Address
                if ($scope.isRaMailing != undefined && !$scope.isRaMailing) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        if ($scope.isAcpAddress) {
                            $scope.isStreetAddress = true;
                            $scope.showvalidationMessage = false;
                            $scope.address.IsInvalidState = false;
                        }
                        else {
                            $scope.isStreetAddress = false;
                        }
                        //$scope.showErrorMessage = true;
                        //$scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                        //to remove RA Mailing address alert when no address is present.
                        $scope.address.IsInvalidState = false;
                    }
                }
            };

            //to check RA mailing Address contains any data to fire validations.
            $scope.validateRAMailingAddress = function () {
                //This section is validate RA Mailing Address
                if ($scope.isRaMailing != undefined && !$scope.isRaMailing) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        if ($scope.isAcpAddress) {
                            $scope.isStreetAddress = true;
                            $scope.showvalidationMessage = false;
                            $scope.address.IsInvalidState = false;
                        }
                        else {
                            $scope.isStreetAddress = false;
                        }
                        //$scope.showErrorMessage = true;
                        //$scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                        //to remove RA Mailing address alert when no address is present.
                        $scope.address.IsInvalidState = false;
                    }
                }
            };

            //This is for Only City textbox
            $scope.validateMailingAddressForCity = function (e) {
                  
                $scope.address.isAddressComponentKeyPressed = false;

                $scope.address.invalidZip = false;


                if ($scope.address.City == "") {
                    if ($scope.address.StreetAddress1 == undefined && $scope.address.Zip5 == undefined)
                    {
                        $scope.address.invalidZip = false;
                    }
                    else if ($scope.address.Zip5 == undefined) {
                        $scope.address.invalidZip = true
                    }
                }

                //$scope.address.StreetAddress1 = $scope.address.StreetAddress1 ? angular.copy($scope.address.StreetAddress1.trim()) : (($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") ? $scope.address.StreetAddress1 = null : $scope.address.StreetAddress1);

                if ($scope.isMandatory != undefined && $scope.isMandatory)
                { }
                else if (($scope.isRaMailing != undefined && !$scope.isRaMailing) || ($scope.isPoMailing != undefined && $scope.isPoMailing) || ($scope.isRafAddress != undefined && $scope.isRafAddress)) {
                    if ($scope.businessAddress != undefined && $scope.businessAddress.City.$viewValue != undefined && $scope.businessAddress.City.$viewValue.length == 0 && $scope.address.City == undefined) {
                        if (e.key == "Backspace" || e.key == "Delete" || e.key == "Del" || e.which == 46 || e.which == 8)
                            $scope.RemoveRAPOMAilingValidations();
                    }
                    else if (($scope.isPoMailing != undefined && $scope.isPoMailing) || ($scope.isRafAddress != undefined && $scope.isRafAddress)) {
                        if ($scope.address.Country == "USA") {
                            if ($scope.businessAddress != undefined && $scope.businessAddress.City.$viewValue != undefined && $scope.businessAddress.City.$viewValue.length == 0 && $scope.address.City == undefined) {

                                $scope.RemoveRAPOMAilingValidations();
                            }
                        }

                        else if ($scope.address.Country != "USA" && $scope.address.Country != "CAN") {

                            if (($scope.businessAddress != undefined) && ($scope.businessAddress.City.$viewValue != undefined && $scope.businessAddress.City.$viewValue.length == 0 && $scope.address.City == undefined)) {
                                if (e.key == "Backspace" || e.key == "Delete" || e.key == "Del" || e.which == 46 || e.which == 8)
                                    $scope.RemoveRAPOMAilingValidations();
                            }
                        }

                        else if ($scope.address.Country == "CAN") {
                            if (($scope.businessAddress != undefined) && ($scope.businessAddress.City.$viewValue != undefined && $scope.businessAddress.City.$viewValue.length == 0 && $scope.address.City == undefined)) {
                                if (e.key == "Backspace" || e.key == "Delete" || e.key == "Del" || e.which == 46 || e.which == 8)
                                    $scope.RemoveRAPOMAilingValidations();
                            }
                        }
                    }
                }
                else {
                    $scope.address.isRAStreetAddressValid = false;
                }

                $scope.address.City = $scope.address.City ? angular.copy($scope.address.City.trim()) : (($scope.address.City == undefined || $scope.address.City == "") ? $scope.address.City = null : $scope.address.City);

                //This condition is to help the method nullCheckAddressCompnent(modal,component) which is presented in service(wacorpService.nullCheckAddressCompnent($scope.modal, $scope[amendedAnnualReportForm]))
                //purpose of this condition is If the user had entered the data and removed the data immediately then no need of any validation which we handle this in service
                if ($scope.address.StreetAddress1 == undefined) {
                    $scope.address.isAddressComponentKeyPressed = true;

                }

                if ($scope.address.StreetAddress1 && $scope.isAgentAddress) {
                    $scope.businessAddress.ValidAddressCheck.$setValidity("text", true);
                }
                if (!$scope.address.StreetAddress1 && !$scope.address.Zip5) {
                    $scope.address.Zip4 = "";
                    //$scope.isAddressValidated = false;
                }

                if ($scope.isNotNeeded) {
                    return true;
                }

                //This section is validate RA Mailing Address
                if ($scope.isRaMailing != undefined && !$scope.isRaMailing) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        //$scope.showErrorMessage = true;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                        $scope.address.IsInvalidState = false;
                    }
                }

                //This section is to validate Prinicipal office Mailing Address
                if ($scope.isPoMailing != undefined && $scope.isPoMailing) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }


                //!$scope.isNotNeeded
                //This flag is to say no need of any validation because it might have validation alreay ex: Statement of withdrawal filing
                //If we make this flag true in filing level then it wont validate(For any reference check Statement of withdrawal filing)

                //This section is to validate Filing Correspondence Address
                //if (!$scope.isNotNeeded)
                if ($scope.isRafAddress != undefined && $scope.isRafAddress) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
                //This is for Commercial Listig Statement
                //if (!$scope.isNotNeeded) {
                if (($scope.isRafAddress != undefined && !$scope.isRaAddress && !$scope.isPoAddress && !$scope.isRafAddress)) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = false;
                        $scope.showvalidationMessage = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
                //}
            }

            $scope.RemoveRAPOMAilingValidations = function () {
                 
                $scope.address.isAddressComponentKeyPressed = true;

                $scope.address.invalidZip = false;

                $scope.address.Zip5 = "";

                $scope.address.Zip4 = "";

                $scope.address.City = "";

                $scope.address.StreetAddress1 = "";

                $scope.address.StreetAddress2 = "";

                $scope.address.PostalCode = "";

                $scope.address.OtherState = "";

                $scope.address.isRAStreetAddressValid = false;

            };
            $scope.validateZip = function () {
                $scope.isValidAddressForZip = false;
            }

            //call the method when Same as Street Address checkbox is checked in RA.
            $scope.setValidation = function (flag,agentData) {
                   
                  $scope.isCheckBoxChecked = flag;
                  if ($scope.isCheckBoxChecked)
                  {
                      if ($scope.address.StreetAddress1 == "" || $scope.address.StreetAddress1 == null || $scope.address.StreetAddress1 == undefined)
                      {
                          if (agentData.MailingAddress.StreetAddress1!="" && agentData.MailingAddress.StreetAddress1!=undefined && agentData.MailingAddress.StreetAddress1!="")
                              $scope.address = agentData.MailingAddress;
                      }
                           
                  }
                  else if ($scope.isCheckBoxChecked != undefined && $scope.isCheckBoxChecked != null && !$scope.isCheckBoxChecked)
                  {
                      if ($scope.address.StreetAddress1 == "" || $scope.address.StreetAddress1 == null || $scope.address.StreetAddress1 == undefined)
                      {
                          if (agentData.MailingAddress.StreetAddress1 != "" && agentData.MailingAddress.StreetAddress1 != undefined && agentData.MailingAddress.StreetAddress1 != "")
                              $scope.address = agentData.MailingAddress;
                      }
                  }
                $scope.address.isAddressComponentKeyPressed = false;

                //$scope.address.invalidZip = false;

                //if (angular.isUndefined($scope.address.Zip5)) {
                //    $scope.address.invalidZip = true
                //}

                if ($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") {
                    $scope.address.isAddressComponentKeyPressed = true;
                    //When there is not data in streetaddress1 then we are removing zip5 and zip4 becausing that are creating lot of mess and we are making zip5 validation false
                    $scope.address.invalidZip = false;
                    $scope.address.Zip5 = '';
                    $scope.address.Zip4 = '';
                    $scope.address.City = '';
                }

                //11/30/2018
                if ($scope.isRaMailing != undefined && !$scope.isRaMailing) {
                    if ($scope.isCheckBoxChecked) {
                        if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                            $scope.isStreetAddress = true;
                            $scope.showvalidationMessage = false;
                        }
                        else {
                            $scope.isStreetAddress = true;
                            $scope.showvalidationMessage = false;
                            //to remove RA Mailing address alert when no address is present.
                            $scope.address.IsInvalidState = false;
                        }
                    }
                    else {
                        if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                            $scope.isStreetAddress = false;
                            $scope.showvalidationMessage = true;
                        }
                        else {
                            $scope.isStreetAddress = true;
                            $scope.showvalidationMessage = false;
                            //to remove RA Mailing address alert when no address is present.
                            $scope.address.IsInvalidState = false;
                        }
                    }
                }
            }

            //call the method when Same as Street Address checkbox is checked in Principal Office.
            $scope.RemovePoValidation = function (flag) {

                $scope.isPOMailingChecked = flag;

                $scope.address.isAddressComponentKeyPressed = false;

                $scope.address.invalidZip = false;


                if (angular.isUndefined($scope.address.Zip5)) {
                    $scope.address.invalidZip = true
                }

                if ($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") {
                    $scope.address.isAddressComponentKeyPressed = true;
                    //When there is not data in streetaddress1 then we are removing zip5 and zip4 becausing that are creating lot of mess and we are making zip5 validation false
                    $scope.address.invalidZip = false;
                    $scope.address.Zip5 = '';
                    $scope.address.Zip4 = '';
                    $scope.address.City = '';
                }
                //This section is to validate Prinicipal office Mailing Address
                if ($scope.isPoMailing != undefined && $scope.isPoMailing) {
                    if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showvalidationMessage = false;
                    }
                }
            }

            $scope.changeState = function () {
                $rootScope.$broadcast("InvokeServiceAddress");
                $scope.clearPOMailingAddress();
            }

            $scope.initPo = function () {
                     
                    if ($scope.isMandatory!=undefined && $scope.isMandatory)//Correspondence Address mandatory for specific filings
                    { }
                    else
                    {
                        if ($scope.isPoMailing || $scope.isRafAddress) {
                            if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                                if ($scope.isAcpAddress) {
                                    $scope.isStreetAddress = true;
                                    $scope.showvalidationMessage = false;
                                    $scope.address.IsInvalidState = false;
                                }
                                else {
                                    $scope.isStreetAddress = false;
                                    //$scope.showvalidationMessage = true;
                                }
                            }
                            else {
                                $scope.isStreetAddress = true;
                                $scope.showvalidationMessage = false;
                            }
                        }

                        if ($scope.userRegMailingAdd != undefined && $scope.userRegMailingAdd) {
                            if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                                $scope.isStreetAddress = false;
                                //$scope.showvalidationMessage = true;
                            }
                            else {
                                $scope.isStreetAddress = true;
                                $scope.showvalidationMessage = false;
                            }
                        }
                            //This section is to validate Filing Correspondence Address
                        else if ($scope.isRafAddress != undefined && $scope.isRafAddress) {
                            if ($scope.address.StreetAddress1 || $scope.address.Zip5 || $scope.address.City) {
                                $scope.isStreetAddress = false;
                                //$scope.showvalidationMessage = true;
                            }
                            else {
                                $scope.isStreetAddress = true;
                                $scope.showvalidationMessage = false;
                            }
                        }
                    }
                 
            };
            $scope.clearPOMailingAddress = function () {
                if ($scope.isPoMailing != undefined && $scope.isPoMailing != null && !$scope.isPoMailing) {
                    $rootScope.$broadcast("ClearPOMailingAddress");
                }
            };
            
            $scope.clearRAAddress = function (flag, value, user, commercialStatement) {
                 
                if (flag) {
                    if (!commercialStatement)
                        $rootScope.$broadcast("ClearRAStreetAddress");
                    else 
                        $rootScope.$broadcast("clearCSCRAMailingAddress");
                  }
                else if (value) {
                    //commercial Listing filing
                    $rootScope.$broadcast("CommercialRAStreetAddress");
                    }
                else if (user) {
                    //User Account Registration
                $rootScope.$broadcast("clearUserRAStreetAddressOnChange");
                }
                else if (commercialStatement) {
                    //commercial Statement of change
                    $rootScope.$broadcast("clearCSCRAMailingAddress");
                }
            };

            $scope.validateData = function (data) {
                if (data != null && data != undefined && data != "")
                    return true;
                else
                    return false;

            }
        }
    };
});

wacorpApp.directive('entityName', function () {
    return {
        templateUrl: 'ng-app/directives/entityName/EntityName.html',
        restrict: 'A',
        scope: {
            entity: '=?entity',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, $timeout, lookupService, $rootScope) {
            if ($scope.entity.businessNames) {
                $scope.entity.businessNames.length = 0;
            }
            $scope.businessNameNotAvailCount = 0;

            if ($rootScope.transactionID || $rootScope.isIncompleteFiling) {
                $timeout(function () {
                    $scope.entity.isBusinessNameAvailable = false;
                    $scope.entity.isDBANameAvailable = false;
                    $rootScope.isIncompleteFiling = false;
                    $rootScope.transactionID = '';
                }, 2000);
            }

            $scope.NameChanged = false;
            $scope.messages = messages;
            $scope.entity = $scope.entity || {};
            $scope.entity.NameReservedId = $scope.entity.NameReservedId == constant.ZERO ? null : $scope.entity.NameReservedId;
            $scope.entity.isBusinessNameAvailable = $scope.entity.Indicator.IsValidEntityName;
            var entityScope = { Indicators: [], IndicatorsCSV: null, ID: constant.ZERO, BusinessTypeID: constant.ZERO, Note: null, IsValidEntityName: false, IsValidDBAName: false, IndicatorsDisplay: null, PSIndicatorsDisplay: null };
            $scope.entity.Indicator = $scope.entity.Indicator ? angular.extend(entityScope, $scope.entity.Indicator) : entityScope;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.CheckforLookUp = true;
            // $scope.entity.isBusinessReserved = $scope.entity.isBusinessReserved || false;
            $scope.entity.oldBusinessName = angular.copy($scope.entity.BusinessName || '');
            $scope.GetReservedBusiness = function (EntityName) {
                $scope.validateReservedName = true;
                if ($scope[EntityName].ReservedName.$valid) {
                    $scope.validateReservedName = false;
                    var config = {
                        params: { registrationID: parseInt($scope.entity.NameReservedId) }
                    };
                    // GetReservedBusiness method is available in constants.js
                    wacorpService.get(webservices.Common.GetReservedBusiness, config, function (response) {
                        if (response.data.BusinessName != null) {
                            $scope.entity.BusinessName = response.data.BusinessName;
                            $scope.entity.BusinessID = response.data.BusinessID;
                            $scope.entity.NameReservedId = response.data.BusinessID;
                            $scope.entity.isBusinessNameAvailable = true;
                            $scope.entity.BusinessIndicator = response.data.BusinessIndicator;
                        }
                        else {
                            //$scope.entity.BusinessName = null;
                          //  $scope.entity.BusinessID = constant.ZERO;
                            //$scope.entity.NameReservedId = null;
                            // Folder Name: app Folder
                            // Alert Name: noReservedName method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.EntityName.noReservedName);
                        }
                    }, function (response) {
                        // Folder Name: app Folder
                        // Alert Name: noReservedName method is available in alertMessages.js
                        wacorpService.alertDialog($scope.messages.EntityName.noReservedName);
                    });
                }
            };

            $scope.GetReservedBusinessClear = function (EntityName) {
                if ($scope[EntityName].ReservedName.$valid) {
                    $scope.entity.BusinessName = "";
                    $scope.entity.BusinessID = "";
                }
            };

            $scope.isValidIndicator = function (isLookup,flag) {
                //if (entity.IsDBAInUse) return;
                $scope.entity.IsDBAInUse = false;
                //$scope.entity.BusinessIndicator = '';
                var indicatorsCSV = null;
                var indicatorslist = null;
                var indicatorsMustNotCSV = null;
                var IndicatorsDisplay = null;
                indicatorsMustNotCSV = $scope.entity.Indicator.IndicatorsMustNotCSV;
                // is dental service checked true
                if ($scope.entity.Indicator.isDentalCheck) {
                    indicatorsCSV = $scope.entity.Indicator.PSIndicatorsCSV;
                    indicatorslist = $scope.entity.Indicator.PSIndicatorList;
                    indicatorsDisplay = $scope.entity.Indicator.PSIndicatorsDisplay;
                }
                else {
                    indicatorsCSV = $scope.entity.Indicator.IndicatorsCSV;
                    indicatorslist = $scope.entity.Indicator.Indicators;
                    indicatorsDisplay = $scope.entity.Indicator.IndicatorsDisplay;
                }
                var isValid = constant.ZERO;
                var isInValidIndicator = constant.ZERO;
                var entityName;

                if ($scope.entity.isUpdate != undefined && $scope.entity.isUpdate && $scope.entity.isUpdate != false) {
                    entityName = $scope.entity.BusinessName + ' ' + indicatorsCSV;
                    entityName = entityName.toLowerCase().replace(/[{|}|(|)|-|;|'|\"]/g, '');
                }
                else {
                    entityName = $scope.entity.BusinessName != null ? $scope.entity.BusinessName.toLowerCase().replace(/[{|}|(|)|-|;|'|\"]/g, '') : null;
                }

                if (indicatorsCSV != null && indicatorsCSV != undefined && indicatorsCSV != '') {
                    angular.forEach(indicatorslist, function (value) {
                        value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                        //isValid = new RegExp("^" + value + "\\s").test(entityName) ? isValid + constant.ONE : isValid;
                        // Start With indicator
                        if (new RegExp("^" + value + "\\s").test(entityName)) {
                            if (entityName.indexOf(value + ' ') != -1) {
                                isValid = isValid + constant.ONE;
                                return;
                            }
                        }
                    });

                    if (isValid == constant.ZERO) {
                        angular.forEach(indicatorslist, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            //isValid = new RegExp("\\s" + value + "\\s").test(entityName) ? isValid + constant.ONE : isValid;
                            // Middile With indicator
                            if (new RegExp("\\s" + value + "\\s").test(entityName)) {
                                if (entityName.indexOf(' ' + value + ' ') != -1) {
                                    isValid = isValid + constant.ONE;
                                    return;
                                }
                            }
                        });
                    }

                    if (isValid == constant.ZERO) {
                        angular.forEach(indicatorslist, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                           // isValid = new RegExp("\\s" + value + "$").test(entityName) ? isValid + constant.ONE : isValid;
                            // Last With indicator
                            if (new RegExp("\\s" + value + "$").test(entityName)) {
                                if (entityName.indexOf(' ' + value) != -1) {
                                    isValid = isValid + constant.ONE;
                                    return;
                                }
                            }
                        });
                    }
                }
                else {
                    isValid = constant.ONE; //For all entities we are not going to have Indicators, that's the reason default we are considering as true.
                }

                if (indicatorsMustNotCSV != null && indicatorsMustNotCSV != undefined && indicatorsMustNotCSV != '') {
                    var isNonCorp = false;
                    var aNonprofitCorp = "a nonprofit corporation";
                    var aNonprofitMutualCorp = "a nonprofit mutual corporation";
                    var corporation = "corporation";

                    if (entityName != "" && entityName != null) {
                        isNonCorp = new RegExp("^" + aNonprofitCorp + "\\s").test(entityName) || new RegExp("^" + aNonprofitMutualCorp + "\\s").test(entityName);

                        if (!isNonCorp) {
                            isNonCorp = new RegExp("\\s" + aNonprofitCorp + "\\s").test(entityName) || new RegExp("\\s" + aNonprofitMutualCorp + "\\s").test(entityName);
                        }
                        if (!isNonCorp) {
                            isNonCorp = new RegExp("\\s" + aNonprofitCorp + "$").test(entityName) || new RegExp("\\s" + aNonprofitMutualCorp + "$").test(entityName);
                        }
                    }

                    var indicatorsMustNot = indicatorsMustNotCSV.toLowerCase().split(',');
                    angular.forEach(indicatorsMustNot, function (value) {
                        value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                        if (isNonCorp && value == corporation) {
                            isInValidIndicator = constant.ZERO;
                        }
                        else {
                            //isInValidIndicator = new RegExp("^" + value + "\\s").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                            // Start With indicator
                            if (new RegExp("^" + value + "\\s").test(entityName)) {
                                if (entityName.indexOf(value + ' ') != -1) {
                                    isInValidIndicator = isInValidIndicator + constant.ONE;
                                    return;
                                }
                            }
                        }
                    });

                    if (isInValidIndicator == constant.ZERO) {
                        angular.forEach(indicatorsMustNot, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            if (isNonCorp && value == corporation) {
                                isInValidIndicator = constant.ZERO;
                            }
                            else {
                                // isInValidIndicator = new RegExp("\\s" + value + "\\s").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                                // Middile With indicator
                                if (new RegExp("\\s" + value + "\\s").test(entityName)) {
                                    if (entityName.indexOf(' ' + value + ' ') != -1) {
                                        isInValidIndicator = isInValidIndicator + constant.ONE;
                                        return;
                                    }
                                }
                            }
                        });
                    }

                    if (isInValidIndicator == constant.ZERO) {
                        angular.forEach(indicatorsMustNot, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            if (isNonCorp && value == corporation) {
                                isInValidIndicator = constant.ZERO;
                            }
                            else {
                                // isInValidIndicator = new RegExp("\\s" + value + "$").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                                // Last With indicator
                                if (new RegExp("\\s" + value + "$").test(entityName)) {
                                    if (entityName.indexOf(' ' + value) != -1) {
                                        isInValidIndicator = isInValidIndicator + constant.ONE;
                                        return;
                                    }
                                }
                            }
                        });
                    }
                }
                 
                var dbaInvalidMsg = "";
                if (isInValidIndicator >= 1) {
                    $scope.indicatorValidMessage = "The business name contains an invalid indicator like (" + indicatorsMustNotCSV.replace(/,/g, ', ').toUpperCase() + ").";
                    dbaInvalidMsg = $scope.messages.EntityName.UseDBANameForMustNotIndicator;
                }
                else {
                    if ($scope.entity.BusinessName != null && $scope.entity.BusinessName != "") {
                        $scope.indicatorValidMessage = isValid > constant.ZERO ? "" : "The business name requested does not contain the necessary designation. Please input one of the required designations (" + indicatorsDisplay.replace(/,/g, ', ').toUpperCase() + ").";// TFS ID 12017

                        dbaInvalidMsg = $scope.messages.EntityName.UseDBANameForIndicator;

                        if ($scope.entity.oldBusinessName != $scope.entity.BusinessName) {
                            $scope.entity.isBusinessNameAvailable = false;
                            if (!isLookup && $scope.entity.businessNames)
                                $scope.entity.businessNames.length = 0;
                        }

                        if ($scope.availableBusinessCount() > constant.ZERO)
                        {
                            $scope.entity.isBusinessNameAvailable = false;
                        }

                        if ($scope.entity.oldBusinessName == $scope.entity.BusinessName) {
                            $scope.entity.isBusinessNameAvailable = true;

                            $scope.entity.Indicator.IsValidEntityName = true;
                        }
                    }
                    else {
                        $scope.indicatorValidMessage = $scope.entity.isBusinessNameAvailable = "";
                    }

                    if (!flag)
                    {
                        $scope.CheckforLookUp = true;
                    }
                }

                // validate and show alert to continue with DBA 
                $scope.entity.IsDBASectionExist = (lookupService.canShowScreenPart($scope.entity.AllScreenParts.DbaName, $scope.entity, $scope.entity.BusinessTypeID)) ? true : false

                if ($scope.entity.IsDBASectionExist && $scope.isContinueDBA == undefined) {
                    $scope.isContinueDBA = false;
                }
                else if ($scope.entity.IsDBASectionExist && isLookup) {
                    $scope.isContinueDBA = false;
                }

                if ($scope.indicatorValidMessage && $scope.entity.IsDBASectionExist && !$scope.isContinueDBA)
                {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.confirmDialog(dbaInvalidMsg,
                        function () {
                            $scope.entity.IsDBAInUse = true;
                            if (flag != undefined && flag != null && flag != "" && flag)
                            {
                                $scope.entity.DBABusinessName = $scope.entity.DBABusinessName;
                                //$scope.entity.isDBANameAvailable = true;
                                $scope.entity.isBusinessNameAvailable =true;
                                 $scope.CheckforLookUp = true;
                            }
                            else
                               $scope.entity.DBABusinessName = $scope.entity.OldDBABusinessName;//$scope.oldDBAName;
                            $scope.CheckforLookUp = false;
                        },
                        function () {
                            $scope.entity.IsDBAInUse = false;
                            $scope.entity.OldDBABusinessName = $scope.entity.DBABusinessName;
                            $scope.entity.DBABusinessName = '';
                            $scope.isContinueDBA = false;
                        }
                    );
                }
                else if ($scope.entity.IsDBASectionExist && $scope.entity.IsDBAInUse) {
                    $scope.entity.IsDBAInUse = false;
                    $scope.entity.OldDBABusinessName = $scope.entity.DBABusinessName;
                    $scope.entity.DBABusinessName = '';
                    $scope.entity.isBusinessNameAvailable = false;//$scope.messages.EntityName.businessNameAvaibilityCheck;
                }
                else {
                    $scope.isContinueDBA = false;
                }
            };

            $scope.searchBusinessNames = function (EntityName) {
                $scope.entity.isBusinessNameAvailable = "";
                $scope.NameChanged = false;
                $scope.entity.oldBusinessName = $scope.entity.BusinessName;
                $scope.validateBusinessName = true;
                $scope.businessNameNotAvailCount = 0;
               
                var config = { params: { businessName: $scope.entity.BusinessName } };
                // GetEntityNameCleanUp method is available in constants.js
                wacorpService.get(webservices.Common.GetEntityNameCleanUp, config, function (data, response) {
                    $rootScope.NewEntityNameCleanUp = data.data;

                }, function (response) {
                    console.log(response);
                });

                if ($scope[EntityName].txtBusiessName.$valid) {
                    $scope.entity.hdnBusinessName = $scope.entity.BusinessName;
                    $scope.validateBusinessName = false;
                    var config = {
                        params: { businessName: $scope.entity.BusinessName,isInhouse:false,businessId: angular.isNullorEmpty($scope.entity.BusinessID) ? 0 : $scope.entity.BusinessID }
                    };
                    // GetBusinessNames method is available in constants.js
                    wacorpService.get(webservices.Common.GetBusinessNames, config, function (response) {
                        $scope.entity.businessNames = response.data;
                        $scope.entity.isBusinessNameAvailable = false;
                        angular.forEach($scope.entity.businessNames, function (item, index) {
                            if (item.AvailableStatus == "Available") {
                                $scope.entity.isBusinessNameAvailable = true;
                                $scope.entity.IsDBAInUse = false;
                                $scope.entity.DBABusinessName = '';
                                $scope.businessNameNotAvailCount = 0;
                                $scope.CheckforLookUp = false;
                            }
                            else if (item.AvailableStatus == "Not Available") {
                                $scope.businessNameNotAvailCount = 1;
                                $scope.CheckforLookUp = false;
                            }
                        });

                        //TFS ticket 
                        // Service Folder: services
                        // File Name: lookupService.js (you can search with file name in solution explorer)
                        $scope.entity.IsDBASectionExist = (lookupService.canShowScreenPart($scope.entity.AllScreenParts.DbaName, $scope.entity, $scope.entity.BusinessTypeID)) ? true : false
                        
                        if (!$scope.entity.isBusinessNameAvailable && $scope.entity.IsDBASectionExist ) {
                            // Folder Name: app Folder
                            // Alert Name: UseDBAName method is available in alertMessages.js 
                            wacorpService.confirmOkCancel($scope.messages.EntityName.UseDBAName,
                                  function () {
                                      $scope.entity.IsDBAInUse = true;
                                      $scope.entity.DBABusinessName = $scope.entity.DBABusinessName ? $scope.entity.DBABusinessName : $scope.entity.OldDBABusinessName;
                                  },
                                  function () {
                                      $scope.entity.IsDBAInUse = false;
                                      $scope.entity.OldDBABusinessName = $scope.entity.DBABusinessName;
                                      $scope.entity.DBABusinessName = '';
                                  }
                                  );
                        }

                        //$scope.entity.UBINumber = ((response.UBINumber == "" || response.UBINumber == null || response.UBINumber == undefined) ? "" : response.UBINumber);
                        //$scope.entity.isBusinessNameAvailable = $scope.availableBusinessCount() > 0;
                        $scope.entity.Indicator.IsValidEntityName = $scope.entity.isBusinessNameAvailable;
                        if ($scope.entity.isBusinessNameAvailable && $scope.entity.IsDBASectionExist) {
                            $scope.isValidIndicator(true); // isValidIndicator method is available in this file only.
                        }
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
            };

            $scope.selectBusiness = function (businessName) {
                $scope.entity.BusinessName = businessName;
            };

            $scope.resetOnReserveClick = function () {
                $scope.entity.DontShowMessage = false;
                //$scope.entity.BusinessIndicator = '';
                if ($scope.entity.IsNameReserved) {
                    $scope.entity.hdnBusinessName = $scope.entity.BusinessName;
                    $scope.entity.BusinessName = '';
                    $scope.indicatorValidMessage = '';
                    $scope.entity.isBusinessNameAvailable = '';
                    $scope.validateBusinessName = '';
                    $scope.entity.businessNames = [];
                    //Newly added as per ticket 44757
                    $scope.entity.IsDBAInUse = false;
                    $scope.entity.DBABusinessName = '';
                    $scope.entity.DontShowMessage = true;
                }
                else {
                    $scope.entity.NameReservedId = '';
                    $scope.indicatorValidMessage = '';
                    $scope.entity.isBusinessNameAvailable = '';
                    $scope.validateReservedName = '';
                    $scope.entity.DBABusinessName = $scope.entity.hdnDBABusinessName;
                    $scope.entity.BusinessName = $scope.entity.hdnBusinessName;
                    $scope.entity.DontShowMessage = true;
                    $scope.entity.BusinessIndicator = '';
                    $scope.entity.IsNameReservedChecked = false;
                }
            };

            //Old code to Check Business name count 
            //$scope.availableBusinessCount = function () {
            //    if ($scope.entity.businessNames == undefined || $scope.entity.businessNames == null) {
            //        return constant.ZERO;
            //    }
            //    else {
            //        var availableBusinessList = $scope.entity.businessNames.filter(function (name) {
            //            return (name.IsAvailable || name.IsOrgBusinessName);
            //        });
            //        return availableBusinessList.length;
            //    }
            //};

            //New code to Check Business name count 
            // check business count availability
            $scope.availableBusinessCount = function () {
                if ($scope.entity.businessNames == undefined || $scope.entity.businessNames == null) {
                    return 0;
                }
                else {

                    var availableBusinesscount = 0;

                    for (var index in $scope.entity.businessNames) {
                        if ($scope.entity.businessNames[index].AvailableStatus == "Available") {
                            availableBusinesscount++;
                            break;
                        }
                    }
                    return availableBusinesscount;
                }
            };

            // Reservation Number stop the alphanumeric text
            $scope.setPastedReservednumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 15);
                    $scope.entity.NameReservedId = pastedText;
                    $scope.checkValue($scope.entity.NameReservedId); // checkValue method is available in this file only.
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 15);
                        $scope.entity.NameReservedId = pastedText;
                    });
                }
            };

            // Check the value
            $scope.checkValue = function (value, id) {
                if (value != "" && value != undefined && value.length > 0) {
                    $scope.formValid = true;
                }
                else
                    $scope.formValid = false;

                //$('#'+id).focus();
            };

            //$scope.isValidIndicator();

            $scope.$watch('entity.BusinessName', function (newValue, oldValue) {
                if (newValue != oldValue) {
                    $scope.NameChanged = angular.equals($scope.project, $scope.original);
                    if ($scope.NameChanged) {
                        $scope.CheckforLookUp = !$scope.entity.IsNameReserved && !$scope.entity.IsDBAInUse;
                    }
                }
                else {
                    $scope.NameChanged = false;
                }
            }, true);

            var checkIndicatorValidation = $scope.$on("checkIndicator", function (evt, data) {
                $scope.isContinueDBA = true;
                $scope.isValidIndicator();
            });

            $scope.$on('$destroy', checkIndicatorValidation);
            // OSOS ID--3270 Foreign UBIs > Register and Requalification allows Active UBIs 
            var checkBusinessNameLookUp = $scope.$on("InvokeBusinessNameLookUp", function (evt, data) {
                $scope.isValidIndicator(null,data);
            });

            $scope.$on('$destroy', checkBusinessNameLookUp);
        },
    };
});
wacorpApp.directive('registerAgent', function () {
    return {
        templateUrl: 'ng-app/directives/RegisterAgent/RegisteredAgent.html',
        restrict: 'A',
        scope: {
            agent: '=?agent',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            businessType: '=?businessType',
            isFormation: '=?isFormation',
            sectionName: '=?sectionName',
            isConsentShow: '=?isConsentShow',
            entity: '=?entity',
            isAgentEditShow: '=?isAgentEditShow',
        },
        controller: function ($scope, wacorpService, $rootScope, $timeout) {
            $scope.messages = messages;
            $scope.page = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.isReview = $scope.isReview || false;
            $scope.isConsentShow = $scope.isConsentShow || true;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.search = getAgentList;
            $scope.businessType = $scope.businessType || '';
            $scope.isFormation = $scope.isFormation || '';
            $scope.isAgentEditShow = $scope.isAgentEditShow || false;
            //$scope.IsNonCommercial = true;
            $scope.showRAHyperLink = false;
            $scope.isCRALogin = false;
            $scope.sectionName = angular.isNullorEmpty($scope.sectionName) ? "" : $scope.sectionName;
            $scope.removeWA = false;
            $scope.agent.StreetAddress.isValidAddressForZip = $scope.agent.StreetAddress.isValidAddressForZip || false;
            $scope.agent.MailingAddress.isValidAddressForZip = $scope.agent.MailingAddress.isValidAddressForZip || false;

            if ($scope.agent) {
                $scope.agent.AgentType = angular.isNullorEmpty($scope.agent.AgentType) ? "I" : $scope.agent.AgentType;
                $scope.agent.StreetAddress.StreetAddress1 = !$scope.agent.StreetAddress.StreetAddress1 ? null : $scope.agent.StreetAddress.StreetAddress1;
                $scope.agent.MailingAddress.StreetAddress1 = !$scope.agent.MailingAddress.StreetAddress1 ? null : $scope.agent.MailingAddress.StreetAddress1;
                $scope.agent.StreetAddress2 = !$scope.agent.StreetAddress2 ? null : $scope.agent.StreetAddress2;
                $scope.agent.City = (($scope.agent.City && (!$scope.agent.StreetAddress1 || !$scope.agent.Zip5)) ? null : $scope.agent.City);
                $scope.agent.MailingAddress.FullAddress = !$scope.agent.MailingAddress.StreetAddress1 ? ResultStatus.NONE : $scope.agent.MailingAddress.FullAddress;
                // agent show default in edit mode if there is no entity name, first name and last name
                if (!$scope.agent.EntityName && !$scope.agent.FirstName && !$scope.agent.LastName) {
                    $scope.isAgentEmpty = true;
                    if ($scope.agent.IsNonCommercial) {
                        $scope.agent.IsNonCommercial = true;
                        if (!$scope.isFormation) {
                            $scope.agent.IsAgentEdit = true;
                        }
                        //else {
                        //}
                    }
                    $scope.agent.IsAmendmentAgentInfoChange = true;
                    $scope.agent.editagentInfo = angular.copy($scope.agent);
                }
                else {
                    $scope.isAgentEmpty = false;
                }

                // validate agent state
                // Street Address
                if (!$scope.agent.StreetAddress.IsInvalidState) {
                    if ($scope.agent.StreetAddress && $scope.agent.StreetAddress.State != "" && $scope.agent.StreetAddress.State != null && $scope.agent.StreetAddress.State != 'WA' && (!$scope.agent.IsNonCommercial || !$scope.isAgentEmpty)) {
                        $scope.agent.isStreetStateMustbeinWA = true;
                        $scope.agent.StreetAddress.IsInvalidState = true;
                    }
                    else {
                        $scope.agent.isStreetStateMustbeinWA = false;
                        $scope.agent.StreetAddress.IsInvalidState = false;
                    }
                }

                // invalid po box address in street address 
                if ($scope.agent.StreetAddress
                    && (wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1) || wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1))
                    ) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var isACP = wacorpService.validatePoBoxAddress($scope.agent.StreetAddress);
                    if (!isACP)
                        $scope.agent.StreetAddress.invalidPoBoxAddress = true;
                }

                // Mailing Address
                if (!$scope.agent.MailingAddress.IsInvalidState) {
                    if ($scope.agent.MailingAddress && $scope.agent.MailingAddress.State != "" && $scope.agent.MailingAddress.State != null && $scope.agent.MailingAddress.State != 'WA' && (!$scope.agent.IsNonCommercial || !$scope.isAgentEmpty)) {
                        $scope.agent.isMailingStateMustbeinWA = true;
                        $scope.agent.MailingAddress.IsInvalidState = true;
                    }
                    else {
                        $scope.agent.isMailingStateMustbeinWA = false;
                        $scope.agent.MailingAddress.IsInvalidState = false;
                    }
                }

                if (angular.isNullorEmpty($scope.agent))
                    return;
                else {
                    var fullName = "";
                    var name = "";
                    name += $scope.agent.FirstName;
                    name += !angular.isNullorEmpty($scope.agent.LastName) ? " " + $scope.agent.LastName : "";
                    if ($scope.agent.AgentType == "I")
                        fullName = name;
                    else {
                        if (angular.isNullorEmpty(name))
                            name += $scope.agent.EntityName;
                        fullName = name;
                    }
                    $scope.agent.FullName = angular.isNullorEmpty(fullName) ? "" : fullName;
                }
            }

            // $scope.IsAmendmentAgentInfoChange = angular.isNullorEmpty($scope.IsAmendmentAgentInfoChange) ? false : $scope.IsAmendmentAgentInfoChange; //Is Entity Type Radio button
            var showforTypes = new Array("WA LIMITED PARTNERSHIP", "WA LIMITED LIABILITY LIMITED PARTNERSHIP", "FOREIGN LIMITED PARTNERSHIP", "FOREIGN LIMITED LIABILITY PARTNERSHIP", "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP");
            angular.forEach(showforTypes, function (key, data) {
                if ($scope.businessType.indexOf(key) > -1) {
                    $scope.showRAHyperLink = true;
                }
            });

            //$scope.showRAHyperLink = $scope.businessType == 'WA LIMITED PARTNERSHIP' || $scope.businessType == 'WA LIMITED LIABILITY LIMITED PARTNERSHIP' ? true : false;
            //$scope.agent.IsNonCommercial = true;

            $scope.removeWA = $scope.businessType.indexOf("WA") > -1 ? false : true;//if type is foreign then remove Washington

            var agentScope = {
                AgentID: constant.ZERO, EntityName: null, FirstName: null, LastName: null, IsNonCommercial: true, EmailAddress: null,
                ConfirmEmailAddress: null, AgentType: ResultStatus.INDIVIDUAL, AgentTypeID: constant.ZERO, BusinessAgentAddressID: constant.ZERO, BusinessAgentMailingAddressID: constant.ZERO, IsRAOfficeorPositionSearch: false,
                StreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                MailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                IsUserRegisteredAgent: false, PhoneNumber: null, IsRegisteredAgentConsent: true, Title: null, IsSameAsMailingAddress: false, //TFS 1143 IsRegisteredAgentConsent: false always true
                CreatedBy: null, AgentCreatdDate: null, AgentCreatdIP: null, IsNewAgent: false, FullName: null, IsAgentEdit: false,
                IsACP: false
            };

            var agentResetScope = {
                AgentID: constant.ZERO, EntityName: null, FirstName: null, LastName: null, IsNonCommercial: true, EmailAddress: null,
                ConfirmEmailAddress: null, AgentType: ResultStatus.INDIVIDUAL, AgentTypeID: constant.ZERO, BusinessAgentAddressID: constant.ZERO, BusinessAgentMailingAddressID: constant.ZERO,
                StreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                MailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                IsUserRegisteredAgent: false, PhoneNumber: null, IsRegisteredAgentConsent: true, Title: null, IsSameAsMailingAddress: false,//TFS 1143 IsRegisteredAgentConsent: false always true
                CreatedBy: null, AgentCreatdDate: null, AgentCreatdIP: null, IsNewAgent: false, FullName: null, IsAgentEdit: false,
                IsACP: false
            };

            var isSameAsMailing = $scope.agent.IsSameAsMailingAddress;

            $scope.agent = $scope.agent ? angular.extend(agentScope, $scope.agent) : angular.copy(agentResetScope);
            $scope.agent.ConfirmEmailAddress = $scope.agent.EmailAddress;
            $scope.oldAgent = angular.copy($scope.agent);

            $scope.Init = function () {
                //$scope.RegisteredAgent.businessAddress.ValidAddressCheck.$setValidity("text", true);
                if ($scope.agent && $scope.agent.IsRAOfficeorPositionSearch && $scope.agent.AgentType == 'O') {
                    $scope.agent.IsRAOfficeorPositionSearch = true;
                    $scope.agent.AgentType = 'O';
                    $scope.agent.IsNewAgent = true;
                }

                // As per the Issues in Save & Close and Shopping Cart in 11.1.2 -- 2980, 2961 & 2134
                //$scope.isSameAsStreet = angular.equals($scope.agent.StreetAddress, $scope.agent.MailingAddress);
                if (($scope.agent.StreetAddress.FullAddress != "" && $scope.agent.StreetAddress.FullAddress != undefined && $scope.agent.StreetAddress.FullAddress != null)
                    && ($scope.agent.MailingAddress.FullAddress != "" && $scope.agent.MailingAddress.FullAddress != undefined && $scope.agent.MailingAddress.FullAddress != null)
                    && (($scope.agent.AgentID == null || $scope.agent.AgentID == undefined ? $scope.agent.AgentID == 0 : $scope.agent.AgentID))) {
                    if ($scope.agent.IsSameAsMailingAddress) {
                        $scope.agent.IsSameAsMailingAddress = true;
                    }
                }
            }

            //$scope.agent.businessType = businessType;

            //Clear the Agent Information
            $scope.clearAgent = function () {
                var isAmendmentAgentclearAgent = $scope.agent.IsAmendmentAgentInfoChange;

                if ($scope.agent.IsAgentEdit) {
                    $scope.agent.EntityName = '';
                    $scope.agent.FirstName = '';
                    $scope.agent.LastName = '';
                    $scope.agent.EmailAddress = '';
                    $scope.agent.ConfirmEmailAddress = '';

                    //$scope.agent.StreetAddress = '';
                    //$scope.agent.MailingAddress = '';

                    for (var item in $scope.agent.StreetAddress) {
                        $scope.agent.StreetAddress[item] = null;
                        $scope.agent.MailingAddress[item] = null;
                    }
                    $scope.agent.StreetAddress.Sate = codes.WA;
                    $scope.agent.StreetAddress.Country = codes.USA;
                    $scope.agent.MailingAddress.Sate = codes.WA;
                    $scope.agent.MailingAddress.Country = codes.USA;
                }
                else {
                    $scope.agent = angular.copy(agentResetScope);
                    $scope.selectedtAgent = angular.copy(agentResetScope);
                    $scope.agent.IsNewAgent = true;
                    $scope.agent.IsNonCommercial = true;
                }
                $scope.agent.IsAmendmentAgentInfoChange = isAmendmentAgentclearAgent;
            };

            if ($rootScope.repository.loggedUser != null)
                $scope.isCRALogin = $rootScope.repository.loggedUser.filerTypeId == filerType.CommercialRegisteredAgent ? true : false;

            //Clear the Agent Information
            $scope.cancelAgent = function () {
                var isAmendmentAgentInfoChangecancelAgent = $scope.agent.IsAmendmentAgentInfoChange;
                isSameAsMailing = false;

                if ($scope.agent.IsAgentEdit) {
                    $scope.agent = !$scope.agent.editagentInfo ? $scope.agent : angular.copy($scope.agent.editagentInfo);
                    $scope.agent.IsAgentEdit = false;
                    $scope.agent.IsNewAgent = false;
                    $scope.agent.IsNonCommercial = true;
                }
                else {
                    agentResetScope.AgentType = 'I';
                    $scope.agent = angular.copy(agentResetScope);
                    $scope.selectedtAgent = angular.copy(agentResetScope);
                    $scope.agent.IsNewAgent = false;
                    $scope.agent.IsNonCommercial = true;
                    $scope.agent.IsAgentEdit = false;
                    // $scope.messages.RegisteredAgent.atleastOneAgent = "Please add at least one Registered agent";
                }

                $scope.agent.IsAmendmentAgentInfoChange = isAmendmentAgentInfoChangecancelAgent;

                // validate agent state
                // Street Address

                if ($scope.agent.StreetAddress && $scope.agent.StreetAddress.State != "" && $scope.agent.StreetAddress.State != null && $scope.agent.StreetAddress.State != 'WA') {
                    $scope.agent.isStreetStateMustbeinWA = true;
                    $scope.agent.StreetAddress.IsInvalidState = true;
                }
                else {
                    $scope.agent.isStreetStateMustbeinWA = false;
                    $scope.agent.StreetAddress.IsInvalidState = false;
                }

                // Mailing Address
                if ($scope.agent.MailingAddress && $scope.agent.MailingAddress.State != "" && $scope.agent.MailingAddress.State != null && $scope.agent.MailingAddress.State != 'WA') {
                    $scope.agent.isMailingStateMustbeinWA = true;
                    $scope.agent.MailingAddress.IsInvalidState = true;
                }
                else {
                    $scope.agent.isMailingStateMustbeinWA = false;
                    $scope.agent.MailingAddress.IsInvalidState = false;
                }

                if (!$scope.agent.EntityName && !$scope.agent.FirstName && !$scope.agent.LastName) {
                    $scope.agent.AgentID = 0;
                    $scope.agent.AgentType = "I";
                }

                // invalid po box address in street address 
                if ($scope.agent.StreetAddress
                     && (wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1) || wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1))
                     ) {
                    var isACP = wacorpService.validatePoBoxAddress($scope.agent.StreetAddress);
                    if (!isACP)
                        $scope.agent.StreetAddress.invalidPoBoxAddress = true;
                }

                //Here we are calling the method which is declared in another controller(EmailOption.js)
                if ($scope.RegisteredAgent.EmailID.$viewValue == "" && ($scope.agent.EmailAddress == "" || $scope.agent.EmailAddress == null || $scope.agent.EmailAddress == undefined)) {
                    $rootScope.$broadcast('onEmailEmpty');
                }
            };

            $scope.IsAlphaNumeric = function (e) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                var keyCode = e.which || e.keyCode;
                var result = wacorpService.IsAlphaNumeric(e);
                if (!result && keyCode == 8 || keyCode == 46 || e.key == "ArrowLeft" || e.key == "ArrowRight") { }
                else if (!result && e.key != "Tab") {
                    e.preventDefault();
                }
            };

            //Add New Agent
            $scope.addNewAgent = function () {
                var isAmendmentAgentInfoChangeaddNewAgent = $scope.agent.IsAmendmentAgentInfoChange;
                $("#divSearchResult").modal('toggle');
                //$scope.agent = angular.copy(agentResetScope);
                $scope.selectedtAgent = angular.copy(agentResetScope);
                $scope.agent.IsNewAgent = true;
                $scope.agent.IsNonCommercial = true;
                $scope.agent.IsAmendmentAgentInfoChange = isAmendmentAgentInfoChangeaddNewAgent;

                //TFS 1143 
                $scope.agent.IsAgentAltered = true;
            };

            //Add office or position
            $scope.addNewOfficeOrPosition = function () {
                var isAmendmentAgentaddNewOfficeOrPosition = $scope.agent.IsAmendmentAgentInfoChange;
                // $("#divSearchResult").modal('toggle');
                agentResetScope.AgentType = 'O';
                $scope.agent = angular.copy(agentResetScope);
                $scope.selectedtAgent = angular.copy(agentResetScope);
                $scope.agent.IsNewAgent = true;
                $scope.agent.IsNonCommercial = true;
                //  $scope.messages.RegisteredAgent.atleastOneAgent = "Please add at least one Registered agent";
                $scope.agent.IsAmendmentAgentInfoChange = isAmendmentAgentaddNewOfficeOrPosition;
            };

            //Copy the Mailing address to Street Address
            $scope.CopyAgentStreetFromMailing = function () {
                ////Invalid Zipcode Validation
                //$scope.RegisteredAgent.businessAddress.ValidAddressCheck.$setValidity("text", true);
                //$scope.agent.StreetAddress.IsACPChecked = false;

                //Holding Returned Mail Flags for RA
                var isRAMailingAddressReturnedMail = $scope.agent.MailingAddress.IsAddressReturnedMail;

                $scope.mailingAddressID = $scope.agent.MailingAddress.ID;
                if ($scope.agent.IsSameAsMailingAddress) {
                    angular.copy($scope.agent.StreetAddress, $scope.agent.MailingAddress);
                    $scope.agent.MailingAddress.ID = $scope.mailingAddressID;
                    //Invalid Zipcode Validation
                    // if(!$scope.agent.StreetAddress.Zip4 && !$scope.agent.MailingAddress.Zip4)
                    //{
                    //    $scope.RegisteredAgent.businessAddress.ValidAddressCheck.$setValidity("text", false);
                    //}
                    if ($scope.agent.IsSameAsMailingAddress)
                        $scope.$broadcast("IsMailingRAAddress", true, $scope.agent);
                }
                else {
                    angular.copy(agentResetScope.MailingAddress, $scope.agent.MailingAddress);
                    //$scope.agent.StreetAddress.IsACPChecked =true;
                    //$rootScope.$broadcast("InvokeValidAddressCheck");
                    if (!$scope.agent.IsSameAsMailingAddress)
                        $scope.$broadcast("IsMailingRAAddress", false, $scope.agent);
                }

                //Setting the Returned Mail Values
                $scope.agent.MailingAddress.IsAddressReturnedMail = isRAMailingAddressReturnedMail;
                //if ($scope.agent.IsSameAsMailingAddress)
                //    $scope.$broadcast("IsMailingRAAddress", true, $scope.agent);
                //else if(!$scope.agent.IsSameAsMailingAddress)
                //    $scope.$broadcast("IsMailingRAAddress", false, $scope.agent);
            };

            //Search Agent Information
            $scope.searchAgent = function () {
                $scope.agentInfo = [];
                $scope.selectedtAgent = undefined;
                getAgentList(constant.ZERO); // getAgentList method is available in this file only.
                $("#divSearchResult").modal('toggle');
            };

            $scope.$watch('agentInfo', function () {
                if ($scope.agentInfo == undefined)
                    return;
                if ($scope.agentInfo.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);

            function getAgentList(page) {
                page = page || constant.ZERO;
                var criteria = {
                    FirstName: $scope.agent.FirstName || '', LastName: $scope.agent.LastName || '', BusinessName: $scope.agent.EntityName || '',
                    BusinessTypeID: $scope.agent.AgentType || '', IsNonCommercial: $scope.agent.IsNonCommercial || '',
                    PageID: page == constant.ZERO ? constant.ONE : page + constant.ONE, PageCount: constant.TEN
                };

                // getCommercialAgetns method is available in constants.js
                wacorpService.post(webservices.Common.getCommercialAgetns, criteria,
                    function (response) {
                        if (response.data != null) {

                            $scope.agentInfo = angular.copy(response.data);
                            if ($scope.totalCount == constant.ZERO && response.data.length > 0) {
                                var totalcount = response.data[constant.ZERO].TotalCount;
                                $scope.pagesCount = Math.round(totalcount / response.data.length);
                                $scope.totalCount = totalcount;
                            }
                            $scope.page = page;
                        }
                        else
                            // Folder Name: app Folder
                            // Alert Name: noDataFound method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.noDataFound);
                    },
                    function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    }
                );
            }

            //On select agent from agent list
            $scope.onSelectAgent = function (selectAgent) {
                $scope.selectedtAgent = undefined;
                $scope.selectedtAgent = selectAgent;
                $scope.selectedtAgent.ConfirmEmailAddress = selectAgent.EmailAddress;

                if ($scope.selectedtAgent.StreetAddress && $scope.selectedtAgent.StreetAddress.State && $scope.selectedtAgent.StreetAddress.State != 'WA') {
                    $scope.selectedtAgent.isStreetStateMustbeinWA = true;
                    $scope.selectedtAgent.StreetAddress.IsInvalidState = true;
                }
                else {
                    $scope.selectedtAgent.isStreetStateMustbeinWA = false;
                    $scope.selectedtAgent.StreetAddress.IsInvalidState = false;
                }

                // Mailing Address
                if ($scope.selectedtAgent.MailingAddress && $scope.selectedtAgent.MailingAddress.State && $scope.selectedtAgent.MailingAddress.State != 'WA') {
                    $scope.selectedtAgent.isMailingStateMustbeinWA = true;
                    $scope.selectedtAgent.MailingAddress.IsInvalidState = true;
                }
                else {
                    $scope.selectedtAgent.isMailingStateMustbeinWA = false;
                    $scope.selectedtAgent.MailingAddress.IsInvalidState = false;
                }
            };

            //Add Search Agent
            $scope.addSearchAgent = function () {
                var isAmendmentAgentInfoChangeaddSearchAgent = $scope.agent.IsAmendmentAgentInfoChange;
                if ($scope.selectedtAgent && $scope.selectedtAgent.AgentID != constant.ZERO) {
                    $scope.agent = $scope.selectedtAgent;
                    if ($scope.agent.IsNonCommercial)//$scope.isFormation && 
                    {
                        $scope.agent.IsNewAgent = true;
                        $scope.agent.AgentID = null;
                    }
                    //else {
                    //    $scope.agent.IsNewAgent = false;
                    //}
                    //$scope.messages.RegisteredAgent.atleastOneAgent = "Please add at least one Registered agent";
                    $("#divSearchResult").modal('toggle');
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: selectAgent method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.RegisteredAgent.selectAgent);
                }

                $scope.agent.IsAmendmentAgentInfoChange = isAmendmentAgentInfoChangeaddSearchAgent;
                $scope.agent.IsUserRegisteredAgent = false;  //TFS 1460

                //TFS 1143 submitting filing means you have said agent consents
                if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
                    $scope.modal.Agent.IsRegisteredAgentConsent =
                        true;
                }

                if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
                    $scope.modal.IsRegisteredAgentConsent = true;
                }
                //TFS 1143

                // invalid po box address in street address 
                if ($scope.agent.StreetAddress
                    && (wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1) || wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1))
                    ) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var isACP = wacorpService.validatePoBoxAddress($scope.agent.StreetAddress);
                    if (!isACP)
                        $scope.agent.StreetAddress.invalidPoBoxAddress = true;
                }

                //TFS 1143 
                $scope.agent.IsAgentAltered = true;
            };

            //Delete selected Agent record
            $scope.deleteAgent = function () {
                if ($scope.agent.AgentID != constant.ZERO) {
                    // Folder Name: app Folder
                    // Alert Name: ConfirmMessage method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                        var isAmendmentdeleteAgent = $scope.agent.IsAmendmentAgentInfoChange;
                        $scope.agent = angular.copy(agentResetScope);
                        $scope.selectedtAgent = angular.copy(agentResetScope);
                        $scope.agent.AgentType = ResultStatus.INDIVIDUAL;
                        // $scope.messages.RegisteredAgent.atleastOneAgent = "Please add at least one Registered agent";
                        $scope.agent.IsAmendmentAgentInfoChange = isAmendmentdeleteAgent;
                        $scope.agent.isMailingStateMustbeinWA = false;
                        $scope.agent.isStreetStateMustbeinWA = false;
                        $scope.agent.StreetAddress.IsInvalidState = false;
                        $scope.agent.MailingAddress.IsInvalidState = false;
                        $scope.agent.IsAgentAltered = true; //TFS 1143
                        //Here we are calling the method which is declared in another controller(EmailOption.js)
                        $rootScope.$broadcast('onEmailEmpty');
                    });
                }
            };

            //Get User details during select register agent consent as Yes
            $scope.getAgentUserDetails = function () {
                $scope.agent.IsAgentAltered = true; //TFS 1143
                isSameAsMailing = false;
                $scope.agent.IsSameAsMailingAddress = false;
                $scope.agent.StreetAddress.raisezip5KeyEvent = false;
                $scope.agent.MailingAddress.raisezip5KeyEvent = false;
                var currentTypeID = angular.copy($scope.agent.AgentType);
                var isAmendmentAgentInfoChange = $scope.agent.IsAmendmentAgentInfoChange;

                if ($scope.agent.IsUserRegisteredAgent) {  //TFS 1143
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        //$scope.agent.IsNewAgent = true;
                        $scope.agent.IsNonCommercial = response.data.FilerTypeId == "CA" ? false : true;
                        $scope.agent.IsNewAgent = $scope.agent.IsNonCommercial ? true : false;
                        $scope.agent.AgentType = (response.data.FilerTypeId == "FI" ? ($scope.newUser.isIndividual == false ? "E" : "I") : response.data.Agent.AgentType);// angular.copy($scope.newUser.Agent.AgentType);  //response.data.isIndividual == false ? "E": "I"; //angular.copy($scope.newUser.Agent.AgentType);
                        $scope.agent.AgentID = angular.copy($scope.newUser.Agent.AgentID);
                        $scope.agent.EntityName = response.data.FilerTypeId == "FI" ? response.data.Agent.OrganizationName : response.data.Agent.EntityName; //angular.copy($scope.newUser.Agent.EntityName);
                        $scope.agent.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.agent.LastName = angular.copy($scope.newUser.LastName);
                        //$scope.agent.FullName = wacorpService.agentFullNameService($scope.newUser);
                        $scope.agent.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.agent.ConfirmEmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.agent.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        $scope.agent.StreetAddress = ($scope.newUser.Address.State == codes.WA) ? angular.copy($scope.newUser.Address) : angular.copy(agentResetScope.StreetAddress);//angular.copy($scope.newUser.Address);
                        $scope.agent.MailingAddress = ($scope.newUser.AltAddress.State == codes.WA) ? angular.copy($scope.newUser.AltAddress) : angular.copy(agentResetScope.MailingAddress);//angular.copy($scope.newUser.AltAddress);
                        $scope.agent.IsAgentEdit = false;
                        $scope.agent.StreetAddress.raisezip5KeyEvent = $scope.agent.StreetAddress.Zip5 ? true : false;
                        $scope.agent.MailingAddress.raisezip5KeyEvent = $scope.agent.MailingAddress.Zip5 ? true : false;
                        // $scope.messages.RegisteredAgent.atleastOneAgent = "Please add at least one Registered agent";

                        //Here we are calling the method which is declared in another controller(EmailOption.js)
                        if (($scope.agent.EmailAddress == "" || $scope.agent.EmailAddress == null || $scope.agent.EmailAddress == undefined)) {
                            $rootScope.$broadcast('onEmailEmpty');
                        }

                        //to validate RA Address 
                        if ($scope.validateData($scope.agent.MailingAddress.StreetAddress1) || $scope.validateData($scope.agent.MailingAddress.Zip5) || $scope.validateData($scope.agent.MailingAddress.City)) {
                            //var agentMailingAddrr=$scope.newUser.AltAddress;  //TFS 1460
                            var agentMailingAddrr = $scope.agent.MailingAddress; //TFS 1460
                            if ($scope.agent.IsACP) {
                                $scope.agent.IsACP = false;
                                $scope.agent.IsSameAsMailingAddress = false;
                                $scope.agent.isRAAddressValid = false;
                                $scope.agent.StreetAddress.IsACPChecked = $scope.agent.IsACP;
                                if ($scope.agent.StreetAddress && (wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1) || wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1))) {
                                    var isACP = wacorpService.validatePoBoxAddress($scope.agent.StreetAddress);
                                    if (!isACP)
                                        $scope.agent.StreetAddress.invalidPoBoxAddress = true;
                                }
                                $scope.RegisteredAgent.businessAddress.ValidAddressCheck.$setValidity("text", true);
                            }

                            //$scope.CopyAgentStreetFromMailing();
                            if ($scope.agent.IsSameAsMailingAddress)
                                $scope.$broadcast("IsMailingRAAddress", true, $scope.agent);
                            else if (!$scope.agent.IsSameAsMailingAddress)
                                $scope.$broadcast("IsMailingRAAddress", false, $scope.agent);
                            angular.copy(agentMailingAddrr, $scope.agent.MailingAddress);
                        }
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    $scope.agent = angular.copy(agentResetScope);
                    $scope.agent.AgentType = currentTypeID == 'O' ? 'E' : currentTypeID;
                    if ($scope.agent.IsSameAsMailingAddress)
                        $scope.$broadcast("IsMailingRAAddress", true, $scope.agent);
                    else if (!$scope.agent.IsSameAsMailingAddress)
                        $scope.$broadcast("IsMailingRAAddress", false, $scope.agent);
                    angular.copy(agentMailingAddrr, $scope.agent.MailingAddress);
                    // $scope.messages.RegisteredAgent.atleastOneAgent = "Please add at least one Registered agent";
                }

                $scope.agent.IsNewAgent = $scope.agent.IsRegisteredAgentConsent;
                $scope.agent.IsAmendmentAgentInfoChange = isAmendmentAgentInfoChange;

                //Here we are calling the method which is declared in another controller(EmailOption.js)
                if (($scope.agent.EmailAddress == "" || $scope.agent.EmailAddress == null || $scope.agent.EmailAddress == undefined)) {
                    $rootScope.$broadcast('onEmailEmpty');
                }
                //TFS 1143 
                $scope.agent.IsAgentAltered = true;
            };

            //$scope.$watch('agent', function () {
            //    if (angular.isNullorEmpty($scope.agent))
            //        return;
            //    else {
            //        var fullName = "";
            //        var name = "";
            //        name += $scope.agent.FirstName;
            //        name += !angular.isNullorEmpty($scope.agent.LastName) ? " " + $scope.agent.LastName : "";
            //        if ($scope.agent.AgentType == "I")
            //            fullName = name;
            //        else {
            //            if (angular.isNullorEmpty(name))
            //                name += $scope.agent.EntityName;
            //            fullName = name;
            //        }
            //        $scope.agent.FullName = angular.isNullorEmpty(fullName) ? "" : fullName;

            //        //// As per the Issues in Save & Close and Shopping Cart in 11.1.2 -- 2980, 2961 & 2134
            //        ////$scope.isSameAsStreet = angular.equals($scope.agent.StreetAddress, $scope.agent.MailingAddress);
            //        //if ($scope.agent.StreetAddress.FullAddress != "" && $scope.agent.StreetAddress.FullAddress != undefined && $scope.agent.StreetAddress.FullAddress != null
            //        //    && $scope.agent.MailingAddress.FullAddress != "" && $scope.agent.MailingAddress.FullAddress != undefined && $scope.agent.MailingAddress.FullAddress != null)
            //        //{
            //        //        if ($scope.agent.StreetAddress.FullAddress == $scope.agent.MailingAddress.FullAddress) {
            //        //            $scope.agent.IsSameAsMailingAddress = true;
            //        //        }
            //        //}                     
            //    }
            //}, true);

            $scope.$watch('agent.MailingAddress', function (newValue, oldValue) {
                if ($scope.agent.IsSameAsMailingAddress) {
                    $scope.agent.IsSameAsMailingAddress = true;
                    $scope.$broadcast("IsMailingRAAddress", true, $scope.agent);
                }
                else if (isSameAsMailing && newValue) {
                    $scope.agent.IsSameAsMailingAddress = true;
                    $scope.$broadcast("IsMailingRAAddress", true, $scope.agent);
                }
                else if (isSameAsMailing && newValue && oldValue) {
                    $scope.agent.IsSameAsMailingAddress = true;
                    $scope.$broadcast("IsMailingRAAddress", true, $scope.agent);
                }
                else if (isSameAsMailing && oldValue) {
                    $scope.agent.IsSameAsMailingAddress = true;
                    $scope.$broadcast("IsMailingRAAddress", true, $scope.agent);
                }
                else
                    $scope.$broadcast("IsMailingRAAddress", false, $scope.agent);
            });

            //to clear textbox info for different agent type when selection changed
            $scope.clearAgentInfo = function (agentType) {
                if (agentType == 'I') {
                    $scope.agent.EntityName = '';
                    //$scope.agent.OfficeOrPosition = '';
                }
                else if (agentType == 'E') {
                    $scope.agent.FirstName = '';
                    $scope.agent.LastName = '';
                    $scope.agent.EntityName = '';
                    //$scope.agent.OfficeOrPosition = '';
                }
                else {
                    $scope.agent.FirstName = '';
                    $scope.agent.LastName = '';
                    $scope.agent.EntityName = '';
                    $scope.agent.IsNewAgent = true;
                }
            }

            $scope.nonCommercialRAEdit = function (agent, isAmendment) {
                if (agent.AgentID > 0) {
                    var config = {
                        params: {
                            BusinessID: agent.BusinessIDForRA, AgentId: isAmendment ? $scope.oldAgent.AgentID : agent.AgentID
                        }
                    };
                    var data = "";

                    var streetAddress = agent.StreetAddress;
                    var mailingAddress = agent.MailingAddress;

                    // getNonCommercialRADetailsForEdit method is available in constants.js
                    wacorpService.get(webservices.Common.getNonCommercialRADetailsForEdit, config, function (response) {
                        if (response.data != null) {
                            angular.copy(response.data, $scope.agent);
                            $scope.agent.StreetAddress.StreetAddress1 = !$scope.agent.StreetAddress.StreetAddress1 ? null : $scope.agent.StreetAddress.StreetAddress1;
                            $scope.agent.MailingAddress.StreetAddress1 = !$scope.agent.MailingAddress.StreetAddress1 ? null : $scope.agent.MailingAddress.StreetAddress1;
                            $scope.agent.editagentInfo = angular.copy(response.data);
                            $scope.agent.ConfirmEmailAddress = $scope.agent.editagentInfo.EmailAddress;

                            if ($scope.agent.editagentInfo.IsNonCommercial) {
                                $scope.agent.IsNonCommercial = true;
                                $scope.agent.IsAgentEdit = true;
                                $scope.agent.IsNewAgent = true;
                                $scope.showErrorMessage = false;
                                $scope.agent.IsAgentAltered = true;  //TFS 1143 set Agent Entity
                                $scope.IsAgentAltered = true; //TFS 1143 set BusinessFilingInfoEntity
                            }

                            $scope.agent.IsAmendmentAgentInfoChange = true;
                            $scope.agent.StreetAddress.IsInvalidState = streetAddress.IsInvalidState;
                            $scope.agent.MailingAddress.IsInvalidState = mailingAddress.IsInvalidState;
                            // Service Folder: services

                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            if (wacorpService.validatePoBoxAddress($scope.agent.StreetAddress)) {
                                $scope.agent.IsACP = true;
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                if (wacorpService.validatePoBoxAddress($scope.agent.MailingAddress)) {
                                    $scope.agent.IsSameAsMailingAddress = true;
                                }
                            }
                        }
                        else
                            // Folder Name: app Folder
                            // Alert Name: noDataFound method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.noDataFound);
                    },
                        function (response) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog(response.data.Message);
                        }
                    );

                    //TFS 1143 TFS 1460 updated old code to correct variable, this was causing the issue with 1460
                    if ($rootScope.repository.loggedUser && $scope.agent.AgentID == $rootScope.repository.loggedUser.agentid) {
                        $scope.agent.IsUserRegisteredAgent = true;
                    }
                    else {
                        $scope.agent.IsUserRegisteredAgent = false;
                    }

                    //Original Code
                    //if ($rootScope.repository.loggedUser && $scope.agent.AgentID == $rootScope.repository.loggedUser.agentid) {
                    //    $scope.agent.IsRegisteredAgentConsent = true;
                    //}
                    //else {
                    //    $scope.agent.IsRegisteredAgentConsent = false;
                    //}
                    //Original Code
                    //TFS 1143 TFS 1460

                    //TFS 1143 submitting filing means you have said agent consents
                    if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
                        $scope.modal.Agent.IsRegisteredAgentConsent =
                            true;
                    }
                    if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
                        $scope.modal.IsRegisteredAgentConsent = true;
                    }
                    //TFS 1143
                }
            }

            //Amendment Agent Radio button change click
            $scope.isAmendmentAgentInfoChange = function (value) {
                var streetAddress = value.StreetAddress;
                var mailingAddress = value.MailingAddress;
                // No radio button Click
                if (!value.IsAmendmentAgentInfoChange) {
                    $scope.agent = $scope.entity ? $scope.entity.oldAmendmentEntity.Agent : angular.copy($scope.oldAgent);;
                    $scope.agent.IsAmendmentAgentInfoChange = false;
                }
                    // Yes radio button Click
                else {
                    $scope.agent.IsAmendmentAgentInfoChange = true;
                }
                $scope.agent.StreetAddress.IsInvalidState = streetAddress.IsInvalidState;
                $scope.agent.MailingAddress.IsInvalidState = mailingAddress.IsInvalidState;
            };

            $scope.ChangeACP = function () {
                //Holding Returned Mail Flags for RA
                var isRAStreetAddressReturnedMail = $scope.agent.StreetAddress.IsAddressReturnedMail;
                var isRAMailingAddressReturnedMail = $scope.agent.MailingAddress.IsAddressReturnedMail;

                if ($scope.agent.IsACP) {
                    $("#divACPRAConfirmation").modal('toggle');
                    $scope.agent.StreetAddress.invalidPoBoxAddress = false;
                    $scope.agent.isRAAddressValid = true;
                }
                else {
                    $scope.agent.IsACP = false;
                    angular.copy(agentResetScope.StreetAddress, $scope.agent.StreetAddress);
                    $scope.agent.IsSameAsMailingAddress = false;
                    $scope.agent.isRAAddressValid = false;
                    $scope.CopyAgentStreetFromMailing(); // CopyAgentStreetFromMailing method is available in this file only.

                    // invalid po box address in street address 
                    if ($scope.agent.StreetAddress
                        && (wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1) || wacorpService.validatePoBox($scope.agent.StreetAddress.StreetAddress1))
                        ) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        var isACP = wacorpService.validatePoBoxAddress($scope.agent.StreetAddress);
                        if (!isACP)
                            $scope.agent.StreetAddress.invalidPoBoxAddress = true;
                    }
                }
                $scope.agent.StreetAddress.IsACPChecked = $scope.agent.IsACP;

                //Setting the Returned Mail Values
                $scope.agent.StreetAddress.IsAddressReturnedMail = isRAStreetAddressReturnedMail;
                $scope.agent.MailingAddress.IsAddressReturnedMail = isRAMailingAddressReturnedMail;

                //if (!$scope.agent.IsACP)
                //    $rootScope.$broadcast("InvokeValidAddressCheck");
                $scope.RegisteredAgent.businessAddress.ValidAddressCheck.$setValidity("text", true);
            }

            $scope.clickOk = function () {
                $("#divACPRAConfirmation").modal('toggle');
                //Holding Returned Mail Flags for PO
                var isRAStreetAddressReturnedMail = $scope.agent.StreetAddress.IsAddressReturnedMail;
                var isRAMailingAddressReturnedMail = $scope.agent.MailingAddress.IsAddressReturnedMail;

                var poaddress = wacorpService.getpoboxAddress();
                angular.copy(poaddress, $scope.agent.StreetAddress);
                $scope.agent.IsSameAsMailingAddress = true;
                $scope.CopyAgentStreetFromMailing(); // CopyAgentStreetFromMailing method is available in this file only.
                $scope.agent.StreetAddress.IsInvalidState = false;
                $scope.agent.MailingAddress.IsInvalidState = false;

                //Setting the Returned Mail Values
                $scope.agent.StreetAddress.IsAddressReturnedMail = isRAStreetAddressReturnedMail;
                $scope.agent.MailingAddress.IsAddressReturnedMail = isRAMailingAddressReturnedMail;
            };

            $scope.cancel = function () {
                $scope.agent.IsACP = false;
                $scope.agent.StreetAddress.IsACPChecked = false;
                $("#divACPRAConfirmation").modal('toggle');
            };

            $scope.checkNonCommercialAgent = function () {
                $scope.agent.IsNonCommercial = true;
            };

            $scope.OfficeOrPositionAgentInfo = function (agentType) {
                if (agentType == 'O') {
                    $scope.agent.IsRAOfficeorPositionSearch = true;
                    $scope.agent.AgentType = 'O';
                    $scope.agent.IsNewAgent = true;
                }
            }

            $scope.checkRAEmail = function () {
                if ($scope.RegisteredAgent.EmailID.$viewValue == "" && ($scope.agent.EmailAddress == "" || $scope.agent.EmailAddress == null || $scope.agent.EmailAddress == undefined)) {
                    //Here we are calling the method which is declared in another controller(EmailOption.js)
                    $rootScope.$broadcast('onEmailEmpty');
                }
            };

            //to trim empty spaces for RA 
            $scope.validateRAEntityName = function (type) {
                if (type == "E" || type == "O") {
                    $scope.agent.EntityName = $scope.agent.EntityName ? angular.copy($scope.agent.EntityName.trim()) : (($scope.agent.EntityName == undefined || $scope.agent.EntityName == "") ? $scope.agent.EntityName = null : $scope.agent.EntityName);
                }
                if (type == "I") {
                    $scope.agent.FirstName = $scope.agent.FirstName ? angular.copy($scope.agent.FirstName.trim()) : (($scope.agent.FirstName == undefined || $scope.agent.FirstName == "") ? $scope.agent.FirstName = null : $scope.agent.FirstName);
                    $scope.agent.LastName = $scope.agent.LastName ? angular.copy($scope.agent.LastName.trim()) : (($scope.agent.LastName == undefined || $scope.agent.LastName == "") ? $scope.agent.LastName = null : $scope.agent.LastName);
                }
            }

            //to clear RA mailing Address when Street address is modified:12/09/2018
            var clearRAStreetAddressOnChange = $scope.$on("ClearRAStreetAddress", function (evt, data) {
                //Holding Returned Mail Flags for PO
                var isRAMailingAddressReturnedMail = $scope.agent.MailingAddress.IsAddressReturnedMail;
                if ($scope.agent.IsSameAsMailingAddress) {
                    if (wacorpService.compareAddress($scope.agent.StreetAddress, $scope.agent.MailingAddress)) {
                        $scope.agent.IsSameAsMailingAddress = false;
                        $scope.CopyAgentStreetFromMailing();
                    }
                }

                //Setting the Returned Mail Values
                $scope.agent.MailingAddress.IsAddressReturnedMail = isRAMailingAddressReturnedMail;
                evt.defaultPrevented = true;
            });

            $scope.$on('$destroy', clearRAStreetAddressOnChange);

            $scope.validateData = function (data) {
                if ((data == null || data == undefined || data == "") || (data != null || data != undefined || data != ""))
                    return true;
                else
                    return false;
            }
        },
    };
});
wacorpApp.directive('principal', function () {
    return {
        templateUrl: 'ng-app/directives/Principals/Principals.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            principalList: '=?principalList',
            note: '=?note',
            isReview: '=?isReview',
            isFormation: '=?isFormation',
            entityTypeId: '=?entityTypeId',
            isUserDisplay: '=?isUserDisplay',
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.principalList = $scope.principalList || [];
            $scope.note = $scope.note || false;
            $scope.isReview = $scope.isReview || false;
            $scope.isFormation = $scope.isFormation || false;
            $scope.addbuttonName = $scope.sectionName == 'Governors' ? "Add "+ $scope.sectionName.slice(0,8) : "Add " + $scope.sectionName;
            $scope.sectionType = $scope.sectionName == 'Governors' ? $scope.sectionName.slice(0, 8) + ' Type' : $scope.sectionName + ' Type:';
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.entityTypeId = $scope.entityTypeId || '';
            $scope.IsGovernorAddressRequired = false; // Is Governor Address Required 
            $scope.IsGovernorAddressShow = true;
            $scope.isUserDisplay = $scope.isUserDisplay || false;
            $scope.diplayName = $scope.sectionName == 'General Partner' ? $scope.sectionName.replace(/ /g, '') + '_gridList' : $scope.sectionName + '_gridList';
            // TFS ID 12822
            if ($scope.sectionName == "Governors") {
                $scope.isUserPricipalText = "I am a " + $scope.sectionName.slice(0, 8);
            }
            else if ($scope.sectionName == "Executor" || $scope.sectionName == "Incorporator" || $scope.sectionName == "InitialBoardOfDirector") {
                $scope.isUserPricipalText = "I am an " + $scope.sectionName;
            }
            else {
                $scope.isUserPricipalText = "I am a " + $scope.sectionName;
            }
           // $scope.isUserPricipalText = $scope.sectionName == "Governors" ? "I am a " + $scope.sectionName.slice(0,8) : "I am a " + $scope.sectionName;

            // If principal Type ID is INDIVIDUAL Entiry name text box is empty.
            $scope.getPrincipleTypeChange = function (principalTypeID) {
                if (principalTypeID == ResultStatus.INDIVIDUAL) {
                    $scope.principal.Name = '';
                }
            };

            angular.forEach($scope.principalList, function (value, key) {
                if (value.IsFormation == true)
                    $scope.isFormation = true;
            });

            $scope.principal = {
                PrincipalID: constant.ZERO, SequenceNo: "", FirstName: null, LastName: null, Title: null, Name: null, PhoneNumber: null, EmailAddress: null, isUserPricipal: false,IsFormation: false,
                TypeID: ResultStatus.INDIVIDUAL, PrincipalBaseType: null, PrincipalMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, PrincipalStreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, IsSameAsMailingAddress: false, BusinessID: constant.ZERO, Status: principalStatus.INSERT, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
                FilerID: constant.ZERO, UserID: constant.ZERO,
                CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            var principalDataScope = {
                PrincipalID: constant.ZERO, SequenceNo: "", FirstName: null, LastName: null, Title: null, Name: null, PhoneNumber: null, EmailAddress: null, isUserPricipal: false,IsFormation: false,
                TypeID: ResultStatus.INDIVIDUAL, PrincipalBaseType: null,
                PrincipalMailingAddress: angular.extend({
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, $scope.principal.PrincipalMailingAddress),

                PrincipalStreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                IsSameAsMailingAddress: false, BusinessID: constant.ZERO, Status: principalStatus.INSERT, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            //Reset the principal
            $scope.resetPrincipal = function () {
                $scope.principal = angular.copy(principalDataScope);
                $scope.addbuttonName = $scope.sectionName == 'Governors' ? "Add " + $scope.sectionName.slice(0, 8) : "Add " + $scope.sectionName;
                $scope.showErrorMessage = false;
            };

            //Add principal data
            $scope.AddPrincipal = function (Principals) {
                if ($scope.principal.PrincipalBaseType == "GOVERNINGPERSON") {
                    $scope.IsGovernorAddressShow = false;
                    $scope.IsGovernorAddressRequired = true;
                }
                else {
                    $scope.IsGovernorAddressShow = true;
                    $scope.IsGovernorAddressRequired = false;
                }

                if ($scope.modalName != "GoverningPerson") {
                    $scope.principal.PrincipalStreetAddress.StreetAddress1 = (($scope.principal.PrincipalStreetAddress.StreetAddress1 != null && $scope.principal.PrincipalStreetAddress.StreetAddress1.trim() == "" || $scope.principal.PrincipalStreetAddress.StreetAddress1 == undefined) ? $scope.principal.PrincipalStreetAddress.StreetAddress1 = null : $scope.principal.PrincipalStreetAddress.StreetAddress1.trim());

                    if (!$scope.principal.PrincipalStreetAddress.StreetAddress1) {
                        $scope.Principals.businessAddress.StreetAddress1.$setValidity("text", false);
                    }
                    else {
                        $scope.Principals.businessAddress.StreetAddress1.$setValidity("text", true);
                    }
                }

                $scope.showErrorMessage = true;
                if ($scope[Principals].$valid) {
                    $scope.principal.IsFormation = $scope.isFormation;
                    $scope.showErrorMessage = false;
                    if ($scope.principal.SequenceNo != "") {
                        angular.forEach($scope.principalList, function (incorp) {
                            if (incorp.SequenceNo == $scope.principal.SequenceNo) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                $scope.principal.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.principal.PrincipalStreetAddress);
                                angular.copy($scope.principal, incorp);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.principalList, function (incorp) {
                            if (maxId == constant.ZERO || incorp.SequenceNo > maxId)
                                maxId = incorp.SequenceNo;
                        });
                        $scope.principal.SequenceNo = ++maxId;
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.principal.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.principal.PrincipalStreetAddress);
                        $scope.principal.PrincipalBaseType = $scope.modalName;
                        $scope.principal.Status = principalStatus.INSERT;
                        $scope.principalList.push($scope.principal);
                    }
                    $scope.resetPrincipal(); // resetPrincipal method is available in this file only.
                }

                if ($scope.modalName.toUpperCase() == "GOVERNINGPERSON") {
                    $scope.IsGovernorAddressShow = false;
                    $scope.IsGovernorAddressRequired = true;
                }
                else {
                    $scope.IsGovernorAddressShow = true;
                    $scope.IsGovernorAddressRequired = false;
                }
            };

            //Edit principal data
            $scope.editPrincipal = function (principaldata) {
                principaldata.PrincipalStreetAddress.Country = principaldata.PrincipalStreetAddress.Country || codes.USA;
                principaldata.PrincipalStreetAddress.State = principaldata.PrincipalStreetAddress.State || codes.USA;
                $scope.principal = angular.copy(principaldata);
                $scope.principal.Status = $scope.principal.PrincipalID == 0 ? principalStatus.INSERT : principalStatus.UPDATE;
                $scope.addbuttonName = $scope.sectionName == 'Governors' ? "Update " + $scope.sectionName.slice(0, 8) : "Update " + $scope.sectionName;
                if (principaldata.PrincipalBaseType.toUpperCase() == "GOVERNINGPERSON")
                {
                    $scope.IsGovernorAddressShow = false;
                    $scope.IsGovernorAddressRequired = true;
                }
                else
                {
                    $scope.IsGovernorAddressShow = true;
                    $scope.IsGovernorAddressRequired = false;
                }
            };

            //Delete principal data
            $scope.deletePrincipal = function (principaldata) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                    if (principaldata.Status=="N")
                    {
                        var index = $scope.principalList.indexOf(principaldata);
                        $scope.principalList.splice(index, 1);
                    }
                    else
                    {
                        principaldata.Status = principalStatus.DELETE;
                    }
                    $scope.resetPrincipal();  // resetPrincipal method is available in this file only.
                });
            };

            // Clear all controls data
            $scope.clearPrincipal = function () {
                $scope.resetPrincipal();  // resetPrincipal method is available in this file only.
            };


            //Get User details during select Principal as I am a respective Principal
            $scope.getPrincipalUserDetails = function (isUserPricipal) {
                var currentTypeID = angular.copy($scope.principal.TypeID);
                if (isUserPricipal) {
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        //$scope.principal.TypeID = response.data.isIndividual == false ? "E" : "I";
                        $scope.principal.TypeID = (response.data.FilerTypeId == "FI" ? ($scope.newUser.isIndividual == false ? "E" : "I") : response.data.Agent.AgentType);
                        //angular.copy($scope.newUser.Agent.AgentType); //angular.copy($scope.newUser.Agent.AgentType);
                        $scope.principal.Status = principalStatus.INSERT;
                        $scope.principal.Name = response.data.FilerTypeId == "FI" ? response.data.Agent.OrganizationName : response.data.Agent.EntityName;//angular.copy($scope.newUser.Agent.EntityName);
                        $scope.principal.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.principal.LastName = angular.copy($scope.newUser.LastName);
                        $scope.principal.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.principal.ConfirmEmailAddress = angular.copy($scope.newUser.ConfirmEmailAddress);
                        $scope.principal.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        $scope.principal.PrincipalStreetAddress = angular.copy($scope.newUser.Address);
                        //Bug Net Id:72164
                        // $scope.principal.PrincipalStreetAddress = angular.copy($scope.newUser.AltAddress);
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    $scope.principal = angular.copy(principalDataScope);
                    $scope.principal.TypeID = currentTypeID;
                    $scope.addbuttonName = $scope.sectionName == 'Governors' ? "Add " + $scope.sectionName.slice(0, 8) : "Add " + $scope.sectionName;
                }
            };
            
            //For Governer Address validation Condition
            if ($scope.modalName.toUpperCase() == 'GOVERNINGPERSON') {
                // governer address required entities not checking adrress fileds are required
                if ($scope.entityTypeId == governerAddressRequiredEntityTypeID.WaProfitCorporation || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaProfessionalServiceCorporation
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaSocialPurposeCorporation || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaPublicUtilityCorporation
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaEmployeeCooperative || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaMassachusettsTrust
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaAssociationUnderFishMarketingAct || $scope.entityTypeId == governerAddressRequiredEntityTypeID.ForeignProfitCorporation
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.ForeignProfessionalServiceCorporation || $scope.entityTypeId == governerAddressRequiredEntityTypeID.ForeignPublicUtilityCorporation
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.ForeignMassachusettsTrust) {
                    $scope.IsGovernorAddressRequired = true;
                }
                else {
                    // Governer Address optional 
                    $scope.IsGovernorAddressRequired = false;
                }
                $scope.IsGovernorAddressShow = false;
            }
        },
    };
});
wacorpApp.directive('principalNonProfitMember', function () {
    return {
        templateUrl: 'ng-app/directives/Principals/PrincipalsNonProfitMembers.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            isReview: '=?isReview',
            principalMemberList: '=?principalMemberList',
            hasMemberNonProfit: '=?hasMemberNonProfit',
            note: '=?note',
            isFormation: '=?isFormation',
            entityTypeId: '=?entityTypeId',
            isUserDisplay: '=?isUserDisplay',
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.principalMemberList = $scope.principalMemberList || [];
            $scope.note = $scope.note || false;
            $scope.isReview = $scope.isReview || false;
            $scope.isFormation = $scope.isFormation || false;
            //$scope.addbuttonName = $scope.sectionName == 'Governors' ? "Add " + $scope.sectionName.slice(0, 8) : "Add " + $scope.sectionName;
            $scope.addbuttonName = "Add " + $scope.sectionName;
            //$scope.sectionType = $scope.sectionName == 'Governors' ? $scope.sectionName.slice(0, 8) + ' Type' : $scope.sectionName + ' Type:';
            $scope.sectionType = $scope.sectionName + ' Type:';
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.entityTypeId = $scope.entityTypeId || '';
            $scope.IsGovernorAddressRequired = false; // Is Governor Address Required 
            $scope.IsGovernorAddressShow = false;
            $scope.isUserDisplay = $scope.isUserDisplay || false;
            $scope.diplayName = $scope.sectionName == 'General Partner' ? $scope.sectionName.replace(/ /g, '') + '_gridList' : $scope.sectionName + '_gridList';
            // TFS ID 12822
            //if ($scope.sectionName == "Governors") {
            //    $scope.isUserPricipalText = "I am a " + $scope.sectionName.slice(0, 8);
            //}
            //else if ($scope.sectionName == "Executor" || $scope.sectionName == "Incorporator" || $scope.sectionName == "InitialBoardOfDirector") {
            //    $scope.isUserPricipalText = "I am an " + $scope.sectionName;
            //}
            //else {
                $scope.isUserPricipalText = "I am a " + $scope.sectionName;
            //}

            

            // If principal Type ID is INDIVIDUAL Entiry name text box is empty.
            $scope.getPrincipleTypeChange = function (principalTypeID) {
                if (principalTypeID == ResultStatus.INDIVIDUAL) {
                    $scope.principal.Name = '';
                }
            };

            angular.forEach($scope.principalMemberList, function (value, key) {
                if (value.IsFormation == true)
                    $scope.isFormation = true;
            });

            $scope.principal = {
                PrincipalID: constant.ZERO, SequenceNo: "", FirstName: null, LastName: null, Title: null, Name: null, PhoneNumber: null, EmailAddress: null, isUserPricipal: false,IsFormation: false,
                TypeID: ResultStatus.INDIVIDUAL, PrincipalBaseType: null, PrincipalMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, PrincipalStreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, IsSameAsMailingAddress: false, BusinessID: constant.ZERO, Status: principalStatus.INSERT, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
                FilerID: constant.ZERO, UserID: constant.ZERO,
                CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            var principalDataScope = {
                PrincipalID: constant.ZERO, SequenceNo: "", FirstName: null, LastName: null, Title: null, Name: null, PhoneNumber: null, EmailAddress: null, isUserPricipal: false,IsFormation: false,
                TypeID: ResultStatus.INDIVIDUAL, PrincipalBaseType: null,
                PrincipalMailingAddress: angular.extend({
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, $scope.principal.PrincipalMailingAddress),

                PrincipalStreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                IsSameAsMailingAddress: false, BusinessID: constant.ZERO, Status: principalStatus.INSERT, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            //Reset the principal
            $scope.resetPrincipal = function () {
                $scope.principal = angular.copy(principalDataScope);
                $scope.addbuttonName = $scope.sectionName == 'Governors' ? "Add " + $scope.sectionName.slice(0, 8) : "Add " + $scope.sectionName;
                $scope.showErrorMessage = false;
            };

            //Add principal data
            $scope.AddPrincipal = function (Principals) {
                //if ($scope.principal.PrincipalBaseType == "GOVERNINGPERSON") {

                    $scope.IsGovernorAddressShow = false;
                    $scope.IsGovernorAddressRequired = true;
                //}
                //else {
                //    $scope.IsGovernorAddressShow = true;
                //    $scope.IsGovernorAddressRequired = false;
                //}

                //if ($scope.modalName != "GoverningPerson") {
                //    $scope.principal.PrincipalStreetAddress.StreetAddress1 = (($scope.principal.PrincipalStreetAddress.StreetAddress1 != null && $scope.principal.PrincipalStreetAddress.StreetAddress1.trim() == "" || $scope.principal.PrincipalStreetAddress.StreetAddress1 == undefined) ? $scope.principal.PrincipalStreetAddress.StreetAddress1 = null : $scope.principal.PrincipalStreetAddress.StreetAddress1.trim());

                //    if (!$scope.principal.PrincipalStreetAddress.StreetAddress1) {
                //        $scope.Principals.businessAddress.StreetAddress1.$setValidity("text", false);
                //    }
                //    else {
                //        $scope.Principals.businessAddress.StreetAddress1.$setValidity("text", true);
                //    }
                //}

                $scope.showErrorMessage = true;
                if ($scope[Principals].$valid) {
                    $scope.principal.IsFormation = $scope.isFormation;
                    $scope.showErrorMessage = false;
                    if ($scope.principal.SequenceNo != "") {
                        angular.forEach($scope.principalMemberList, function (incorp) {  //TFS 2672 TFS 2692   
                            if (incorp.SequenceNo == $scope.principal.SequenceNo) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                $scope.principal.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.principal.PrincipalStreetAddress);
                                angular.copy($scope.principal, incorp);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.principalMemberList, function (incorp) {//TFS 2672 TFS 2692   
                            if (maxId == constant.ZERO || incorp.SequenceNo > maxId)
                                maxId = incorp.SequenceNo;
                        });
                        $scope.principal.SequenceNo = ++maxId;
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.principal.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.principal.PrincipalStreetAddress);
                        $scope.principal.PrincipalBaseType = $scope.modalName;
                        $scope.principal.Status = principalStatus.INSERT;
                        $scope.principalMemberList.push($scope.principal); //TFS 2672 TFS 2692  
                    }
                    $scope.resetPrincipal(); // resetPrincipal method is available in this file only.
                }

                //if ($scope.modalName.toUpperCase() == "GOVERNINGPERSON") {
                    $scope.IsGovernorAddressShow = false;
                    $scope.IsGovernorAddressRequired = true;
                //}
                //else {
                //    $scope.IsGovernorAddressShow = true;
                //    $scope.IsGovernorAddressRequired = false;
                //}
            };

            //Edit principal data
            $scope.editPrincipal = function (principaldata) {
                principaldata.PrincipalStreetAddress.Country = principaldata.PrincipalStreetAddress.Country || codes.USA;
                principaldata.PrincipalStreetAddress.State = principaldata.PrincipalStreetAddress.State || codes.USA;
                $scope.principal = angular.copy(principaldata);
                $scope.principal.Status = $scope.principal.PrincipalID == 0 ? principalStatus.INSERT : principalStatus.UPDATE;
                //$scope.addbuttonName = $scope.sectionName == 'Governors' ? "Update " + $scope.sectionName.slice(0, 8) : "Update " + $scope.sectionName;
                $scope.addbuttonName = "Update " + $scope.sectionName;
                //if (principaldata.PrincipalBaseType.toUpperCase() == "GOVERNINGPERSON")
                //{
                    $scope.IsGovernorAddressShow = false;
                    $scope.IsGovernorAddressRequired = true;
                //}
                //else
                //{
                //    $scope.IsGovernorAddressShow = true;
                //    $scope.IsGovernorAddressRequired = false;
                //}
            };

            //Delete principal data
            $scope.deletePrincipal = function (principaldata) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                    if (principaldata.Status=="N")
                    {
                        var index = $scope.principalMemberList.indexOf(principaldata);
                        $scope.principalMemberList.splice(index, 1);
                    }
                    else
                    {
                        principaldata.Status = principalStatus.DELETE;
                    }
                    $scope.resetPrincipal();  // resetPrincipal method is available in this file only.
                });
            };

            // Clear all controls data
            $scope.clearPrincipal = function () {
                $scope.resetPrincipal();  // resetPrincipal method is available in this file only.
            };


            //Get User details during select Principal as I am a respective Principal
            $scope.getPrincipalUserDetails = function (isUserPricipal) {
                var currentTypeID = angular.copy($scope.principal.TypeID);
                if (isUserPricipal) {
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        //$scope.principal.TypeID = response.data.isIndividual == false ? "E" : "I";
                        $scope.principal.TypeID = (response.data.FilerTypeId == "FI" ? ($scope.newUser.isIndividual == false ? "E" : "I") : response.data.Agent.AgentType);
                        //angular.copy($scope.newUser.Agent.AgentType); //angular.copy($scope.newUser.Agent.AgentType);
                        $scope.principal.Status = principalStatus.INSERT;
                        $scope.principal.Name = response.data.FilerTypeId == "FI" ? response.data.Agent.OrganizationName : response.data.Agent.EntityName;//angular.copy($scope.newUser.Agent.EntityName);
                        $scope.principal.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.principal.LastName = angular.copy($scope.newUser.LastName);
                        $scope.principal.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.principal.ConfirmEmailAddress = angular.copy($scope.newUser.ConfirmEmailAddress);
                        $scope.principal.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        $scope.principal.PrincipalStreetAddress = angular.copy($scope.newUser.Address);
                        //Bug Net Id:72164
                        // $scope.principal.PrincipalStreetAddress = angular.copy($scope.newUser.AltAddress);
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    $scope.principal = angular.copy(principalDataScope);
                    $scope.principal.TypeID = currentTypeID;
                    //$scope.addbuttonName = $scope.sectionName == 'Governors' ? "Add " + $scope.sectionName.slice(0, 8) : "Add " + $scope.sectionName;
                    $scope.addbuttonName = "Add " + $scope.sectionName;
                }
            };
            
            //For Governer Address validation Condition
            //if ($scope.modalName.toUpperCase() == 'GOVERNINGPERSON') {
                // governer address required entities not checking adrress fileds are required
                if ($scope.entityTypeId == governerAddressRequiredEntityTypeID.WaProfitCorporation || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaProfessionalServiceCorporation
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaSocialPurposeCorporation || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaPublicUtilityCorporation
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaEmployeeCooperative || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaMassachusettsTrust
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.WaAssociationUnderFishMarketingAct || $scope.entityTypeId == governerAddressRequiredEntityTypeID.ForeignProfitCorporation
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.ForeignProfessionalServiceCorporation || $scope.entityTypeId == governerAddressRequiredEntityTypeID.ForeignPublicUtilityCorporation
                    || $scope.entityTypeId == governerAddressRequiredEntityTypeID.ForeignMassachusettsTrust) {
                    $scope.IsGovernorAddressRequired = true;
                }
                else {
                    // Governer Address optional 
                    $scope.IsGovernorAddressRequired = false;
                }
                $scope.IsGovernorAddressShow = false;
            //}

            //has members flag
                $scope.CheckhasMemberNonProfit = function () {
                    $scope.hasMemberNonProfit = null;
                    if (document.getElementById("rdoHasMemberNonProfitYes").checked == true) {
                        //alert("true");
                        //document.getElementById("hdnHasMemberNonProfit").value = true;
                        $scope.hasMemberNonProfit = true;
                        document.getElementById("rdoHasMemberNonProfitYes").checked = true;
                        document.getElementById("rdoHasMemberNonProfitNo").checked = false;

                        document.getElementById("hdnHasMemberNonProfit").value = true; //Setting hidden
                        document.getElementById("hdnHasMemberNonProfitSelected").value = true; //Setting valid
                    } else if (document.getElementById("rdoHasMemberNonProfitNo").checked == true) {
                        //document.getElementById("hdnHasMemberNonProfit").value = false;
                        //alert("false");
                        $scope.hasMemberNonProfit = false;
                        document.getElementById("rdoHasMemberNonProfitYes").checked = false;
                        document.getElementById("rdoHasMemberNonProfitNo").checked = true;

                        document.getElementById("hdnHasMemberNonProfit").value = false; //Setting hidden
                        document.getElementById("hdnHasMemberNonProfitSelected").value = true; //Setting valid
                    } else {
                        //alert("null");
                        $scope.hasMemberNonProfit = null;
                        document.getElementById("rdoHasMemberNonProfitYes").checked = false;
                        document.getElementById("rdoHasMemberNonProfitNo").checked = false;

                        document.getElementById("hdnHasMemberNonProfit").value = null; //Setting hidden
                        document.getElementById("hdnHasMemberNonProfitSelected").value = false; //Setting invalid
                    };
                    //alert($scope.hasMemberNonProfit);
                //$scope.modal.hasMemberNonProfit = document.getElementById("hdnHasMemberNonProfit").value();

            };

            $(document).ready(function () {
                if (!$scope.isReview) {
                    $scope.CheckhasMemberNonProfit();
                };

            });
        },
    };
});
wacorpApp.directive('principalOffice', function () {
    return {
        templateUrl: 'ng-app/directives/PrincipalOffice/PrincipalOffice.html',
        restrict: 'A',
        scope: {
            principalData: '=?principalData',
            sectionName: '=?sectionName',
            showStreetAddress: '=?showStreetAddress',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            isRequired: '=?isRequired'
        },
        controller: function ($scope, wacorpService, $timeout, $rootScope) {
            $scope.messages = messages;
            $scope.sectionName = $scope.sectionName || "";
            $scope.showStreetAddress = $scope.showStreetAddress || false;
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.principalData.ConfirmEmailAddress = $scope.principalData.EmailAddress;
            $scope.isRequired = true;

            //// As per the Issues in Save & Close and Shopping Cart in 11.1.2 -- 2980, 2961 & 2134
            ////$scope.isSameAsStreet = angular.equals($scope.principalData.PrincipalStreetAddress, $scope.principalData.PrincipalMailingAddress);
            //if ($scope.principalData.PrincipalStreetAddress.FullAddress != "" && $scope.principalData.PrincipalStreetAddress.FullAddress != undefined && $scope.principalData.PrincipalStreetAddress.FullAddress != null
            //            && $scope.principalData.PrincipalMailingAddress.FullAddress != "" && $scope.principalData.PrincipalMailingAddress.FullAddress != undefined && $scope.principalData.PrincipalMailingAddress.FullAddress != null)
            //{
            //    if ($scope.principalData.PrincipalStreetAddress.FullAddress == $scope.principalData.PrincipalMailingAddress.FullAddress) {
            //        $scope.principalData.IsSameAsMailingAddress = true;
            //    }
            //    else {
            //        $scope.principalData.IsSameAsMailingAddress = false;
            //    }
            //}

            var principalScope = {
                PrincipalID: constant.ZERO, SequenceNo: "", FirstName: null, LastName: null, Title: null, Name: null, PhoneNumber: null, EmailAddress: null,
                TypeID: ResultStatus.INDIVIDUAL, PrincipalBaseType: null,
                PrincipalMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                PrincipalStreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, IsSameAsMailingAddress: false, BusinessID: constant.ZERO, Status: null, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null,
                IsACP : false
            };

            $scope.resetScope = {
                PrincipalMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
            };

            $scope.IsAlphaNumeric = function (e) {
                var result = wacorpService.IsAlphaNumeric(e);
                var keyCode = e.which || e.keyCode;
                if (!result && keyCode == 8 || keyCode == 46 || e.key == "ArrowLeft" || e.key == "ArrowRight") { }
                else if (!result && e.key != "Tab") {
                    e.preventDefault();
                }
            };

            $scope.principalData = $scope.principalData ? angular.extend(principalScope, $scope.principalData) : angular.copy(principalScope);
            $scope.principalData.PrincipalStreetAddress.StreetAddress1 = !$scope.principalData.PrincipalStreetAddress.StreetAddress1 ? null : $scope.principalData.PrincipalStreetAddress.StreetAddress1;
            $scope.principalData.PrincipalMailingAddress.StreetAddress1 = !$scope.principalData.PrincipalMailingAddress.StreetAddress1 ? null : $scope.principalData.PrincipalMailingAddress.StreetAddress1;
            $scope.principalData.PrincipalMailingAddress.StreetAddress2 = !$scope.principalData.PrincipalMailingAddress.StreetAddress2 ? null : $scope.principalData.PrincipalMailingAddress.StreetAddress2;
            if ($scope.principalData.PrincipalMailingAddress)
            {
                if ($scope.principalData.PrincipalMailingAddress.Country && $scope.principalData.PrincipalMailingAddress.Country == "CAN")
                    $scope.principalData.PrincipalMailingAddress.City = $scope.principalData.PrincipalMailingAddress.City;
                else if ($scope.principalData.PrincipalMailingAddress.Country && $scope.principalData.PrincipalMailingAddress.Country != "USA")
                    $scope.principalData.PrincipalMailingAddress.City = (($scope.principalData.PrincipalMailingAddress.City && (!$scope.principalData.PrincipalMailingAddress.StreetAddress1 || !$scope.principalData.PrincipalMailingAddress.PostalCode)) ? null : $scope.principalData.PrincipalMailingAddress.City);
                else
                    $scope.principalData.PrincipalMailingAddress.City = !$scope.principalData.PrincipalMailingAddress.City ? null : $scope.principalData.PrincipalMailingAddress.City;
            }

            //Copy Street address to Mailing Addresses on same check box checked
            $scope.CopyStreetFromMailing = function () {

                //Holding Returned Mail Flags for PO
                var isPOMailingAddressReturnedMail = $scope.principalData.PrincipalMailingAddress.IsAddressReturnedMail;

                if ($scope.principalData.IsSameAsMailingAddress)
                {
                    $scope.principalData.PrincipalMailingAddress.StreetAddress1 = angular.copy($scope.principalData.PrincipalStreetAddress.StreetAddress1);
                    $scope.principalData.PrincipalMailingAddress.StreetAddress2 = angular.copy($scope.principalData.PrincipalStreetAddress.StreetAddress2);
                    $scope.principalData.PrincipalMailingAddress.City = angular.copy($scope.principalData.PrincipalStreetAddress.City);
                    $scope.principalData.PrincipalMailingAddress.Country = angular.copy($scope.principalData.PrincipalStreetAddress.Country);
                    $scope.principalData.PrincipalMailingAddress.State = angular.copy($scope.principalData.PrincipalStreetAddress.State);
                    $scope.principalData.PrincipalMailingAddress.Zip5 = angular.copy($scope.principalData.PrincipalStreetAddress.Zip5);
                    $scope.principalData.PrincipalMailingAddress.Zip4 = angular.copy($scope.principalData.PrincipalStreetAddress.Zip4);
                    $scope.principalData.PrincipalMailingAddress.PostalCode = angular.copy($scope.principalData.PrincipalStreetAddress.PostalCode);
                    $scope.principalData.PrincipalMailingAddress.OtherState = angular.copy($scope.principalData.PrincipalStreetAddress.OtherState);

                    $scope.principalData.PrincipalStreetAddress.StreetAddress1 = !$scope.principalData.PrincipalStreetAddress.StreetAddress1 ? null: $scope.principalData.PrincipalStreetAddress.StreetAddress1;
                    $scope.principalData.PrincipalMailingAddress.StreetAddress1 = !$scope.principalData.PrincipalMailingAddress.StreetAddress1 ? null: $scope.principalData.PrincipalMailingAddress.StreetAddress1;
                }
                    //angular.copy($scope.principalData.PrincipalStreetAddress, $scope.principalData.PrincipalMailingAddress);


                else {
                    angular.copy($scope.resetScope.PrincipalMailingAddress, $scope.principalData.PrincipalMailingAddress);
                }

                //Setting the Returned Mail Values
                $scope.principalData.PrincipalMailingAddress.IsAddressReturnedMail = isPOMailingAddressReturnedMail;

                if ($scope.principalData.IsSameAsMailingAddress)
                    $scope.$broadcast("IsMailingPOAddress", true);
                else if (!$scope.principalData.IsSameAsMailingAddress)
                    $scope.$broadcast("IsMailingPOAddress", false);

            };

            $scope.ChangeACP = function () {

                //Holding Returned Mail Flags for PO
                var isPOStreetAddressReturnedMail = $scope.principalData.PrincipalStreetAddress.IsAddressReturnedMail;
                var isPOMailingAddressReturnedMail = $scope.principalData.PrincipalMailingAddress.IsAddressReturnedMail;

                if ($scope.principalData.IsACP) {
                    $("#divACPPOConfirmation").modal('toggle');
                }
                else {
                    if ($scope.principalData.PrincipalStreetAddress.ID && $scope.principalData.PrincipalStreetAddress.ID > 0) {
                        var streetAddressId = $scope.principalData.PrincipalStreetAddress.ID;
                    }
                    angular.copy($scope.resetScope.PrincipalMailingAddress, $scope.principalData.PrincipalStreetAddress);
                    $scope.principalData.IsSameAsMailingAddress = false;
                    $scope.CopyStreetFromMailing(); // CopyStreetFromMailing method is available in this file only.
                    if (streetAddressId && streetAddressId>0)
                        $scope.principalData.PrincipalStreetAddress.ID = streetAddressId;
                }

                $scope.principalData.PrincipalStreetAddress.IsACPChecked = $scope.principalData.IsACP;

                //Setting the Returned Mail Values
                $scope.principalData.PrincipalStreetAddress.IsAddressReturnedMail = isPOStreetAddressReturnedMail;
                $scope.principalData.PrincipalMailingAddress.IsAddressReturnedMail = isPOMailingAddressReturnedMail;

                //if (!$scope.principalData.IsACP)
                //    $rootScope.$broadcast("InvokeValidAddressCheck");
                $scope.PrincipalOffice.businessAddress.ValidAddressCheck.$setValidity("text", true);
            }

            $scope.clickOk = function () {
                $("#divACPPOConfirmation").modal('toggle');
                //Holding Returned Mail Flags for PO
                var isPOStreetAddressReturnedMail = $scope.principalData.PrincipalStreetAddress.IsAddressReturnedMail;

                var poaddress = wacorpService.getpoboxAddress();
                if ($scope.principalData.PrincipalStreetAddress.ID && $scope.principalData.PrincipalStreetAddress.ID>0)
                {
                    var streetAddressId = $scope.principalData.PrincipalStreetAddress.ID;
                }
                angular.copy(poaddress, $scope.principalData.PrincipalStreetAddress);
                $scope.principalData.IsSameAsMailingAddress = true;
                $scope.CopyStreetFromMailing(); // CopyStreetFromMailing method is available in this file only.
                if (streetAddressId && streetAddressId>0)
                    $scope.principalData.PrincipalStreetAddress.ID = streetAddressId;

                //Setting the Returned Mail Values
                $scope.principalData.PrincipalStreetAddress.IsAddressReturnedMail = isPOStreetAddressReturnedMail;
            };

            $scope.cancel = function () {
                $scope.principalData.IsACP = false;
                $("#divACPPOConfirmation").modal('toggle');
            };

            $scope.validatePoBox = function () {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.principalData.IsACP = wacorpService.validatePoBox($scope.principalData.PrincipalStreetAddress.StreetAddress1);
                if ($scope.principalData.IsACP) {
                    $scope.principalData.IsSameAsMailingAddress = true;
                }
            }

            $scope.init = function () {
                $timeout(function () {
                    $scope.validatePoBox(); // validatePoBox method is available in this file only
                }, 1000);
            }

            $scope.checkPOEmail = function () {
                if ($scope.PrincipalOffice.EmailID.$viewValue =="" && ($scope.principalData.EmailAddress == "" || $scope.principalData.EmailAddress == null || $scope.principalData.EmailAddress == undefined)) {
                    //Here we are calling the method which is declared in another controller(EmailOption.js)
                    $rootScope.$broadcast('onEmailEmpty');
                }
            };

            //to clear PO mailing Address when Street address is modified
            var clearPOMailingAddress = $scope.$on("ClearPOMailingAddress", function (evt, data) {

                //Holding Returned Mail Flags for PO
                var isPOMailingAddressReturnedMail = $scope.principalData.PrincipalMailingAddress.IsAddressReturnedMail;
                if ($scope.principalData.IsSameAsMailingAddress) {
                    if (wacorpService.compareAddress($scope.principalData.PrincipalStreetAddress, $scope.principalData.PrincipalMailingAddress))
                    {
                        $scope.principalData.IsSameAsMailingAddress = false;
                        $scope.CopyStreetFromMailing();
                    }
                }

                //Setting the Returned Mail Values
                $scope.principalData.PrincipalMailingAddress.IsAddressReturnedMail = isPOMailingAddressReturnedMail;
                evt.defaultPrevented = true;
            });
            $scope.$on('$destroy', clearPOMailingAddress);
        },
    };
});
wacorpApp.directive('purposeAndPowers', function () {
    return {
        templateUrl: 'ng-app/directives/PurposeAndPowers/PurposeAndPowers.html',
        restrict: 'A',
        scope: {
            isReview: '=?isReview',
            purposePowerData: '=?purposePowerData',
            showErrorMessage: '=?showErrorMessage',
        },
        controller: function ($scope) {
            $scope.messages = messages;
            $scope.isReview = $scope.isReview || false;
            $scope.purposePowerData = $scope.purposePowerData || {};
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.$watch(function () {
                $scope.purposePowerData = $scope.purposePowerData || {};
                $scope.isRequired = ($scope.purposePowerData.IsEmployees || $scope.purposePowerData.IsLocalState || $scope.purposePowerData.IsEnvironment) ? false : true;
            });
        },
    };
});
wacorpApp.directive('initialBoardDirector', function () {
    return {
        templateUrl: 'ng-app/directives/InitialBoardDirectors/InitialBoardDirector.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            directorsList: '=?directorsList',
            isReview: '=?isReview',
            isFormation: '=?isFormation',

        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.directorsList = $scope.directorsList || [];
            $scope.isReview = $scope.isReview || false;
            $scope.isFormation = $scope.isFormation || false;
            $scope.sectionType = 'Initial Director Type:';
            //if ($rootScope.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION ||
            //    $rootScope.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION)
            //{
            //    $scope.addbutton = "Add " + $scope.sectionName.replace('Board of ', '').replace('Directors', 'Director');

            //} else{
            $scope.addbutton = "Add Director";// + $scope.sectionName.replace('Directors', 'Director');
            //}
          
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            //if ($rootScope.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION ||
            //    $rootScope.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION)
            //{
                $scope.isUserDirectorText = sectionNames.INITIALDIRECTOR;

            //} else {
            //$scope.isUserDirectorText = sectionNames.INITIALBOARDDIRECTOR;
            //}
           

            $scope.director = {
                PrincipalID: constant.ZERO, SequenceNo: "", FirstName: null, LastName: null, Title: null, Name: null, PhoneNumber: null, EmailAddress: null, IsFormation: false,
                TypeID: ResultStatus.INDIVIDUAL, PrincipalBaseType: null, PrincipalMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, PrincipalStreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null,
                    PostalCode: null, County: null, CountyName: null
                }, IsSameAsMailingAddress: false, BusinessID: constant.ZERO, Status: principalStatus.INSERT, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            // If director Type ID is INDIVIDUAL Entiry name text box is empty.
            $scope.getDirectorTypeChange = function (directorTypeID) {
                if (directorTypeID == ResultStatus.INDIVIDUAL) {
                    $scope.director.Name = '';
                }
            };

            var directorDataScope = {
                PrincipalID: constant.ZERO, SequenceNo: "", FirstName: null, LastName: null, Title: null, Name: null, PhoneNumber: null, EmailAddress: null, IsFormation: false,
                TypeID: ResultStatus.INDIVIDUAL, PrincipalBaseType: null, PrincipalMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, PrincipalStreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, IsSameAsMailingAddress: false, BusinessID: constant.ZERO, Status: principalStatus.INSERT, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            //Reset the principal
            $scope.resetDirector = function () {
                $scope.director = angular.copy(directorDataScope);
                //if ($rootScope.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION ||
                //    $rootScope.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION)
                //{
                $scope.addbutton = "Add Director";// + $scope.sectionName.replace('Board of ', '');

                //} else {
                //$scope.addbutton = "Add " + $scope.sectionName;
                //}               
                $scope.showErrorMessage = false;
                $scope.isDirectorChecked = false;
                $scope.InitialBoardDirector.businessAddress.StreetAddress1.$setValidity("text", true);
            };

            //Add principal data
            $scope.AddDirector = function (InitialBoardDirector) {
                $scope.showErrorMessage = true;

                $scope.director.PrincipalStreetAddress.StreetAddress1 = (($scope.director.PrincipalStreetAddress.StreetAddress1 != null && $scope.director.PrincipalStreetAddress.StreetAddress1.trim() == "" || $scope.director.PrincipalStreetAddress.StreetAddress1 == undefined) ? $scope.director.PrincipalStreetAddress.StreetAddress1 = null : $scope.director.PrincipalStreetAddress.StreetAddress1.trim());
                if (!$scope.director.PrincipalStreetAddress.StreetAddress1) {
                    $scope.InitialBoardDirector.businessAddress.StreetAddress1.$setValidity("text", false);
                }
                else {
                    $scope.InitialBoardDirector.businessAddress.StreetAddress1.$setValidity("text", true);
                }

                if ($scope[InitialBoardDirector].$valid) {
                    $scope.director.IsFormation = $scope.isFormation;
                    $scope.showErrorMessage = false;
                    if ($scope.director.SequenceNo != "") {
                        angular.forEach($scope.directorsList, function (incorp) {
                            if (incorp.SequenceNo == $scope.director.SequenceNo) {
                                $scope.director.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.director.PrincipalMailingAddress);
                                angular.copy($scope.director, incorp);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.directorsList, function (incorp) {
                            if (maxId == constant.ZERO || incorp.SequenceNo > maxId)
                                maxId = incorp.SequenceNo;
                        });
                        $scope.director.SequenceNo = ++maxId;
                        $scope.director.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.director.PrincipalMailingAddress);
                        $scope.director.PrincipalBaseType = $scope.modalName;
                        $scope.director.Status = principalStatus.INSERT;
                        $scope.directorsList.push($scope.director);
                    }
                    $scope.resetDirector(); // resetDirector method is available in this file only.
                }
            };

            //Edit principal data
            $scope.editDirector = function (directordata) {
                directordata.PrincipalMailingAddress.Country = directordata.PrincipalMailingAddress.Country || codes.USA;
                directordata.PrincipalMailingAddress.State = directordata.PrincipalMailingAddress.State || codes.USA;
                $scope.director = angular.copy(directordata);
                $scope.director.Status = $scope.director.PrincipalID == 0 ? principalStatus.INSERT : principalStatus.UPDATE;
                //if ($rootScope.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION ||
                //   $rootScope.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION) {
                $scope.addbutton = "Update Director";// + $scope.sectionName.replace('Board of ', '');

                //} else {
                //    $scope.addbutton = "Update " + $scope.sectionName;
                //}
            };

            //Delete principal data
            $scope.deleteDirector = function (directordata) {
               
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                   
                    if (directordata.Status == "N") {
                        var index = $scope.directorsList.indexOf(directordata);
                        $scope.directorsList.splice(index, 1);
                    }
                    else {
                        directordata.Status = principalStatus.DELETE;
                    }
                    $scope.resetDirector(); // resetDirector method is available in this file only.
                });
            };

            // Clear all controls data
            $scope.clearDirector = function () {
                $scope.resetDirector(); // resetDirector method is available in this file only.
            };

            //Get User details during select I am an Intial board of director
            $scope.getDirectorUserDetails = function (isUserDirector) {
                var currentTypeID = angular.copy($scope.director.TypeID);
                if (isUserDirector) {
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        $scope.director.TypeID = (response.data.FilerTypeId == "FI" ? ($scope.newUser.isIndividual == false ? "E" : "I") : response.data.Agent.AgentType);// angular.copy($scope.newUser.Agent.AgentType);  //response.data.isIndividual == false ? "E": "I"; //angular.copy($scope.newUser.Agent.AgentType);
                        //$scope.director.TypeID = response.data.isIndividual == false ? "E" : "I";  //response.data.isIndividual == false ? "E" : "I";//angular.copy($scope.newUser.Agent.AgentType);
                        $scope.director.Status = principalStatus.INSERT;
                        $scope.director.Name = response.data.FilerTypeId == "FI" ? response.data.Agent.OrganizationName : response.data.Agent.EntityName;//angular.copy($scope.newUser.Agent.EntityName);
                        $scope.director.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.director.LastName = angular.copy($scope.newUser.LastName);
                        $scope.director.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.director.ConfirmEmailAddress = angular.copy($scope.newUser.ConfirmEmailAddress);
                        $scope.director.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        $scope.director.PrincipalStreetAddress = angular.copy($scope.newUser.Address);
                        // Bug net id:72164
                      //  $scope.director.PrincipalStreetAddress = angular.copy($scope.newUser.AltAddress);
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    $scope.director = angular.copy(directorDataScope);
                    $scope.director.TypeID = currentTypeID;
                    $scope.addbutton = "Add Director";
                }
            };
        },
    };
});
wacorpApp.directive('dbaName', function () {
    return {
        templateUrl: 'ng-app/directives/DBAName/DBAName.html',
        restrict: 'A',
        scope: {
            entity: '=?entity',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService) {
            $scope.$watch('entity.IsDBAInUse', function () {
                if (!$scope.entity.IsDBAInUse && $scope.businessNames)
                {
                    $scope.businessNames.length = 0;
                }
            });
            $scope.businessNameNotAvailCount = 0;
            if ($scope.entity.DBABusinessName)
            {
                $scope.entity.IsDBAInUse = true;
                $scope.entity.isDBANameAvailable = true;
            }

            //This flag is used only for Requalification filings for Lookup - Ticket - 75938
            if ($scope.entity.BusinessFiling.FilingTypeName == uploadedFiles.Requalification) {
                $scope.entity.isDBANameAvailable = false; //75938
            }
            
            $scope.messages = messages;
            $scope.entity = $scope.entity || {};
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            //$scope.entity.oldDBAName = angular.copy($scope.entity.DBABusinessName || '');
            $scope.entity.hdnDBABusinessName = angular.copy($scope.entity.DBABusinessName || '');
            $scope.entity.NewDBABusinessName = !angular.isNullorEmpty($scope.entity.NewDBABusinessName) ? $scope.entity.NewDBABusinessName : $scope.entity.DBABusinessName;

            $scope.isValidIndicator = function () {
                //$scope.IsBusinessNameAvailable = ($scope.entity.DBABusinessName != null && $scope.entity.DBABusinessName != "") ?
                //(($scope.entity.oldDBAName != $scope.entity.DBABusinessName) ? $scope.messages.DBAName.businessNameAvailable : "") : "";
                $scope.businessNameNotAvailCount = 0;
                $scope.entity.isDBANameAvailable = $scope.entity.DBABusinessName && ($scope.entity.OldDBABusinessName == $scope.entity.DBABusinessName);

                // valid indicators
                if ($scope.entity.DBABusinessName)
                    $scope.isValidDBAIndicator(); // isValidDBAIndicator method is available in this file only
            };

            $scope.isValidDBAIndicator = function (isLookup) {
                $scope.entity.invalidDBAIndicator = false;
                var indicatorsCSV = null;
                var indicatorslist = null;
                var indicatorsMustNotCSV = null;
                var IndicatorsDisplay = null;
                indicatorsMustNotCSV = $scope.entity.Indicator.IndicatorsMustNotCSV;
                // is dental service checked true
                if ($scope.entity.Indicator.isDentalCheck) {
                    indicatorsCSV = $scope.entity.Indicator.PSIndicatorsCSV;
                    indicatorslist = $scope.entity.Indicator.PSIndicatorList;
                    indicatorsDisplay = $scope.entity.Indicator.PSIndicatorsDisplay;
                }
                else {
                    indicatorsCSV = $scope.entity.Indicator.IndicatorsCSV;
                    indicatorslist = $scope.entity.Indicator.Indicators;
                    indicatorsDisplay = $scope.entity.Indicator.IndicatorsDisplay;
                }
                var isValid = constant.ZERO;
                var isInValidIndicator = constant.ZERO;
                var entityName;

                if ($scope.entity.isUpdate != undefined && $scope.entity.isUpdate && $scope.entity.isUpdate != false) {
                    entityName = $scope.entity.DBABusinessName + ' ' + indicatorsCSV;
                    entityName = entityName.toLowerCase().replace(/[{|}|(|)|-|;|'|\"]/g, '');
                }
                else {
                    entityName = $scope.entity.DBABusinessName != null ? $scope.entity.DBABusinessName.toLowerCase().replace(/[{|}|(|)|-|;|'|\"]/g, '') : null;
                }

                if (indicatorsCSV != null && indicatorsCSV != undefined && indicatorsCSV != '') {

                    angular.forEach(indicatorslist, function (value) {

                        value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                        //isValid = new RegExp("^" + value + "\\s").test(entityName) ? isValid + constant.ONE : isValid;
                        // Start With indicator
                        if (new RegExp("^" + value + "\\s").test(entityName)) {
                            if (entityName.indexOf(value + ' ') != -1) {
                                isValid = isValid + constant.ONE;
                                return;
                            }
                        }
                    });

                    if (isValid == constant.ZERO) {
                        angular.forEach(indicatorslist, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            //isValid = new RegExp("\\s" + value + "\\s").test(entityName) ? isValid + constant.ONE : isValid;
                            // Middile With indicator
                            if (new RegExp("\\s" + value + "\\s").test(entityName)) {
                                if (entityName.indexOf(' ' + value + ' ') != -1) {
                                    isValid = isValid + constant.ONE;
                                    return;
                                }
                            }
                        });
                    }
                    if (isValid == constant.ZERO) {
                        angular.forEach(indicatorslist, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            //isValid = new RegExp("\\s" + value + "$").test(entityName) ? isValid + constant.ONE : isValid;
                            // Last With indicator
                            if (new RegExp("\\s" + value + "$").test(entityName)) {
                                if (entityName.indexOf(' ' + value) != -1) {
                                    isValid = isValid + constant.ONE;
                                    return;
                                }
                            }
                        });
                    }
                }
                else {
                    isValid = constant.ONE; //For all entities we are not going to have Indicators, that's the reason default we are considering as true.
                }

                if (indicatorsMustNotCSV != null && indicatorsMustNotCSV != undefined && indicatorsMustNotCSV != '') {

                    var isNonCorp = false;
                    var aNonprofitCorp = "a nonprofit corporation";
                    var aNonprofitMutualCorp = "a nonprofit mutual corporation";
                    var corporation = "corporation";

                    if (entityName != "" && entityName != null) {
                        isNonCorp = new RegExp("^" + aNonprofitCorp + "\\s").test(entityName) || new RegExp("^" + aNonprofitMutualCorp + "\\s").test(entityName);

                        if (!isNonCorp) {
                            isNonCorp = new RegExp("\\s" + aNonprofitCorp + "\\s").test(entityName) || new RegExp("\\s" + aNonprofitMutualCorp + "\\s").test(entityName);
                        }
                        if (!isNonCorp) {
                            isNonCorp = new RegExp("\\s" + aNonprofitCorp + "$").test(entityName) || new RegExp("\\s" + aNonprofitMutualCorp + "$").test(entityName);
                        }
                    }

                    var indicatorsMustNot = indicatorsMustNotCSV.toLowerCase().split(',');
                    angular.forEach(indicatorsMustNot, function (value) {

                        value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                        if (isNonCorp && value == corporation) {
                            isInValidIndicator = constant.ZERO;
                        }
                        else {
                            //isInValidIndicator = new RegExp("^" + value + "\\s").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                            // Start With indicator
                            if (new RegExp("^" + value + "\\s").test(entityName)) {
                                if (entityName.indexOf(value + ' ') != -1) {
                                    isInValidIndicator = isInValidIndicator + constant.ONE;
                                    return;
                                }
                            }
                        }
                    });

                    if (isInValidIndicator == constant.ZERO) {
                        angular.forEach(indicatorsMustNot, function (value) {

                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            if (isNonCorp && value == corporation) {
                                isInValidIndicator = constant.ZERO;
                            }
                            else {
                                // isInValidIndicator = new RegExp("\\s" + value + "\\s").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                                // Middile With indicator
                                if (new RegExp("\\s" + value + "\\s").test(entityName)) {
                                    if (entityName.indexOf(' ' + value + ' ') != -1) {
                                        isInValidIndicator = isInValidIndicator + constant.ONE;
                                        return;
                                    }
                                }
                            }
                        });
                    }
                    if (isInValidIndicator == constant.ZERO) {

                        angular.forEach(indicatorsMustNot, function (value) {

                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            if (isNonCorp && value == corporation) {
                                isInValidIndicator = constant.ZERO;
                            }
                            else {
                                // isInValidIndicator = new RegExp("\\s" + value + "$").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                                // Last With indicator
                                if (new RegExp("\\s" + value + "$").test(entityName)) {
                                    if (entityName.indexOf(' ' + value) != -1) {
                                        isInValidIndicator = isInValidIndicator + constant.ONE;
                                        return;
                                    }
                                }
                            }
                        });
                    }
                }

                var dbaInvalidMsg = "";
                if (isInValidIndicator >= 1) {
                    $scope.indicatorValidMessage = "The doing business as (dba) name containing invalid indicator like (" + indicatorsMustNotCSV.replace(/,/g, ', ').toUpperCase() + ").";
                }
                else if ($scope.entity.DBABusinessName != null && $scope.entity.DBABusinessName != "") {
                    $scope.indicatorValidMessage = isValid > constant.ZERO ? "" : "The doing business as (dba) name requested does not contain the necessary designation. Please input one of the required designations (" + indicatorsDisplay.replace(/,/g, ', ').toUpperCase() + ").";// TFS ID 12017
                }

                if ($scope.indicatorValidMessage)
                {
                    $scope.entity.invalidDBAIndicator = true;
                }
            };


            $scope.searchBusinessNames = function (DBAName) {
                $scope.isValidIndicator(); //Ticket - 75938
                $scope.businessNameNotAvailCount = 0;
                $scope.showErrorMessage = true;
                $scope.IsBusinessNameAvailable = "";
                $scope.entity.isDBANameAvailable = false;
                $scope.validateBusinessName = true;
                if ($scope.entity.DBABusinessName != null) {
                    $scope.entity.hdnDBABusinessName = $scope.entity.DBABusinessName.toUpperCase();
                    if ($scope[DBAName].txtDBABusinessName.$valid) {
                        $scope.validateBusinessName = false;
                        var config = {
                            params: { DBAName: $scope.entity.DBABusinessName.toUpperCase(), businessName: $scope.entity.BusinessName, isEntityValid: false, businessId: angular.isNullorEmpty($scope.entity.BusinessID) ? 0 : $scope.entity.BusinessID, isInhouse: false }
                        };
                        // GetBusinessDBANames method is available in constants.js
                        wacorpService.get(webservices.Common.GetBusinessDBANames, config, completed, failed);
                        function completed(response) {
                            $scope.businessNames = response.data;
                            angular.forEach($scope.businessNames, function (item, index) {
                                if (item.AvailableStatus == "Available")
                                {
                                    $scope.entity.isDBANameAvailable = true;
                                    $scope.businessNameNotAvailCount = 0;
                                }          

                                if (item.AvailableStatus == "Not Available")
                                {
                                    $scope.businessNameNotAvailCount = 1;
                                    $scope.entity.isDBANameAvailable = false;
                                }
                                  

                            });
                            $scope.UBINumber = (response.UBINumber == "" || response.UBINumber == null || response.UBINumber == undefined ? "" : response.UBINumber);
                        }
                        function failed(response) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog(JSON.stringify(response.data));

                            //wacorpService.alertDialog(response.data);
                        }
                    }
                }
            };

            $scope.selectBusiness = function (businessName) {
                $scope.entity.DBABusinessName = businessName;
            };
            var validateDBAName=$scope.$on('isDBAValid', function (e) {
                $scope.isValidDBAIndicator();
            });

            $scope.$on('$destroy', validateDBAName);

            var checkDBAIndicatorValidation = $scope.$on("checkDBAIndicator", function (evt, data) {
                $scope.isValidDBAIndicator();
            });

            $scope.$on('$destroy', checkDBAIndicatorValidation);
        },
    };
});
wacorpApp.directive('uploadFiles', function ($http) {
    return {
        templateUrl: 'ng-app/directives/UploadFiles/UploadFiles.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            showOtherBox: '=?showOtherBox',
            isReview: '=?isReview',
            uploadData: '=?uploadData',
            uploadList: '=?uploadList',
            showErrorMessage: '=?showErrorMessage',
            note: '=?note',
            fileSize: '=?fileSize',
            fileType: '=?fileType',
            validateFileType: '=?validateFileType',
            validateFileSize: '=?validateFileSize',
            certificateOfExistenceNote: '=?certificateOfExistenceNote',
            documentTypeId: '=?documentTypeId',
            documentType: '=?documentType',
        },
        controller: function ($scope, $http, wacorpService, $rootScope) {

            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.showOtherBox = $scope.showOtherBox || false;
            $scope.isReview = $scope.isReview || false;
            $scope.uploadData = $scope.uploadData || {};
            $scope.uploadData.IsArticalsExist = angular.isNullorEmpty($scope.uploadData.IsArticalsExist) ? true : $scope.uploadData.IsArticalsExist;
            $scope.uploadList = $scope.uploadList || [];
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.note = angular.isNullorEmpty($scope.note) ? "" : $scope.note;
            $scope.fileSize = angular.isNullorEmpty($scope.fileSize) ? uploadedFiles.FILESIZE : $scope.fileSize;
            $scope.fileType = angular.isNullorEmpty($scope.fileType) ? uploadedFiles.FILETYPES : $scope.fileType;
            $scope.validateFileType = angular.isNullorEmpty($scope.validateFileType) ? true : $scope.validateFileType;
            $scope.validateFileSize = angular.isNullorEmpty($scope.validateFileSize) ? true : $scope.validateFileSize;
            $scope.fileSizeMessage = $scope.messages.UploadFiles.fileSizeNote.replace('{0}', ($scope.fileSize / (uploadedFiles.FILESIZEMB)));
            $scope.fileTypeMessage = $scope.messages.UploadFiles.fileTypeNote.replace('{0}', $scope.fileType.toString());
            $scope.certificateOfExistenceNote = angular.isNullorEmpty($scope.certificateOfExistenceNote) ? "" : $scope.certificateOfExistenceNote;
            $scope.documentTypeId = $scope.documentTypeId || '';
            $scope.documentType = $scope.documentType || '';

            $scope.$watch(function () {

                $scope.UploadLableText = $scope.sectionName.replace($scope.sectionName.split(' ')[0], '').trim();
                $scope.UploadLableText = $scope.UploadLableText == 'of Incorporation' ? 'Articles of Incorporation' : $scope.UploadLableText;

                if ($scope.modalName == uploadedFiles.CLEARANCECERTIFICATEMODAL)
                    $scope.UploadLableText = $scope.messages.UploadFiles.clearanceCertificateUploadText;

                if ($scope.sectionName == uploadedFiles.CertificateOfFormation)
                    $scope.UploadLableText = $scope.sectionName;

                $scope.uploadConfirmation = $scope.messages.UploadFiles.uploadFilesSectionConfirmation.replace('{0}', $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName);
                $scope.uploadText = "";
              
                if ($scope.modalName == uploadedFiles.ARTICLESOFINCORPORATIONMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.articleUploadText;
                else if ($scope.modalName == uploadedFiles.CERTIFICATEOFFORMATIONMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.certificateofFormationUploadText;
                else if ($scope.modalName == uploadedFiles.CLEARANCECERTIFICATEMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.clearanceCertificateUploadText;
                else if ($scope.modalName == uploadedFiles.CERTIFICATEOFEXISTENCEMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.certificateOfExistenceUploadText;              
                else
                    $scope.uploadText = $scope.sectionName;
            });

            // NOW UPLOAD THE FILES.
            $scope.upload = function (e) {
                var validFormats = $scope.fileType;
                $scope.files = [];
                $scope.$apply(function () {
                    for (var i = constant.ZERO; i < e.files.length; i++) {
                        $scope.files.push(e.files[i])
                    }
                });
                var data = new FormData();
                var selectedFiles = [];
                for (var i in $scope.files) {
                    data.append("uploadedFile", $scope.files[i]);
                    var value = $scope.files[i];
                    if (value.name != "") {
                        var fileInfo = {
                            extenstion: value.name.substring(value.name.lastIndexOf('.') + constant.ONE).toLowerCase(),
                            size: value.size,
                        };
                        selectedFiles.push(fileInfo);
                    }                   
                }
                angular.forEach(selectedFiles, function (file) {
                    var fileTypeindex = constant.ZERO, filesizeValid = true, formatValid = false;
                    if ($scope.validateFileType) {
                        // fileTypeindex = validFormats.indexOf(file.extenstion);
                        angular.forEach(validFormats, function (item) {
                            if (item.replace(/\s/g, '') == file.extenstion) {
                                formatValid = true;
                            }
                        });
                        fileTypeindex = formatValid ? 1 : -1;
                    }
                 
                  
                    if ($scope.validateFileSize)
                        filesizeValid = file.size <= $scope.fileSize;
                    if (fileTypeindex > constant.NEGATIVE && filesizeValid) {
                 
                        if ($scope.documentType == uploadedFiles.CertificateofLimitedPartnership) {
                            $scope.documentTypeId = docuementTypeIds.UploadCertificateofLimitedPartnership;
                     
                        } else if ($scope.documentType == uploadedFiles.CertificateOfFormation) {
                            $scope.documentTypeId = docuementTypeIds.UploadCertificateofFormation;
                        }
                        else if ($scope.documentType == uploadedFiles.ArticlesofIncorporation) {
                            $scope.documentTypeId = docuementTypeIds.UploadArticlesofIncorporation;
                        }
                        else if ($scope.documentType == uploadedFiles.CertificateofExistence) {

                            $scope.documentTypeId = docuementTypeIds.UploadCertificateofExistence;
                        } else if ($scope.documentType == uploadedFiles.PURPOSEANDPOWERS) {
                            $scope.documentTypeId = docuementTypeIds.PURPOSEANDPOWERS;
                        } else if ($scope.documentType == uploadedFiles.CertificateofLimitedLiabilityLimitedPartnership) {
                            $scope.documentTypeId = docuementTypeIds.CertificateofLimitedLiabilityLimitedPartnership;
                        }
                        else if ($scope.documentType == uploadedFiles.RevenueClearanceCertificate) {
                            $scope.documentTypeId = docuementTypeIds.RevenueClearanceCertificate;
                        }
                        else if ($scope.documentType == uploadedFiles.CertificateofLimitedLiabilityPartnership) {
                            $scope.documentTypeId = docuementTypeIds.UploadCertificateofLimitedLiabilityPartnership;
                        }
                        else if ($scope.documentType == uploadedFiles.PreferredStock) {
                            $scope.documentTypeId = docuementTypeIds.PreferredStock;
                        }
                        else if ($scope.documentType == uploadedFiles.PreparedAmendment) {
                            $scope.documentTypeId = docuementTypeIds.PreparedAmendment;
                        }
                        else
                            $scope.documentType = $scope.sectionName;
                        // fileUpload method is available in constants.js
                        var uri = webservices.Common.fileUpload + '?DocumentType=' + $scope.documentType + '&DocumentTypeId=' + $scope.documentTypeId + '&FullUserName=' + ($rootScope.repository.loggedUser != undefined ? $rootScope.repository.loggedUser.FullUserName : '');
                        if ($rootScope.repository.loggedUser != undefined)
                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                        $http({
                            url: uri,
                            method: "POST",
                            data: data,
                            transformRequest: angular.identity,
                            headers: {
                                'Content-Type': undefined
                            }
                        }).success(function (result) {
                            $(e).closest('form')[0].reset();
                            $scope.uploadList.push(result[constant.ZERO]);
                        }).error(function (result, status) {
                            $(e).closest('form')[0].reset();
                            // Folder Name: app Folder
                            // Alert Name: uploadFailed method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.uploadFailed);
                        });
                        $scope.filenotSupported = "";
                    }
                    else {
                        if (fileTypeindex == constant.NEGATIVE)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (fileTypeindex == constant.NEGATIVE && file.size > $scope.fileSize)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (file.size > $scope.fileSize) {
                            var size = ($scope.fileSize / (uploadedFiles.FILESIZEMB));
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileSizeNotSupport.replace('{0}', size);
                        }
                    }
                });
            }

            $scope.deleteFile = function (file, index) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    // deleteUploadedFile method is available in constants.js
                    wacorpService.post(webservices.Common.deleteUploadedFile, file,
                        function (response) {
                            //var index = $scope.uploadList.indexOf(response);
                            $scope.uploadList.splice(index, constant.ONE);
                            // Folder Name: app Folder
                            // Alert Name: fileDelete method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDelete);
                        },
                        function (response) {
                            // Folder Name: app Folder
                            // Alert Name: fileDeleteFailed method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDeleteFailed);
                        }
                    );
                });
            };

            $scope.deleteAllFiles = function (files) {

                //if (files[constant.ZERO] != undefined) {
                //    files[constant.ZERO].TempFileLocation = "";
                //}

                if (files.length > constant.ZERO) {
                    var fileList = { files: files }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        // deleteAllUploadedFiles method is available in constants.js
                        wacorpService.post(webservices.Common.deleteAllUploadedFiles, files,
                            function (response) {
                                $scope.uploadList = [];
                            },
                            function (response) {
                            }
                        );
                    },
                    function () {
                        $scope.uploadData.IsArticalsExist = true;
                    });
                }
            };

            $scope.uploadClick = function () {
                var uploadID = $scope.modalName + '_UploadArticals';
                $('#' + uploadID).trigger('click');
                //var evObj = document.createEvent('MouseEvents');
                //evObj.initMouseEvent('click', true, true, window);
                //uploadID.dispatchEvent(evObj);
            };
        },
    };
});
wacorpApp.directive('genericUploadFiles', function ($http) {
    return {
        templateUrl: 'ng-app/directives/UploadFiles/GenericUploadFiles.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            showOtherBox: '=?showOtherBox',
            isReview: '=?isReview',
            uploadList: '=?uploadList',
            otherComments: '=?otherComments',
            showErrorMessage: '=?showErrorMessage',
            fileSize: '=?fileSize',
            fileType: '=?fileType',
            validateFileType: '=?validateFileType',
            validateFileSize: '=?validateFileSize',
            purposeAndPowersText: '=?purposeAndPowersText',
            documentTypeId: '=?documentTypeId',
            documentType: '=?documentType',
        },
        controller: function ($scope, $http, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.showOtherBox = $scope.showOtherBox || false;
            $scope.isReview = $scope.isReview || false;
            $scope.otherComments = $scope.otherComments || "";
            $scope.uploadList = $scope.uploadList || [];
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.fileSize = angular.isNullorEmpty($scope.fileSize) ? uploadedFiles.FILESIZE : $scope.fileSize;
            $scope.fileType = angular.isNullorEmpty($scope.fileType) ? uploadedFiles.FILETYPES : $scope.fileType;
            $scope.validateFileType = angular.isNullorEmpty($scope.validateFileType) ? true : $scope.validateFileType;
            $scope.validateFileSize = angular.isNullorEmpty($scope.validateFileSize) ? true : $scope.validateFileSize;
            $scope.purposeAndPowersText = angular.isNullorEmpty($scope.purposeAndPowersText) ? "" : $scope.purposeAndPowersText;
            $scope.fileSizeMessage = $scope.messages.UploadFiles.fileSizeNote.replace('{0}', ($scope.fileSize / (uploadedFiles.FILESIZEMB)));
            $scope.fileTypeMessage = ($scope.fileType.toString() == 'NONE' || $scope.fileType.toString() == '') ? "" : $scope.messages.UploadFiles.fileTypeNote.replace('{0}', $scope.fileType.toString());
            $scope.documentTypeId = $scope.documentTypeId || '';
            $scope.documentType = $scope.documentType || '';

            $scope.$watch(function () {
                $scope.uploadConfirmation = $scope.messages.UploadFiles.uploadFilesSectionConfirmation.replace('{0}', $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName);
                $scope.uploadText = "";
                if ($scope.modalName == uploadedFiles.ARTICLESOFINCORPORATIONMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.articleUploadText;
                else if ($scope.modalName == uploadedFiles.CERTIFICATEOFFORMATIONMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.certificateofFormationUploadText;
                else if ($scope.modalName == uploadedFiles.CLEARANCECERTIFICATEMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.clearanceCertificateUploadText;
                else if ($scope.modalName == uploadedFiles.CERTIFICATEOFEXISTENCEMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.certificateOfExistenceUploadText;
                else
                    $scope.uploadText = $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName;

                if ( $scope.uploadText.slice(1) == "a List of Addresses Used") {
                    $scope.uploadText = "A List of Addresses Used"
                }
                else
                    $scope.uploadText;
            });

            // NOW UPLOAD THE FILES.
            $scope.upload = function (e) {
                var validFormats = $scope.fileType;
                $scope.files = [];
                $scope.$apply(function () {
                    for (var i = constant.ZERO; i < e.files.length; i++) {
                        $scope.files.push(e.files[i])
                    }
                });
                var data = new FormData();
                var selectedFiles = [];
                for (var i in $scope.files) {
                    data.append("uploadedFile", $scope.files[i]);
                    var value = $scope.files[i];
                    if (value.name != "") {
                        var fileInfo = {
                            extenstion: value.name.substring(value.name.lastIndexOf('.') + constant.ONE).toLowerCase(),
                            size: value.size,
                        };
                        selectedFiles.push(fileInfo);
                    }
                }
                angular.forEach(selectedFiles, function (file) {
                    var fileTypeindex = constant.ZERO, filesizeValid = true,formatValid=false;
                    if ($scope.validateFileType) {
                        angular.forEach(validFormats, function (item) {
                            if(item.replace(/\s/g, '')==file.extenstion){
                                formatValid = true;
                            }
                        });
                        fileTypeindex = formatValid?1:-1;
                         //fileTypeindex = validFormats.indexOf(file.extenstion);
                    }
                    if ($scope.validateFileSize)
                        filesizeValid = file.size <= $scope.fileSize;
                    if (fileTypeindex > constant.NEGATIVE && filesizeValid) {

                        if ($scope.documentType == uploadedFiles.CertificateofLimitedPartnership) {
                            $scope.documentTypeId = docuementTypeIds.UploadCertificateofLimitedPartnership;

                        } else if ($scope.documentType == uploadedFiles.CertificateOfFormation) {
                            $scope.documentTypeId = docuementTypeIds.UploadCertificateofFormation;
                        }
                        else if ($scope.documentType == uploadedFiles.ArticlesofIncorporation) {
                            $scope.documentTypeId = docuementTypeIds.UploadArticlesofIncorporation;
                        }
                        else if ($scope.documentType == uploadedFiles.CertificateofExistence) {

                            $scope.documentTypeId = docuementTypeIds.UploadCertificateofExistence;
                        } else if ($scope.documentType == uploadedFiles.PURPOSEANDPOWERS) {
                            $scope.documentTypeId = docuementTypeIds.PURPOSEANDPOWERS;
                        } else if ($scope.documentType == uploadedFiles.CertificateofLimitedLiabilityLimitedPartnership) {
                            $scope.documentTypeId = docuementTypeIds.CertificateofLimitedLiabilityLimitedPartnership;
                        }
                        else if ($scope.documentType == uploadedFiles.RevenueClearanceCertificate) {
                            $scope.documentTypeId = docuementTypeIds.RevenueClearanceCertificate;
                        }
                        else if ($scope.documentType == uploadedFiles.CertificateofLimitedLiabilityPartnership) {
                            $scope.documentTypeId = docuementTypeIds.UploadCertificateofLimitedLiabilityPartnership;
                        } else if ($scope.documentType == uploadedFiles.PreferredStock) {
                            $scope.documentTypeId = docuementTypeIds.PreferredStock;
                        }
                        else if ($scope.documentType == uploadedFiles.PreparedAmendment) {
                            $scope.documentTypeId = docuementTypeIds.PreparedAmendment;
                        }
                        else
                            $scope.documentType = $scope.sectionName;


                        if ($rootScope.repository.loggedUser != undefined)
                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                        // fileUpload method is available in constants.js
                        var uri = webservices.Common.fileUpload + '?DocumentType=' + $scope.documentType + '&DocumentTypeId=' + $scope.documentTypeId + '&FullUserName=' + ($rootScope.repository.loggedUser != undefined ? $rootScope.repository.loggedUser.FullUserName : '');
                        $http({
                            url: uri,
                            method: "POST",
                            cache:false,
                            data: data,
                            transformRequest: angular.identity,
                            headers: {
                                'Content-Type': undefined
                            }
                        }).success(function (result) {
                            $(e).closest('form')[0].reset();
                            $scope.uploadList.push(result[constant.ZERO]);
                        }).error(function (result, status) {
                            $(e).closest('form')[0].reset();
                            // Folder Name: app Folder
                            // Alert Name: uploadFailed method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.uploadFailed);
                        });
                        $scope.filenotSupported = "";
                    }
                    else {
                        if (fileTypeindex == constant.NEGATIVE)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (fileTypeindex == constant.NEGATIVE && file.size > $scope.fileSize)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (file.size > $scope.fileSize) {
                            var size = ($scope.fileSize / (uploadedFiles.FILESIZEMB));
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileSizeNotSupport.replace('{0}', size);
                        }
                    }
                });

                angular.element(e).val(null);
            }

            $scope.deleteFile = function (file, index) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                    // deleteUploadedFile method is available in constants.js
                    wacorpService.post(webservices.Common.deleteUploadedFile, file,
                        function (response) {
                            //var index = $scope.uploadList.indexOf(response);
                            $scope.uploadList.splice(index, constant.ONE);
                            // Folder Name: app Folder
                            // Alert Name: fileDelete method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDelete);
                            if( $scope.uploadList.length == 0)
                            {
                                $scope.uploadList = [];
                            }
                        },
                        function (response) {
                            // Folder Name: app Folder
                            // Alert Name: fileDeleteFailed method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDeleteFailed);
                        }
                    );
                });
            };

            $scope.genericUploadClick = function () {
                var uploadID = $scope.modalName + '_UploadGenericFile';
                $('#' + uploadID).trigger('click');
            };
        },
    };
});
wacorpApp.directive('fundraiserGenericUploadFiles', function ($http) {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserCFTUploadsFiles/FundraiserGenericUploadFiles.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            isReview: '=?isReview',
            uploadList: '=?uploadList',
            showErrorMessage: '=?showErrorMessage',
            fileSize: '=?fileSize',
            fileType: '=?fileType',
            validateFileType: '=?validateFileType',
            validateFileSize: '=?validateFileSize',
            documentTypeId: '=?documentTypeId',
            documentType: '=?documentType',
            cftType: '=?cftType'
        },
        controller: function ($scope, $http, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.isReview = $scope.isReview || false;
            $scope.uploadList = $scope.uploadList || [];
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.fileSize = angular.isNullorEmpty($scope.fileSize) ? uploadedFiles.FILESIZE : $scope.fileSize;
            $scope.fileType = angular.isNullorEmpty($scope.fileType) ? uploadedFiles.FILETYPES : $scope.fileType;
            $scope.validateFileType = angular.isNullorEmpty($scope.validateFileType) ? true : $scope.validateFileType;
            $scope.validateFileSize = angular.isNullorEmpty($scope.validateFileSize) ? true : $scope.validateFileSize;
            $scope.fileSizeMessage = $scope.messages.UploadFiles.fileSizeNote.replace('{0}', ($scope.fileSize / (uploadedFiles.FILESIZEMB)));
            $scope.fileTypeMessage = ($scope.fileType.toString() == 'NONE' || $scope.fileType.toString() == '') ? "" : $scope.messages.UploadFiles.fileTypeNote.replace('{0}', $scope.fileType.toString());
            $scope.documentTypeId = $scope.documentTypeId || '';
            $scope.documentType = $scope.documentType || '';
            $scope.cftType = $scope.cftType || '';

            $scope.$watch(function () {
                $scope.uploadConfirmation = $scope.messages.UploadFiles.uploadFilesSectionConfirmation.replace('{0}', $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName);
                $scope.uploadText = "";
                $scope.uploadText = $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName;

                if ($scope.uploadText.slice(1) == "a List of Addresses Used") {
                    $scope.uploadText = "A List of Addresses Used"
                }
                else
                    $scope.uploadText;
            });

            // NOW UPLOAD THE FILES.
            $scope.upload = function (e) {
                var validFormats = $scope.fileType;
                $scope.files = [];
                $scope.$apply(function () {
                    for (var i = constant.ZERO; i < e.files.length; i++) {
                        $scope.files.push(e.files[i])
                    }
                });
                var data = new FormData();
                var selectedFiles = [];
                for (var i in $scope.files) {
                    data.append("uploadedFile", $scope.files[i]);
                    var value = $scope.files[i];
                    if (value.name != "") {
                        var fileInfo = {
                            extenstion: value.name.substring(value.name.lastIndexOf('.') + constant.ONE).toLowerCase(),
                            size: value.size,
                        };
                        selectedFiles.push(fileInfo);
                    }
                }
                angular.forEach(selectedFiles, function (file) {
                    var fileTypeindex = constant.ZERO, filesizeValid = true, formatValid = false;
                    if ($scope.validateFileType) {
                        angular.forEach(validFormats, function (item) {
                            if (item.replace(/\s/g, '') == file.extenstion) {
                                formatValid = true;
                            }
                        });
                        fileTypeindex = formatValid ? 1 : -1;
                        //fileTypeindex = validFormats.indexOf(file.extenstion);
                    }
                    if ($scope.validateFileSize)
                        filesizeValid = file.size <= $scope.fileSize;
                    if (fileTypeindex > constant.NEGATIVE && filesizeValid) {

                        if ($scope.documentType == uploadedFiles.FederalTaxDocuments) {
                            $scope.documentTypeId = docuementTypeIds.FederalTaxDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.LegalInfoAddressDocuments) {
                            $scope.documentTypeId = docuementTypeIds.LegalInfoAddressDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.ArticlesofIncorporation) {
                            $scope.documentTypeId = docuementTypeIds.UploadArticlesofIncorporation;
                        }
                        else if ($scope.documentType == uploadedFiles.ListOfAddressesDocuments) {
                            $scope.documentTypeId = docuementTypeIds.ListOfAddressesDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.TaxReturnListDocuments) {
                            $scope.documentTypeId = docuementTypeIds.TaxReturnListDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.OverrideDocuments) {
                            $scope.documentTypeId = docuementTypeIds.OverrideDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.UploadBondwaiverSosBondDocument) {
                            $scope.documentTypeId = docuementTypeIds.UploadBondwaiverSosBondDocument;
                        }
                        else if ($scope.documentType == uploadedFiles.UploadBondwaiverSuretyBondDocuments) {
                            $scope.documentTypeId = docuementTypeIds.UploadBondwaiverSuretyBondDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.FinancialInformationIrsDocumentUpload) {
                            $scope.documentTypeId = docuementTypeIds.FinancialInformationIrsDocumentUpload;
                        }
                        else if ($scope.documentType == uploadedFiles.DeclarationOfTrust) {
                            $scope.documentTypeId = docuementTypeIds.DeclarationOfTrust;
                        }
                        else if ($scope.documentType == uploadedFiles.UploadSuretyBondsDocuments) {
                            $scope.documentTypeId = docuementTypeIds.UploadSuretyBondsDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.SuretyBond) {
                            $scope.documentTypeId = docuementTypeIds.SuretyBond;
                        }

                        if ($rootScope.repository.loggedUser != undefined)
                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                        // fundraiserfileUpload method is available in constants.js
                        var uri = webservices.CFT.fundraiserfileUpload + '?DocumentType=' + $scope.documentType + '&DocumentTypeId=' + $scope.documentTypeId + '&FullUserName=' + ($rootScope.repository.loggedUser != undefined ? $rootScope.repository.loggedUser.FullUserName : '') + '&cftType=' + $scope.cftType;
                        $http({
                            url: uri,
                            method: "POST",
                            cache: false,
                            data: data,
                            transformRequest: angular.identity,
                            headers: {
                                'Content-Type': undefined
                            }
                        }).success(function (result) {
                            $(e).closest('form')[0].reset();
                            $scope.uploadList.push(result[constant.ZERO]);
                        }).error(function (result, status) {
                            $(e).closest('form')[0].reset();
                            // Folder Name: app Folder
                            // Alert Name: uploadFailed method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.uploadFailed);
                        });
                        $scope.filenotSupported = "";
                    }
                    else {
                        if (fileTypeindex == constant.NEGATIVE)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (fileTypeindex == constant.NEGATIVE && file.size > $scope.fileSize)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (file.size > $scope.fileSize) {
                            var size = ($scope.fileSize / (uploadedFiles.FILESIZEMB));
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileSizeNotSupport.replace('{0}', size);
                        }
                    }
                });

                angular.element(e).val(null);
            }

            $scope.deleteFile = function (file, index) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                    // deleteUploadedFile method is available in constants.js
                    wacorpService.post(webservices.CFT.deleteUploadedFile, file,
                        function (response) {
                            if (response.data.BusinessFilingDocumentId > 0) {
                                angular.forEach($scope.uploadList, function (value, key) {
                                    if (response.data.BusinessFilingDocumentId==value.BusinessFilingDocumentId)
                                    {
                                        value.Status = response.data.Status;
                                    }
                                });
                            }
                            else {
                                //var index = $scope.uploadList.indexOf(response);
                                $scope.uploadList.splice(index, constant.ONE);
                            }
                            // Folder Name: app Folder
                            // Alert Name: fileDelete method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDelete);
                            if ($scope.uploadList.length == 0) {
                                $scope.uploadList = [];
                            }
                        },
                        function (response) {
                            // Folder Name: app Folder
                            // Alert Name: fileDeleteFailed method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDeleteFailed);
                        }
                    );
                });
            };

            $scope.genericUploadClick = function () {
                var uploadID = $scope.modalName + '_UploadGenericFile';
                $('#' + uploadID).trigger('click');
            };
        },
    };
});
wacorpApp.directive('emailOption', function () {
    return {
        templateUrl: 'ng-app/directives/EmailOption/emailOption.html',
        restrict: 'A',
        scope: {
            emailOpt: '=?emailOpt',
            isReview: '=?isReview',
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.isReview = $scope.isReview || false;
            $scope.emailOpt = $scope.emailOpt || {};
            $scope.emailOpt.IsEmailOptionChecked = $scope.emailOpt.IsEmailOptionChecked || false;

            // show/hide the screen parts based on entity types
            var ScreenPart = function (screenPart, modal, businessTypeID) {
                if (angular.isNullorEmpty(screenPart))
                    return false;
                return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
            };

            var RAEmailCheck = function (RaAddress, principalEmailAddress) {
                if (RaAddress.IsNonCommercial && !RaAddress.EmailAddress) {
                    $scope.emailOpt.IsEmailOptionChecked = false;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog("The registered agent email address is not available on file; please update the registered agent email address to enable email opt-in.");
                }
                else if (!RaAddress.IsNonCommercial && !RaAddress.EmailAddress) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog("Please have your Commercial Registered Agent file a Commercial Statement of Change in order to update the commercial registered agent email address on file to enable email opt-in.");
                    //wacorpService.alertDialog("Please file a Statement of Change in order to update the commercial registered agent email address on file to enable email opt-in.");
                    $scope.emailOpt.IsEmailOptionChecked = false;
                }
                else {
                    $scope.emailOpt.IsEmailOptionChecked = true;
                }
            };

            var POEmailCheck = function (RaAddress, principalEmailAddress) {
                if (!principalEmailAddress) {
                    $scope.emailOpt.IsEmailOptionChecked = false;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog("The principal office email address is not available on file; please update the principal office email address to enable email opt-in.");
                }
                else {
                    $scope.emailOpt.IsEmailOptionChecked = true;
                }
            };

            var RAandPOEmailCheck = function (RaAddress, principalEmailAddress) {
                if (!RaAddress.EmailAddress && !principalEmailAddress) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog("Both principal office email address and registered agent email address is not available on file; please update the email addresses to enable email opt-in");
                    $scope.emailOpt.IsEmailOptionChecked = false;
                }
                else if (RaAddress.IsNonCommercial && !RaAddress.EmailAddress) {
                    $scope.emailOpt.IsEmailOptionChecked = false;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog("The registered agent email address is not available on file; please update the registered agent email address to enable email opt-in.");
                }
                else if (!RaAddress.IsNonCommercial && !RaAddress.EmailAddress) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog("Please have your Commercial Registered Agent file a Commercial Statement of Change in order to update the commercial registered agent email address on file to enable email opt in.");
                    $scope.emailOpt.IsEmailOptionChecked = false;
                }
                else if (!principalEmailAddress) {
                    $scope.emailOpt.IsEmailOptionChecked = false;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog("The principal office email address is not available on file; please update the principal office email address to enable email opt-in.");
                }
                else {
                    $scope.emailOpt.IsEmailOptionChecked = true;
                }
            };

            //var test = $scope.$on("test", function (evt, data) {
	        //    $scope.CheckEmailOpt();
            //});


            $scope.CheckEmailOpt = function () {
                if ($scope.emailOpt.IsEmailOptionChecked) {

                    var isEmailOptValidated = false;
                    // here BusinessTypeID = 7 is CHARITABLE ORGANIZATION,  BusinessTypeID = 10 is COMMERCIAL FUNDRAISER,  BusinessTypeID = 8 is CHARITABLE CHARITABLE TRUST
                    if ($scope.emailOpt.BusinessTypeID != null && ($scope.emailOpt.BusinessTypeID == 7 || $scope.emailOpt.BusinessTypeID == 10 || $scope.emailOpt.BusinessTypeID == 8)) {
                        //CHARITIES
                        if (!$scope.emailOpt.EntityEmailAddress) {
                            $scope.emailOpt.IsEmailOptionChecked = false;
                            // here FilingTypeID = 163 is CLOSE CHARITABLE ORGANIZATION, FilingTypeID = 169 is CHARITABLE TRUST CLOSURE, FilingTypeID = 186 is COMMERCIAL FUNDRAISER CLOSURE, FilingTypeID = 3677 is CHARITABLE ORGANIZATION OPTIONAL CLOSURE
                            if ($scope.emailOpt.BusinessFiling != null && ($scope.emailOpt.BusinessFiling.FilingTypeID == 163 || $scope.emailOpt.BusinessFiling.FilingTypeID == 169 || $scope.emailOpt.BusinessFiling.FilingTypeID == 186 || $scope.emailOpt.BusinessFiling.FilingTypeID == 3677)) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                wacorpService.alertDialog("The organization email address is not available on file; please update the organization email address to enable email opt-in.");
                            }
                            else {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                wacorpService.alertDialog("The organization email address is not available on file; please update the organization email address to enable email opt-in.");
                            }
                        }
                        else {
                            $scope.emailOpt.IsEmailOptionChecked = true;
                        }
                    }
                    else {
                        //CORPORATIONS
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        var RaAddress = wacorpService.setAgentObjForAllCorpFilings($scope.emailOpt);
                        var principalEmailAddress = "";

                        //ScreenPart($scope.emailOpt.AllScreenParts.PrincipalOffice, $scope.emailOpt, $scope.emailOpt.BusinessTypeID) && 
                        if (ScreenPart($scope.emailOpt.AllScreenParts.PrincipalOffice, $scope.emailOpt, $scope.emailOpt.BusinessTypeID) && $scope.emailOpt.IsFormationWithIntialReport) {
                            principalEmailAddress = $scope.emailOpt.FormationWithInitialReport.PrincipalOffice.EmailAddress;
                        }
                        else if (ScreenPart($scope.emailOpt.AllScreenParts.IRPrincipalOfficeInWA, $scope.emailOpt, $scope.emailOpt.BusinessTypeID) && $scope.emailOpt.IsFormationWithIntialReport) {
                            principalEmailAddress = $scope.emailOpt.FormationWithInitialReport.PrincipalOffice.EmailAddress;
                        }
                        else if (ScreenPart($scope.emailOpt.AllScreenParts.PrincipalOfficeInWashington, $scope.emailOpt, $scope.emailOpt.BusinessTypeID) && $scope.emailOpt.IsFormationWithIntialReport) {
                            principalEmailAddress = $scope.emailOpt.PrincipalOffice.EmailAddress;
                        }
                        else {
                            principalEmailAddress = $scope.emailOpt.PrincipalOffice.EmailAddress;
                        }

                        if (ScreenPart($scope.emailOpt.AllScreenParts.PrincipalOffice, $scope.emailOpt, $scope.emailOpt.BusinessTypeID) && ScreenPart($scope.emailOpt.AllScreenParts.RegisteredAgent, $scope.emailOpt, $scope.emailOpt.BusinessTypeID)) {
                            RAandPOEmailCheck(RaAddress, principalEmailAddress); // RAandPOEmailCheck method is available in this file only.
                            isEmailOptValidated = true;
                        }
                        else if (ScreenPart($scope.emailOpt.AllScreenParts.IRPrincipalOfficeInWA, $scope.emailOpt, $scope.emailOpt.BusinessTypeID) && ScreenPart($scope.emailOpt.AllScreenParts.RegisteredAgent, $scope.emailOpt, $scope.emailOpt.BusinessTypeID) && $scope.emailOpt.IsFormationWithIntialReport) {
                            RAandPOEmailCheck(RaAddress, principalEmailAddress); // RAandPOEmailCheck method is available in this file only.
                            isEmailOptValidated = true;
                        }
                        else if (ScreenPart($scope.emailOpt.AllScreenParts.PrincipalOfficeInWashington, $scope.emailOpt, $scope.emailOpt.BusinessTypeID) && ScreenPart($scope.emailOpt.AllScreenParts.RegisteredAgent, $scope.emailOpt, $scope.emailOpt.BusinessTypeID)) {
                            RAandPOEmailCheck(RaAddress, principalEmailAddress); // RAandPOEmailCheck method is available in this file only.
                            isEmailOptValidated = true;
                        }
                        else if (ScreenPart($scope.emailOpt.AllScreenParts.RegisteredAgent, $scope.emailOpt, $scope.emailOpt.BusinessTypeID)) {
                            if ($scope.emailOpt.BusinessFiling.FilingTypeName == 'ARTICLES OF AMENDMENT') {
	                            if ($scope.emailOpt.BusinessType.toUpperCase() == "WA NONPROFIT CORPORATION" ||
		                            $scope.emailOpt.BusinessType.toUpperCase() == "WA NONPROFIT PROFESSIONAL SERVICE CORPORATION" ||
		                            (($scope.emailOpt.BusinessType.toUpperCase() == "WA PROFESSIONAL SERVICE CORPORATION" || $scope.emailOpt.BusinessType.toUpperCase() == "WA PROFIT CORPORATION" || $scope.emailOpt.BusinessType.toUpperCase() == "WA SOCIAL PURPOSE CORPORATION ") && !$scope.emailOpt.IsFormationWithIntialReport)) {
	                            	RAandPOEmailCheck(RaAddress, principalEmailAddress);
	                                isEmailOptValidated = true;
	                            } else {
		                            RAEmailCheck(RaAddress, principalEmailAddress); // RAEmailCheck method is available in this file only.
		                            isEmailOptValidated = true;
	                            }
                            }
                        }
                        else if (ScreenPart($scope.emailOpt.AllScreenParts.PrincipalOffice, $scope.emailOpt, $scope.emailOpt.BusinessTypeID)) {
                            POEmailCheck(RaAddress, principalEmailAddress); // RAEmailCheck method is available in this file only.
                            isEmailOptValidated = true;
                        }
                        else if (isEmailOptValidated == false) {
                            // Commented on 08/07/2018
                           
                                if (($scope.emailOpt.BusinessType.toUpperCase() == "WA PROFESSIONAL SERVICE CORPORATION" || $scope.emailOpt.BusinessType.toUpperCase() == "WA PROFIT CORPORATION" || $scope.emailOpt.BusinessType.toUpperCase() == "WA SOCIAL PURPOSE CORPORATION ") && $scope.emailOpt.IsFormationWithIntialReport) {
                                    principalEmailAddress = $scope.emailOpt.FormationWithInitialReport.PrincipalOffice.EmailAddress;
                                }
                                else {
                                    principalEmailAddress = $scope.emailOpt.PrincipalOffice.EmailAddress;
                                }
                                RAandPOEmailCheck(RaAddress, principalEmailAddress); // RAandPOEmailCheck method is available in this file only.
                            
                                
                            
                        }
                        else {
                            $scope.emailOpt.IsEmailOptionChecked = true;
                        }
                    }
                }
            }
            
            var onEmailEmpty = function () {
                $scope.emailOpt.IsEmailOptionChecked = false;
            };

            //Here we are declaring the Method which will be calling in PO and RA Components
            var emailOptUnchecked = $scope.$on("onEmailEmpty", function () {
                onEmailEmpty(); // onEmailEmpty method is available in this file only.
            });

            $scope.$on('$destroy', function () {
                emailOptUnchecked(); // emailOptUnchecked method is available in this file only.
            });

           

        },
    };
});
wacorpApp.directive('authorizedPerson', function () {
    return {
        templateUrl: 'ng-app/directives/AuthorizedPerson/AuthorizedPerson.html',
        restrict: 'A',
        scope: {
            authPerson: '=?authPerson',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            sectionName: '=?sectionName'
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isReview = $scope.isReview || false;
            $scope.messages = messages;
            $scope.sectionName = angular.isNullorEmpty($scope.sectionName) ? sectionNames.AUTHORIZEDPERSON : $scope.sectionName;
            var authPersonScope = {
                AuthorizedPersonFirstName: null,
                AuthorizedPersonLastName: null,
                AuthorizedPersonTitle: null,
                AuthorizedPersonEntityName: null,
                IsAccepted: false,
                PersonType: ResultStatus.INDIVIDUAL,
                DocUnderPenalities: null,
                DocIsSigned: false,
                IsRAorTrusteeCoverSheetSigned: false
            };
            $scope.authPerson = $scope.authPerson ? angular.extend(authPersonScope, $scope.authPerson) : angular.copy(authPersonScope);
            $scope.fillUserInfo = function () {
                var currentTypeID = angular.copy($scope.authPerson.PersonType);
                if ($scope.authPerson.DocIsSigned) {
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        $scope.authPerson.PersonType = (response.data.FilerTypeId == "FI" ? ($scope.newUser.isIndividual == false ? "E" : "I") : response.data.Agent.AgentType);//angular.copy($scope.newUser.Agent.AgentType);// response.data.isIndividual == false ? "E" : "I";//angular.copy($scope.newUser.Agent.AgentType);
                        $scope.authPerson.AuthorizedPersonEntityName = response.data.FilerTypeId == "FI" ? response.data.Agent.OrganizationName : response.data.Agent.EntityName;// angular.copy($scope.newUser.Agent.EntityName);
                        $scope.authPerson.AuthorizedPersonFirstName = angular.copy($scope.newUser.FirstName);
                        $scope.authPerson.AuthorizedPersonLastName = angular.copy($scope.newUser.LastName);
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    $scope.authPerson.PersonType = currentTypeID;
                    $scope.authPerson.AuthorizedPersonEntityName = null;
                    $scope.authPerson.AuthorizedPersonFirstName = null;
                    $scope.authPerson.AuthorizedPersonLastName = null;
                }
            };
            $scope.isNeedValidation = function () {
                return $scope.showErrorMessage || false;
            };
        },
    };
});
wacorpApp.directive('effectiveDate', function () {
    return {
        templateUrl: 'ng-app/directives/EffectiveDate/EffectiveDate.html',
        restrict: 'A',
        scope: {
            effectiveData: '=?effectiveData',
            showErrorMessage: '=?showErrorMessage',
            isFormation: '=?isFormation',
            sectionName: '=?sectionName'
        },
        controller: function ($scope, wacorpService) {
            $scope.messages = messages;
            $scope.effectiveData = $scope.effectiveData || {};
            $scope.isFormation = $scope.isFormation || '';
            $scope.effectiveData.EffectiveDateType = angular.isNullorEmpty($scope.effectiveData.EffectiveDateType) ? ResultStatus.DATEOFFILING : $scope.effectiveData.EffectiveDateType;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.sectionName = angular.isNullorEmpty($scope.sectionName) ? "" : $scope.sectionName;
            $scope.effectiveData.IsAmendmentEffectiveChange = angular.isNullorEmpty($scope.effectiveData.IsAmendmentEffectiveChange) ? false : $scope.effectiveData.IsAmendmentEffectiveChange; //Is Entity Type Radio button

            $scope.FutureEffectiveDateAlert = function () {
                // Folder Name: app Folder
                // Alert Name: futureEffectiveDate method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.futureEffectiveDate,
                        function () { // yes
                        }
                        , function () { // no 
                            $scope.effectiveData.EffectiveDateType = ResultStatus.DATEOFFILING;
                        });
            };

            $scope.checkEffectiveDate = function () {
                if (wacorpService.dateFormatService($scope.effectiveData.EffectiveDate) == null) {
                    $scope.effectiveData.EffectiveDate = null;
                }
            }

        },
    };
});
wacorpApp.directive('otherEffectiveDate', function () {
    return {
        templateUrl: 'ng-app/directives/OtherEffectiveDate/OtherEffectiveDate.html',
        restrict: 'A',
        scope: {
            effectiveData: '=?effectiveData',
            showErrorMessage: '=?showErrorMessage',
            sectionName: '=?sectionName',
            isFormation: '=?isFormation'
        },
        controller: function ($scope, wacorpService) {
            $scope.messages = messages;
            $scope.effectiveData = $scope.effectiveData || {};
            $scope.isFormation = $scope.isFormation || '';
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.sectionName = angular.isNullorEmpty($scope.sectionName) ? "Effective Date" : $scope.sectionName;

            $scope.FutureEffectiveDateAlert = function () {
                // Folder Name: app Folder
                // Alert Name: futureEffectiveDate method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.futureEffectiveDate,
                        function () { // yes
                        }
                        , function () { // no 
                            $scope.effectiveData.EffectiveDateType = ResultStatus.DATEOFFILING;
                        });
            }
        },
    };
});
wacorpApp.directive('natureOfBusiness', function () {
    return {
        templateUrl: 'ng-app/directives/NatureofBusiness/NatureofBusiness.html',
        restrict: 'A',
        scope: {
            naicsOptions: '=?naicsOptions',
            naicsCodeModel: '=?naicsCodeModel',
            settings: '=?settings',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            isRequired: '=?isRequired'
        },
        controller: function ($scope, wacorpService, $rootScope, lookupService) {
            $scope.naicsOptions = $scope.naicsOptions || [];
            $scope.naicsCodeModel = $scope.naicsCodeModel || [];
            var settingScope = { scrollableHeight: '300px', scrollable: true, key: "Key", value: "Value", isKeyList: false };
            $scope.settings = $scope.settings ? angular.extend(settingScope, $scope.settings) : angular.copy(settingScope);
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isRequired =  true;
           
            $scope.Init = function () {
                $scope.selectedItems = [];
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.NaicsCodes(function (response) {
                    $scope.naicsCodeModel.filter(function (naicscode) {
                        for (var i = 0; i < response.data.length; i++) {
                            if (naicscode == response.data[i].Key) {
                                $scope.selectedItems.push(response.data[i]);
                                break;
                            }
                        }
                    });
                });
            };
        },
    };
});
// NOTE: online Requalifications disabled @ ln.106 (remove this note when re-enabling)

wacorpApp.directive('businessSearch', function () {
    return {
        templateUrl: 'ng-app/directives/BusinessSearch/BusinessSearch.html',
        restrict: 'A',
        scope: {
            searchType: '=?searchType',
            selectedBusiness: '=?selectedBusiness',
            sectionName: '=?sectionName',
            submitFunc: '&?submitFunc',
            expressPdfNote: '=?expressPdfNote',
            certifyCopiesNote: '=?certifyCopiesNote',
        },
        controller: function ($scope, wacorpService, focus, $timeout, $rootScope, $cookieStore) {
            // declare scope variables
            $scope.page = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.messages = messages;
            $scope.searchType = $scope.searchType || "";
            $scope.businessSearchCriteria = { Type: searchTypes.BUSINESSNO, ID: "", IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, BusinessTypeId: constant.ZERO, IsOnline: true, SearchType: $scope.searchType, isSearchClick: false, SortBy: null, SortType: null };
            $scope.selectedBusiness = null;
            $scope.search = loadbusinessList;
            $scope.searchval = '';
            $scope.isButtonSerach = false;
            $scope.sectionName = $scope.sectionName || '';
            $scope.expressPdfNote = $scope.expressPdfNote || false;
            $scope.certifyCopiesNote = $scope.certifyCopiesNote || false;

            focus("searchField");

            //TFS 2626 Default Values

            $scope.isGrossRevenueNonProfitValid = true;
            var isGrossRevenueNonProfitEnabled = false;
            $rootScope.IsGrossRevenueNonProfit = ($rootScope.IsGrossRevenueNonProfit != undefined ? $rootScope.IsGrossRevenueNonProfit : false);

            //TFS 2626
            $scope.submitBusiness = function () {
                //TFS 2626
                $scope.showErrorMessage = false;
                
                if ($scope.isGrossRevenueNonProfitValid) {
                    //TFS 2626
                    if ($scope.submitFunc) {

                        // TFS#2347; added
                        $scope.IsGrossRevenueNonProfit = $rootScope.IsGrossRevenueNonProfit;

                        $rootScope.currentTarget = "" //or empty 
                        //$scope.businessSearchText = $scope.sectionName;

                        $scope.submitFunc();
                    }
                    //TFS 2626
                } else {
                    $scope.showErrorMessage = true;
                };
                //TFS 2626
            };

            // search business list
            $scope.searchBusiness = function (searchform) {
                $scope.isShowErrorFlag = true;
                if ($scope[searchform].$valid) {
                    $scope.businessSearchCriteria.isSearchClick = true;
                    $scope.isShowErrorFlag = false;
                    $scope.isButtonSerach = true;
                    $rootScope.selectedBusinessID = constant.ZERO;
                    $scope.selectedBusinessID = constant.ZERO;
                    $scope.selectedBusinessTypeID = constant.ZERO;  //TFS 2514
                    $rootScope.selectedBusinessTypeID = constant.ZERO;  //TFS 2514
                    loadbusinessList(constant.ZERO); // loadbusinessList method is available in this file only.
                }
            };

            //clear text on selecting radio button
            $scope.cleartext = function () {
                $scope.businessSearchCriteria.ID = null;
                $scope.businessSearchCriteria.SortType = null;
                $scope.businessSearchCriteria.SortBy = null;
            };

            // clear fields
            $scope.clearFun = function () {
                $scope.businessSearchCriteria.ID = "";
                $scope.businessSearchCriteria.isSearchClick = false;
                $scope.businessSearchCriteria.SortType = null;
                $scope.businessSearchCriteria.SortBy = null;
            };

            // get selected business information
            $scope.getSelectedBusiness = function (business) {
                
                $scope.selectedBusiness = business;
                $scope.selectedBusinessID = business.BusinessID;
                $scope.selectedBusinessTypeID = business.BusinessTypeID;  //TFS 2514
                $rootScope.selectedBusinessID = $scope.selectedBusinessID;
                $rootScope.selectedBusinessTypeID = $scope.selectedBusinessTypeID; //TFS 2514
                $rootScope.selectedBusiness = $scope.selectedBusiness

                //CheckGrossRevenueNonProfit(business);  //TFS 2626
                $scope.CheckGrossRevenueNonProfit(business);  //TFS 2626
                $scope.CheckIsGrossRevenueNonProfit();  //TFS 2626

            };

            // get business list data from server
            function loadbusinessList(page, sortBy) {
                page = page || constant.ZERO;
                $scope.businessSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                $scope.selectedBusiness = null;
                if (sortBy != undefined) {
                    if ($scope.businessSearchCriteria.SortBy == sortBy) {
                        if ($scope.businessSearchCriteria.SortType == 'ASC') {
                            $scope.businessSearchCriteria.SortType = 'DESC';
                        }
                        else {
                            $scope.businessSearchCriteria.SortType = 'ASC';
                        }
                    }
                    else {
                        $scope.businessSearchCriteria.SortBy = sortBy;
                        $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                }
                else {
                    if ($scope.businessSearchCriteria.Type == "businessno") {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "UBI#";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.businessSearchCriteria.Type == "businessname") {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "BusinessName";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                }

                //TFS 1061 If no SearchType in Scope, check for SearchType in parent
                if (($scope.businessSearchCriteria.SearchType == '') && !($scope.$parent.SearchType == '')) {
                    $scope.businessSearchCriteria.SearchType = $scope.$parent.SearchType;
                }
                //TFS 1061 If no SearchType in Scope, check for SearchType in parent

                var data = angular.copy($scope.businessSearchCriteria);
                $scope.isButtonSerach = page == 0;

                data.ID = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID : $scope.searchval);
                wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
                    $rootScope.searchCriteria = {
                        searList: response, page: page,
                        searchType: $scope.businessSearchCriteria.Type,
                        searchValue: $scope.businessSearchCriteria.ID,
                        pagesCount: $scope.pagesCount,
                    };

                    loadList($rootScope.searchCriteria); // loadList method is available in this file only.
                    $scope.selectedBusiness = null;
                    $scope.selectedBusinessID = constant.ZERO;
                    $scope.selectedBusinessTypeID = constant.ZERO;  //TFS 2514
                }, function (response) {
                    $scope.selectedBusiness = null;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                });

                if (typeof (document.getElementById("btnContinue")) !== 'undefined'
                        && (document.getElementById("btnContinue")) !== null) {
                    document.getElementById('btnContinue').disabled = true;
                };

            }

            // select search type
            $scope.selectSearchType = function () {
                $scope.businessSearchCriteria.ID = "";
            }

            $scope.$watch('BusinessList', function () {
                if ($scope.BusinessList == undefined)
                    return;
                if ($scope.BusinessList.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);

            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.businessSearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.businessSearchCriteria.ID = pastedText;
                    });
                }
            };

            function loadList(responseData, flag) {
                var response = responseData.searList;
                var page = responseData.page;
                if (flag) {
                    $scope.businessSearchCriteria.Type = responseData.searchType;
                    $scope.businessSearchCriteria.ID = responseData.searchValue;
                }

                $scope.BusinessList = response.data;
                if ($scope.isButtonSerach && response.data.length > 0) {
                    var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                    var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                    $scope.pagesCount = response.data.length < $scope.businessSearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                    $scope.totalCount = totalcount;
                    $scope.searchval = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID : $scope.searchval);

                    //Putting all the code in rootscope for Back Button Purpose
                    $rootScope.pagesCount = $scope.pagesCount;
                    $rootScope.totalCount = $scope.totalCount;
                    $rootScope.businessSearchCriteria = $scope.businessSearchCriteria;
                    $rootScope.searchval = $scope.searchval
                }
                //Getting Data from rootscope for Back Button Purpose
                if (response.data.length > 0) {
                    $scope.totalCount = $rootScope.totalCount;
                    $scope.pagesCount = $rootScope.pagesCount;
                    $scope.businessSearchCriteria = $rootScope.businessSearchCriteria;
                    $scope.searchval = $rootScope.searchval;
                }

                $scope.selectedBusinessID = $rootScope.selectedBusinessID;
                $scope.selectedBusinessTypeID = $rootScope.selectedBusinessTypeID; //TFS 2514
                $scope.selectedBusiness = $rootScope.selectedBusiness;
                $scope.page = page;
                $scope.BusinessListProgressBar = false;
                focus("tblBusinessSearch");

                //TFS 2626
                //CheckGrossRevenueNonProfit(null);
                $scope.CheckGrossRevenueNonProfit(null);
                //TFS 2626

            }

            $scope.setUBILength = function (e) {
                if ($scope.businessSearchCriteria.ID != undefined && $scope.businessSearchCriteria.ID != null && $scope.businessSearchCriteria.ID != "" && $scope.businessSearchCriteria.ID.length >= 9) {
                    if (e.which != 97) {
                        // Allow: backspace, delete, tab, escape, enter and .
                        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                            // Allow: Ctrl+A, Command+A
                            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                            // Allow: home, end, left, right, down, up
                            (e.keyCode >= 35 && e.keyCode <= 40)) {
                            // let it happen, don't do anything
                            return;
                        }
                        // Ensure that it is a number and stop the keypress
                        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                            e.preventDefault();
                        }
                        e.preventDefault();
                    }
                }
            };

            // TFS 2626
            $scope.CheckIsGrossRevenueNonProfit = function () {
                $rootScope.IsGrossRevenueNonProfit = null;
                $scope.isGrossRevenueNonProfitValid = true;

                //if (typeof (document.getElementById("btnContinue")) !== 'undefined'
                //        && (document.getElementById("btnContinue")) !== null) {
                //    document.getElementById('btnContinue').disabled = false;
                //};


                if (isGrossRevenueNonProfitEnabled == true) {
                    $scope.isGrossRevenueNonProfitValid = false;
                    if ($('#rdoIsGrossRevenueNonProfitOver500K').is(':checked')) {
                        $rootScope.IsGrossRevenueNonProfit = true;
                        $scope.IsGrossRevenueNonProfit = true;

                        $scope.isGrossRevenueNonProfitValid = true;
                        //document.getElementById('btnContinue').disabled = false;  //TFS 2524 enable button default

                    } else if ($('#rdoIsGrossRevenueNonProfitUnder500K').is(':checked')) {
                        $rootScope.IsGrossRevenueNonProfit = false;
                        $scope.IsGrossRevenueNonProfit = false;

                        $scope.isGrossRevenueNonProfitValid = true;
                        //document.getElementById('btnContinue').disabled = false;  //TFS 2524 enable button default

                    } else {
                        $rootScope.IsGrossRevenueNonProfit = null;
                        $scope.IsGrossRevenueNonProfit = null;

                        $scope.isGrossRevenueNonProfitValid = false;
                        //document.getElementById('btnContinue').disabled = true;  //TFS 2524 disable button default

                    };
                };
                $scope.SetContinueEnabled();
            };

            $scope.CheckGrossRevenueNonProfit = function (business) {
            //function CheckGrossRevenueNonProfit(business) {
                $rootScope.IsGrossRevenueNonProfit = null;
                $scope.IsGrossRevenueNonProfit = null;
                $scope.isGrossRevenueNonProfitValid = true;
                $scope.isOnlineFilingDisabled = false;

                isGrossRevenueNonProfitEnabled = false;
                //isGrossRevenueNonProfitQuestionEnabled = false;

                //Default Values
                if (typeof (document.getElementById("divIsGrossRevenueNonProfit")) !== 'undefined'
                    && (document.getElementById("divIsGrossRevenueNonProfit")) !== null) {
                    document.getElementById('divIsGrossRevenueNonProfit').style.display = "none";
                };
                if (typeof (document.getElementById("divIsGrossRevenueNonProfitQuestion")) !== 'undefined'
                    && (document.getElementById("divIsGrossRevenueNonProfitQuestion")) !== null) {
                    document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = "none";
                };
                if (typeof (document.getElementById("divNonProfitOnlineDisable")) !== 'undefined'
                    && (document.getElementById("divNonProfitOnlineDisable")) !== null) {
                    document.getElementById('divNonProfitOnlineDisable').style.display = "none";
                };
                //Default Values

                if (business != null) {
                    //clear Rdo buttons
                    if (typeof (document.getElementById("rdoIsGrossRevenueNonProfitOver500K")) !== 'undefined'
                        && (document.getElementById("rdoIsGrossRevenueNonProfitOver500K")) !== null) {
                        document.getElementById("rdoIsGrossRevenueNonProfitOver500K").checked = false;
                    };
                    if (typeof (document.getElementById("rdoIsGrossRevenueNonProfitUnder500K")) !== 'undefined'
                        && (document.getElementById("rdoIsGrossRevenueNonProfitUnder500K")) !== null) {
                        document.getElementById("rdoIsGrossRevenueNonProfitUnder500K").checked = false;
                    };

                    //alert('$scope.searchType: ' + $scope.searchType);
                    //Check if Filing is disabled  TFS 2695 TFS 2333
                    if (business.BusinessType == "WA NONPROFIT CORPORATION"
                        || business.BusinessType == "WA NONPROFIT PROFESSIONAL SERVICE CORPORATION"
                        ) {
                        if (
                            $scope.searchType === "AnnualReport"
                            || $scope.searchType === "Reinstatement"
                            || $scope.searchType === "Articles of Incorporation"
                            //|| $scope.searchType === "BusinessAmended"
                            || $scope.searchType === "AmendedAnnualReport" //Check to allow the Filing DevOps 2210
                            || $scope.searchType === "StatementofChange"
                            || $scope.searchType === "StatementofTermination"
                            || $scope.searchType === "searchExpressPDFCoE" //Check to allow the Filing DevOps 2209
                            ) { //add filing types to this list to enable them
                            $scope.isOnlineFilingDisabled = false;
                        } else {
                            $scope.isOnlineFilingDisabled = true;
                        };
                    } else if (
                        business.BusinessType == "FOREIGN NONPROFIT CORPORATION"
                        || business.BusinessType == "FOREIGN NONPROFIT PROFESSIONAL SERVICE CORPORATION"
                        ) {
                        if (
                            $scope.searchType === "AnnualReport"
                            //|| $scope.searchType === "Reinstatement"  //TFS#2333; disabling online requals
                            || $scope.searchType === "Articles of Incorporation"
                            //|| $scope.searchType === "BusinessAmended"
                            || $scope.searchType === "AmendedAnnualReport"  //Check to allow the Filing DevOps 2210
                            || $scope.searchType === "StatementofChange"
                            || $scope.searchType === "StatementofTermination"
                            || $scope.searchType === "searchExpressPDFCoE"  //Check to allow the Filing DevOps 2209
                            ) { //add filing types to this list to enable them
                            $scope.isOnlineFilingDisabled = false;
                        } else {
                            $scope.isOnlineFilingDisabled = true;
                        };
                    };
                    //TFS 2695

                    //(disable online Express/One Click for NP)
                    if (business.BusinessType == "WA NONPROFIT CORPORATION"
                        || business.BusinessType == "WA NONPROFIT PROFESSIONAL SERVICE CORPORATION"
                        || business.BusinessType == "FOREIGN NONPROFIT CORPORATION"
                        || business.BusinessType == "FOREIGN NONPROFIT PROFESSIONAL SERVICE CORPORATION"
                        ) {
                        if (window.location.href.indexOf("expressAnnualReport") > -1
                            || window.location.href.indexOf("oneClickAR") > -1
                            ) {
                            $scope.isOnlineFilingDisabled = true;
                        };
                    };

                    //TFS 2320 Check if Partial is visible  
                    //if (
                    //    (business.BusinessType == "WA NONPROFIT CORPORATION"
                    //    || business.BusinessType == "WA NONPROFIT PROFESSIONAL SERVICE CORPORATION"
                    //    || business.BusinessType == "FOREIGN NONPROFIT CORPORATION"
                    //    || business.BusinessType == "FOREIGN NONPROFIT PROFESSIONAL SERVICE CORPORATION")
                    //    &&
                    //    ($scope.searchType === "AnnualReport"
                    //    || $scope.searchType === "Reinstatement"
                    //    || $scope.searchType === "Articles of Incorporation")
                    //    ) {
                    //    isGrossRevenueNonProfitEnabled = true;
                    //} else {
                    //    isGrossRevenueNonProfitEnabled = false;
                    //};

                    //alert('$scope.searchType: ' + $scope.searchType);
                    //Check If Gross Revenue Question is Visible
                    if (
                        (business.BusinessType == "WA NONPROFIT CORPORATION"
                        || business.BusinessType == "WA NONPROFIT PROFESSIONAL SERVICE CORPORATION")
                        &&
                        ($scope.searchType === "AnnualReport"
                        || $scope.searchType === "Reinstatement"
                        || $scope.searchType === "Articles of Incorporation")
                        ) {
                        isGrossRevenueNonProfitEnabled = true;
                        //isGrossRevenueNonProfitQuestionEnabled = true;
                    } else if (
                        (business.BusinessType == "FOREIGN NONPROFIT CORPORATION"
                        || business.BusinessType == "FOREIGN NONPROFIT PROFESSIONAL SERVICE CORPORATION")
                        &&
                        ($scope.searchType === "AnnualReport"
                        || $scope.searchType === "Reinstatement"
                        || $scope.searchType === "Articles of Incorporation")
                        ) {
                        isGrossRevenueNonProfitEnabled = true;
                        //isGrossRevenueNonProfitQuestionEnabled = true;
                    } else {
                        isGrossRevenueNonProfitEnabled = false;
                        //isGrossRevenueNonProfitQuestionEnabled = false;
                    };
                    //TFS 2320 Check if visible

                    //alert('$scope.isOnlineFilingDisabled: ' + $scope.isOnlineFilingDisabled);
                    if ($scope.isOnlineFilingDisabled) {
                        $('#divIsGrossRevenueNonProfit').hide();
                        document.getElementById('divNonProfitOnlineDisable').style.display = "block";
                        document.getElementById('spnNonProfitOnlineDisableLoggedOn').style.display = "block";

                        $scope.isGrossRevenueNonProfitValid = false;
                    } else if ($scope.isOnlineFilingDisabled != true) {  //filing enabled

                        //alert('isGrossRevenueNonProfitEnabled: ' + isGrossRevenueNonProfitEnabled);
                        if (isGrossRevenueNonProfitEnabled == true) {
                            document.getElementById('divIsGrossRevenueNonProfit').style.display = 'block';
                            //show question
                            document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = 'block';
                            $scope.isGrossRevenueNonProfitValid = false;

                            //alert('isGrossRevenueNonProfitQuestionEnabled: ' + isGrossRevenueNonProfitQuestionEnabled);
                            //if (isGrossRevenueNonProfitQuestionEnabled == true) {
                            //    //show question
                            //    document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = 'block';
                            //    $scope.isGrossRevenueNonProfitValid = false;
                            //} else {
                            //    //hide question
                            //    document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = 'none';
                            //    //set valid
                            //    $scope.isGrossRevenueNonProfitValid = true;
                            //};

                        } else {
                            //hide all screen parts
                            document.getElementById('divIsGrossRevenueNonProfit').style.display = 'none';
                            document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = 'none';
                            //set valid
                            $scope.isGrossRevenueNonProfitValid = true;
                        };

                    } else {  //filing disabled
                        //hide question display blocked filing message
                        document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = 'none';
                        document.getElementById('divNonProfitOnlineDisable').style.display = 'block';

                        $scope.isGrossRevenueNonProfitValid = true;
                    };

                };

                $scope.SetContinueEnabled();
            };

            $scope.SetContinueEnabled = function () {
                //Set Button Enabled
                if (typeof (document.getElementById("btnContinue")) !== 'undefined'
                    && (document.getElementById("btnContinue")) !== null) {
                    document.getElementById('btnContinue').disabled = true; //TFS 2524 disable button default

                    if ($scope.isGrossRevenueNonProfitValid == true
                    && $scope.isOnlineFilingDisabled == false
                    && $scope.selectedBusinessID !== 0) {
                        document.getElementById('btnContinue').disabled = false;  //TFS 2524 enable button default
                    };
                };
            };

            if ($rootScope.searchCriteria) {
                // $scope.isButtonSerach = true;
                loadList($rootScope.searchCriteria, true); // loadList method is available in this file only.
                //  $scope.isButtonSerach = false;
                $scope.businessSearchCriteria.isSearchClick = true;
            }

            $(document).ready(function () {
                //CheckGrossRevenueNonProfit($scope.selectedBusiness);
                $scope.CheckGrossRevenueNonProfit($scope.selectedBusiness);
                $scope.CheckIsGrossRevenueNonProfit();

                //TFS 2730
                $scope.isShowLogonError = false
                if (
                    (window.location.href.indexOf("oneClickARSearch") != -1) ||
                    (window.location.href.indexOf("expressAnnualReportSearch") != -1)
                    ) {
                    $scope.isShowLogonError = true;
                } else {
                    $scope.isShowLogonError = false;
                };
                //TFS 2730
            });
            // TFS 2626
        },
    }
});
wacorpApp.directive('fein', function ($filter, $timeout) {
    return {
        templateUrl: 'ng-app/directives/CFT/FEIN/_FEIN.html',
        restrict: 'A',
        scope: {
            feinData: '=?feinData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.usaCode = usaCode;
            $scope.washingtonCode = washingtonCode;
            $scope.isOptional = true;
            $scope.isCorporation = true;
            $scope.isOther = true;
            $scope.FederalTaxTypes = [];
            $scope.Countries = [];
            $scope.States = [];
            $scope.ShowIRSLetter = false;
            $scope.OrganizationNames = [];
            $scope.FederalCount = false;
            $scope.oldEntityName = "";
            $scope.Count = 0;
            //$scope.feinData.IsShowFederalTax = false;
            $scope.washingtonIntegerCode = washingtonIntegerCode;
            //$scope.charityOrganization = {};
            //$scope.charityOrganization.AKANamesList = $scope.charityOrganization.AKANamesList || [];
            //$scope.feinData.IsFederalTax = false;

            var feinScope = {
                FEINNumber: constant.ZERO, UBINumber: constant.ZERO, IsEntityRegisteredInWA: false, IsUBIOrganizationaStructure: true, isShowAka: false, Purpose: null,
                JurisdictionCountry: codes.USA, JurisdictionState: codes.WA, UBIOtherDescp: '', JurisdictionCountryDesc: null, JurisdictionStateDesc: null,
                JurisdictionDesc: null, Jurisdiction: null, IsFEINNumberExistsorNot: false, IsUBINumberExistsorNot: false, IsShowFederalTax: false, IsOrgNameExists: false, IsActiveFilingExist: false
            };

            $scope.feinData = $scope.feinData ? angular.extend(feinScope, $scope.feinData) : angular.copy(feinScope);


            $scope.selectedJurisdiction = function (items, selectedVal) {
                var result = "";
                angular.forEach(items, function (item) {
                    if (selectedVal == item.Key) {
                        result = item.Value;
                    }
                });
                return result;
            }

            var ubiCnt = 1;
            $scope.$watch('feinData', function () {
                $scope.feinData.FEINNumber = $scope.feinData.FEINNumber == 0 ? '' : $scope.feinData.FEINNumber;
                $scope.feinData.UBINumber = $scope.feinData.UBINumber == 0 ? '' : $scope.feinData.UBINumber;
                $scope.feinData.IsEntityRegisteredInWA = angular.isNullorEmpty($scope.feinData.IsEntityRegisteredInWA) ? false : $scope.feinData.IsEntityRegisteredInWA;
                $scope.feinData.IsUBIOrganizationaStructure = angular.isNullorEmpty($scope.feinData.IsUBIOrganizationaStructure) ? true : $scope.feinData.IsUBIOrganizationaStructure;
                $scope.feinData.JurisdictionCountry = $scope.feinData.JurisdictionCountry == 0 ? '' : $scope.feinData.JurisdictionCountry;
                $scope.feinData.JurisdictionState = $scope.feinData.JurisdictionState == 0 ? $scope.washingtonCode : $scope.feinData.JurisdictionState;
                $scope.feinData.IsActiveFilingExist = angular.isNullorEmpty($scope.feinData.IsActiveFilingExist) ? false : $scope.feinData.IsActiveFilingExist;
                $scope.feinData.isShowAka = angular.isNullorEmpty($scope.feinData.isShowAka) ? false : $scope.feinData.isShowAka;

                //Qualifier

                $scope.feinData.IsIntegratedAuxiliary = angular.isNullorEmpty($scope.feinData.IsIntegratedAuxiliary) ? false : $scope.feinData.IsIntegratedAuxiliary;
                $scope.feinData.IsPoliticalOrganization = angular.isNullorEmpty($scope.feinData.IsPoliticalOrganization) ? false : $scope.feinData.IsPoliticalOrganization;
                $scope.feinData.IsRaisingFundsForIndividual = angular.isNullorEmpty($scope.feinData.IsRaisingFundsForIndividual) ? false : $scope.feinData.IsRaisingFundsForIndividual;
                $scope.feinData.IsRaisingLessThan50000 = angular.isNullorEmpty($scope.feinData.IsRaisingLessThan50000) ? false : $scope.feinData.IsRaisingLessThan50000;
                $scope.feinData.IsAnyOnePaid = angular.isNullorEmpty($scope.feinData.IsAnyOnePaid) ? false : $scope.feinData.IsAnyOnePaid;
                $scope.feinData.IsInfoAccurate = angular.isNullorEmpty($scope.feinData.IsInfoAccurate) ? false : $scope.feinData.IsInfoAccurate;

                if ($scope.feinData.Purpose)
                {
                    if ($scope.feinData.Purpose.length > 500)
                    {
                        $scope.feinData.Purpose = $scope.feinData.Purpose.replace(/(\r\n|\n|\r)/gm, "");
                        $scope.feinData.Purpose = $scope.feinData.Purpose.substring(0, 500);
                    }
                        
                }

                //if ($scope.feinData.JurisdictionCountry != $scope.usaCode) {
                //    $scope.feinData.JurisdictionState = '';
                //}
                if (ubiCnt == 1 && typeof ($scope.feinData.UBINumber) != typeof (undefined) && $scope.feinData.UBINumber != null && $scope.feinData.UBINumber != '') {
                    $scope.getOrganizationNameByUBI($scope.feinData.UBINumber); // getOrganizationNameByUBI method is available in this file only
                    ubiCnt++;
                }

                var cnt = 1;
                if (typeof ($scope.feinData.AKANamesList) != typeof (undefined) && $scope.feinData.AKANamesList != null) {
                    if ($scope.feinData.AKANamesList.length > 0) {
                        angular.forEach($scope.feinData.AKANamesList, function (akaInfo) {
                            if (akaInfo.Status != "D") {
                                cnt = 0;
                            }
                        });
                        if (cnt == 0) {
                            $scope.feinData.isShowAka = true;
                        }
                        else {
                            $scope.feinData.isShowAka = false;
                        }
                    }
                }

                angular.forEach($scope.FederalTaxTypes, function (tax) {
                    if (tax.Key == $scope.feinData.FederalTaxExemptId)
                        $scope.feinData.FederalTaxExemptText = tax.Value;
                    $scope.feinData.IsFTDocumentAttached = true;
                });

                angular.forEach($scope.Countries, function (country) {
                    if (country.Key == $scope.feinData.JurisdictionCountry)
                        $scope.feinData.JurisdictionCountryDesc = country.Value;
                });
                angular.forEach($scope.States, function (state) {
                    if (state.Key == $scope.feinData.JurisdictionState)
                        $scope.feinData.JurisdictionStateDesc = state.Value;
                });

                //angular.forEach($scope.feinData.FederaltaxUpload, function (value) {
                //    if (value.Status!="D") {
                //        $scope.FederalCount = false;
                //    }
                //    else {
                //        $scope.FederalCount = true;
                //    }
                //});
                //$scope.FederalChange();
            }, true);

            //$scope.CountryChangeDesc = function () {
            //    $scope.feinData.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.Countries, $scope.feinData.JurisdictionCountry);
            //};
            //Get Federal Tax Types List
            $scope.getFederalTaxTypes = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.FederalTaxTypes(function (response) { $scope.FederalTaxTypes = response.data; });
            };
            $scope.getFederalTaxTypes(); // getFederalTaxTypes method is available in this file only.

            var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
                $scope.Countries = response.data;
            }, function (response) {
            });

            var lookupStatesParams = { params: { name: 'CFTStates' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
                $scope.States = response.data;
            }, function (response) {
            });


            $scope.organizationStructure = function (value) {
                if (value) {
                    $scope.feinData.IsUBIOrganizationaStructure = true;
                }
                else {
                    $scope.feinData.IsUBIOrganizationaStructure = false;
                }

            }
            //Get Business Details by UBI Number
            $scope.getBusinessDetails = function () {
                var ubidata = { params: { ubiNumber: $scope.feinData.UBINumber, cftType: $scope.feinData.CFTType } }
                if (ubidata.ubiNumber != '' && ubidata.ubiNumber != null) {
                    // IsUBINumberExists method is available in constants.js
                    wacorpService.get(webservices.CFT.IsUBINumberExists, ubidata, function (response) {
                        if (response.data == 'true') {
                            // Folder Name: app Folder
                            // Alert Name: isUBIExistorNot method is available in alertMessages.js SSS
                            wacorpService.alertDialog(messages.Fein.isUBIExistorNot);
                            $scope.feinData.IsUBINumberExistsorNot = false;
                            $scope.feinData.UBINumber = null;
                        }
                        else {
                            $scope.feinData.IsUBINumberExistsorNot = true;
                            var data = {
                                params: { UBINumber: $scope.feinData.UBINumber }
                            }
                            // getBusinessDetailsByUBINumber method is available in constants.js
                            wacorpService.get(webservices.CFT.getBusinessDetailsByUBINumber, data, function (response) {

                                if (response.data.EntityName != null) {
                                    $scope.feinData.EntityName = response.data.EntityName;
                                    $scope.feinData.IsOrganizationalStructureType = response.data.BusinessType;
                                    $scope.feinData.OrganizationStructureJurisdictionCountryId = response.data.OrganizationStructureJurisdictionCountryId == null ? "" : response.data.OrganizationStructureJurisdictionCountryId.toString();
                                    $scope.feinData.OrganizationalStructureStateJurisdictionId = response.data.OrganizationalStructureStateJurisdictionId == null ? "" : response.data.OrganizationalStructureStateJurisdictionId.toString();
                                    $scope.feinData.OSJurisdictionId = response.data.OrganizationalStructureJurisdictionId == 0 ? "" : response.data.OrganizationalStructureJurisdictionId.toString();
                                    $scope.feinData.IsOSNonProfitCorporation = (response.data.BusinessType == "C") ? true : false;
                                    $scope.feinData.CFTOfficersList = response.data.CFTOfficersList;
                                    $scope.feinData.isHavingEntityOnUBISearch = angular.isNullorEmpty($scope.feinData.EntityName) ? false : true;

                                    angular.forEach($scope.Countries, function (country) {
                                        if (country.Key == $scope.feinData.OrganizationStructureJurisdictionCountryId)
                                            $scope.feinData.OrganizationStructureJurisdictionCountryDesc = country.Value;
                                    });

                                    angular.forEach($scope.States, function (state) {
                                        if (state.Key == $scope.feinData.OrganizationalStructureStateJurisdictionId)
                                            $scope.feinData.OrganizationalStructureStateJurisdictionDesc = state.Value;
                                    });
                                } else {
                                    // Folder Name: app Folder
                                    // Alert Name: noDataFound method is available in alertMessages.js 
                                    wacorpService.alertDialog(messages.noDataFound);
                                    $scope.feinData.UBINumber = null;
                                }

                            }, function (response) { });
                        }
                    }, function (response) { });
                }

            };

            $scope.getOrganizationNameByUBI = function (value) {

                $scope.feinData.IsOrgNameExists = false;
                //$scope.feinData.isBusinessNameChanged = false;
                if ($scope.feinData.EntityName != "" && $scope.feinData.EntityName != undefined) {
                    if ($scope.feinData.FeinUbiCount == 0)
                        $scope.feinData.UBIOldName = $scope.feinData.EntityName;
                }
                if (value != "" && value != null && value.length == 9) {
                    var ubidata = { params: { UBINumber: $scope.feinData.UBINumber.replace(" ", "").replace(" ", "") } }
                    wacorpService.get(webservices.CFT.getOrganizationNameByUBI, ubidata, function (response) {
                        if (response.data.replace(/(^"|"$)/g, '') != "") {
                            $scope.feinData.EntityName = response.data.replace(/(^"|"$)/g, '').replace(/\\/g, '');
                            $scope.feinData.IsOrgNameExists = true;
                            $scope.feinData.IsUbiAssociated = false;
                            $scope.feinData.businessNames = 0;
                            if ($scope.feinData.UBIOldName != null && $scope.feinData.UBIOldName != undefined)
                                $scope.feinData.FeinUbiCount++;
                        }
                        else {
                            $scope.feinData.EntityName = $scope.feinData.UBIOldName;
                            //$scope.feinData.EntityName = "";
                            $scope.feinData.IsOrgNameExists = false;
                            $scope.feinData.IsUbiAssociated = true;
                        }
                    });

                }

            };


            $scope.getOrganizationNameByFEIN = function (value, type) {
                //$scope.feinData.IsOrgNameExists = false;
                //$scope.feinData.isBusinessNameChanged = false;
                if (value != "" && value != null && value.replace("-", "").length == 9) {
                    var feindata = { params: { FEINNumber: value.replace("-", ""), cftType: type } }
                    // getOrganizationNameByFEIN method is available in constants.js
                    wacorpService.get(webservices.CFT.getOrganizationNameByFEIN, feindata, function (response) {

                        //new logic 10/03/2017 TFS:15366
                        $scope.OrganizationNames = [];
                        $scope.OrganizationNames = response.data;
                        if ($scope.OrganizationNames.length > 0)
                            $("#divOrganizationNamesList").modal('toggle');
                        if ($scope.feinData.FeinOldvalue == null || $scope.feinData.FeinOldvalue == "")
                            $scope.feinData.FeinOldvalue = $scope.feinData.FEINNumber;

                        if ($scope.feinData.FeinOldvalue != $scope.feinData.FEINNumber) {
                            //$scope.feinData.IsShowFederalTax = true;
                            //if (!$scope.feinData.IsNewRegistration) {
                            //    if ($scope.feinData.FederaltaxUpload.length > 0) {
                            //        angular.forEach($scope.feinData.FederaltaxUpload, function (value, data)
                            //        {
                            //            if (value.BusinessFilingDocumentId > 0) {
                            //                wacorpService.confirmDialog($scope.messages.UploadFiles.irsConfirm, function () {
                            //                    value.Status=principalStatus.DELETE;
                            //            });
                            //            }
                            //            else {
                            //                var index = $scope.feinData.FederaltaxUpload.indexOf(value);
                            //                $scope.feinData.FederaltaxUpload.splice(index, constant.ONE);
                            //            }
                            //        });
                            //    }
                            //}
                            $scope.validateFeinRule(); // validateFeinRule method is available in this file only
                        }
                        else if ($scope.feinData.FeinOldvalue == $scope.feinData.FEINNumber) {
                            if (!$scope.feinData.IsNewRegistration) {
                                if ($scope.feinData.FederaltaxUpload.length > 0) {
                                    angular.forEach($scope.feinData.FederaltaxUpload, function (value, data) {
                                        var index = $scope.feinData.FederaltaxUpload.indexOf(value);
                                        $scope.feinData.FederaltaxUpload.splice(index, constant.ONE);
                                    });
                                }

                                $scope.feinData.IsFederalTax = $scope.feinData.OldIsFederalTax;
                                $scope.feinData.IsShowFederalTax = $scope.feinData.OldIsShowFederalTax;
                                $scope.feinData.FederalTaxExemptId = $scope.feinData.OldFederalTaxExemptId;
                            }
                        }
                        if (response.data == "")
                            $scope.feinData.IsOrgNameExists = false;
                        //if (response.data != "") {
                        //    $scope.OrganizationNames = response.data;
                        //    $("#divOrganizationNamesList").modal('toggle');
                        //    if ($scope.feinData.FeinOldvalue == null || $scope.feinData.FeinOldvalue == "") {
                        //        $scope.feinData.FeinOldvalue = $scope.feinData.FEINNumber;
                        //    }

                        //}
                        //else {
                        //    $scope.OrganizationNames = [];
                        //    $("#divOrganizationNamesList").modal('toggle');
                        //    //$scope.feinData.EntityName = "";
                        //    $scope.feinData.IsOrgNameExists = false;
                        //    //$scope.feinData.IsShowFederalTax = false;
                        //}
                    });
                }
            };


            $scope.validateFeinRule = function () {
                if ($scope.feinData.IsFederalTax
                                && $('#ddlCharityFein option:selected').text() != '--Select Status Type--'
                                && $('#ddlCharityFein option:selected').text() != 'Church/Church affiliated'
                                && $('#ddlCharityFein option:selected').text() != 'Government entity'
                                && $('#ddlCharityFein option:selected').text() != 'Annual gross receipts normally $5,000 or less') {
                    $scope.feinData.IsShowFederalTax = true;
                }
                else
                    $scope.feinData.IsShowFederalTax = false;
            };

            $scope.clearUBI = function () {
                if ($scope.feinData.FeinUbiCount >= 0)
                    $scope.feinData.EntityName = $scope.feinData.UBIOldName;

                $scope.feinData.IsOrgNameExists = false;
                $scope.feinData.IsUbiAssociated = true;
                $scope.feinData.UBINumber = '';
            }
            //Is FEIN Number exists or not checking
            $scope.IsFEINNumberExists = function () {
                var data = { params: { feinNumber: $scope.feinData.FEINNumber } }
                if (data.FEINNumber != '' && data.FEINNumber != null) {
                    // IsFEINNumberExists method is available in constants.js
                    wacorpService.get(webservices.CFT.IsFEINNumberExists, data, function (response) {
                        if (response.data == 'true') {
                            // Folder Name: app Folder
                            // Alert Name: isFEINExistorNot method is available in alertMessages.js 
                            wacorpService.alertDialog(messages.Fein.isFEINExistorNot);
                            $scope.feinData.IsFEINNumberExistsorNot = false;
                            $scope.feinData.FEINNumber = null;
                        }
                        else {
                            $scope.feinData.IsFEINNumberExistsorNot = true;
                        }
                    }, function (response) {
                    });
                }

            };

            $scope.onSelectOrganization = function (org) {
                $scope.SelectedOrganization = undefined;
                $scope.SelectedOrganization = org;
            }

            $scope.selectOrganization = function () {
                if ($scope.SelectedOrganization != null && $scope.SelectedOrganization != undefined) {
                    $scope.feinData.EntityName = $scope.SelectedOrganization.EntityName.replace(/(^"|"$)/g, '');
                    $scope.feinData.IsOrgNameExists = true;
                    $scope.feinData.businessNames = 0;
                    //if ($scope.feinData.FEINNumber != $scope.feinData.FeinOldvalue) {
                    //    $scope.feinData.FeinOldvalue = $scope.feinData.FEINNumber;
                    //    //$scope.feinData.IsShowFederalTax = true;
                    //}

                    if ($scope.feinData.FeinOldvalue != $scope.feinData.FEINNumber) {
                        //$scope.feinData.IsShowFederalTax = true;
                        $scope.validateFeinRule();
                    }
                    else if ($scope.feinData.FeinOldvalue == $scope.feinData.FEINNumber) {
                        if (!$scope.feinData.IsNewRegistration) {
                            if ($scope.feinData.FederaltaxUpload.length > 0) {
                                angular.forEach($scope.feinData.FederaltaxUpload, function (value, data) {
                                    var index = $scope.feinData.FederaltaxUpload.indexOf(value);
                                    $scope.feinData.FederaltaxUpload.splice(index, constant.ONE);
                                });
                            }

                            $scope.feinData.IsFederalTax = $scope.feinData.OldIsFederalTax;
                            $scope.feinData.IsShowFederalTax = $scope.feinData.OldIsShowFederalTax;
                            $scope.feinData.FederalTaxExemptId = $scope.feinData.OldFederalTaxExemptId;
                        }

                        //$scope.validateFeinRule();
                    }
                    $("#divOrganizationNamesList").modal('toggle');
                }
            }

            $scope.cancel = function () {
                $("#divOrganizationNamesList").modal('toggle');
            }
            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.feinData.UBINumber = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.feinData.UBINumber = pastedText;
                    });
                }
            };

            $scope.setUBILength = function (e)
            {
                if (e.currentTarget.value != undefined && e.currentTarget.value != null && e.currentTarget.value!="" && e.currentTarget.value.length >= 9) {
                    // Allow: backspace, delete, tab, escape, enter and .
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                        // Allow: Ctrl+A, Command+A
                        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                        // Allow: home, end, left, right, down, up
                        (e.keyCode >= 35 && e.keyCode <= 40)) {
                        // let it happen, don't do anything
                        return;
                    }
                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                    }
                    e.preventDefault();
                }
            };

            var oldvalue1 = '';
            $scope.$watch('feinData.FederalTaxExemptId', function (newValue, oldValue) {
                if (newValue != oldValue) {
                    oldvalue1 = oldValue;
                }
            });

            $scope.FederalChange = function (id, files) {
                if (id > 0) {
                    var cartlist = $filter('filter')($scope.FederalTaxTypes, { Key: id });
                    if (cartlist[0].Value === "Church/Church affiliated" || cartlist[0].Value === "Government entity" || cartlist[0].Value === "Annual gross receipts normally $5,000 or less") {
                        $scope.feinData.IsShowFederalTax = false;
                        $scope.feinData.FederalTaxExemptText = cartlist[0].Value;
                    }
                    else {
                        $scope.feinData.IsShowFederalTax = true;
                    }
                    if (!$scope.feinData.IsShowFederalTax) {
                        switch ($scope.feinData.FederalTaxExemptText) {
                            case 'Church/Church affiliated':
                                if ($scope.feinData.FederaltaxUpload != undefined && $scope.feinData.FederaltaxUpload.length > 0) {
                                    // Folder Name: app Folder
                                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js 
                                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                                        // deleteAllUploadedFiles method is available in constants.js
                                        wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                            $scope.feinData.FederaltaxUpload = [];
                                            $scope.feinData.IsShowFederalTax = false;
                                        })

                                    },
                                    function () {
                                        $scope.feinData.FederalTaxExemptId = oldvalue1;
                                        $scope.feinData.IsShowFederalTax = true;
                                    }
                                    );
                                }
                                break;
                            case 'Government entity':
                                if ($scope.feinData.FederaltaxUpload != undefined && $scope.feinData.FederaltaxUpload.length > 0) {
                                    // Folder Name: app Folder
                                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js 
                                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                                        // deleteAllUploadedFiles method is available in constants.js
                                        wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                            $scope.feinData.FederaltaxUpload = [];
                                            $scope.feinData.IsShowFederalTax = false;
                                        })

                                    },
                                    function () {
                                        $scope.feinData.FederalTaxExemptId = oldvalue1;
                                        $scope.feinData.IsShowFederalTax = true;
                                    }
                                    );
                                }

                                break;
                            case 'Annual gross receipts normally $5,000 or less':
                                if ($scope.feinData.FederaltaxUpload != undefined && $scope.feinData.FederaltaxUpload.length > 0) {
                                    // Folder Name: app Folder
                                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                                        // deleteAllUploadedFiles method is available in constants.js
                                        wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                            $scope.feinData.FederaltaxUpload = [];
                                            $scope.feinData.IsShowFederalTax = false;
                                        })

                                    },
                                    function () {
                                        $scope.feinData.FederalTaxExemptId = oldvalue1;
                                        $scope.feinData.IsShowFederalTax = true;
                                    });
                                }
                                break;
                        }
                    }
                }
                else if ($scope.feinData.FederalTaxExemptText != "Church/Church affiliated" || $scope.feinData.FederalTaxExemptText != "Government entity" || $scope.feinData.FederalTaxExemptText != "Annual gross receipts normally $5,000 or less") {
                    //$scope.feinData.IsShowFederalTax = false;
                    if ($scope.feinData.FederaltaxUpload != undefined && $scope.feinData.FederaltaxUpload.length > 0) {
                        // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            angular.forEach($scope.feinData.FederaltaxUpload, function (value, data) {
                                if (value.BusinessFilingDocumentId > 0) {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.feinData.FederaltaxUpload.indexOf(value);
                                    $scope.feinData.FederaltaxUpload.splice(index, 1);
                                }

                            });
                            $scope.feinData.IsShowFederalTax = false;
                            //wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                            //    $scope.feinData.FederaltaxUpload = [];
                            //})
                        }, function () {
                            $scope.feinData.IsShowFederalTax = true;
                            $scope.feinData.IsFederalTax = true;
                        });
                    }
                    else {
                        $scope.feinData.FederaltaxUpload = [];
                    }
                }
                else {
                    $scope.feinData.IsShowFederalTax = true;
                }

            }

            $scope.FederalNo = function () {
                $scope.feinData.FederalTaxExemptId = '';
            }

        },
    };
});

wacorpApp.directive('fundraiserentityInfo', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserEntityInfo/_FundraiserEntityInfo.html',
        restrict: 'A',
        scope: {
            entityInformation: '=?entityInformation',
            sectionName: '=?sectionName',
            showStreetAddress: '=?showStreetAddress',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.sectionName = $scope.sectionName || "";
            $scope.showStreetAddress = $scope.showStreetAddress || false;
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            //$scope.entityInformation.EntityConfirmEmailAddress = $scope.entityInformation.EntityEmailAddress;
            $scope.UploadListOfAddresses = [];
            $scope.FederalTaxTypes = [];
            $scope.mailingAddress1HasPOBOX = false;
            $scope.mailingAddress2HasPOBOX = false;
            var entityScope = {
                EntityName: null, EntityEmailAddress: null, EntityConfirmEmailAddress: null, EntityWebsite: null, EntityPhoneNumber: null, CountryCode: null, PhoneExtension: null,
                EntityMailingAddress: {
                    Attention: null, ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                EntityStreetAddress: {
                    Attention: null, ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, IsSameAsEntityMailingAddress: false, BusinessID: constant.ZERO, Status: null, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                , UploadListOfAddresses: [], IsUploadAddress: false
            };

            var EntityStreetAddressForCopy = {
                Attention: null, ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                    FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                }, FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
            }

            $scope.resetScope = {
                EntityMailingAddress: {
                    Attention: null, ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
            };

            $scope.entityInformation = $scope.entityInformation ? angular.extend(entityScope, $scope.entityInformation) : angular.copy(entityScope);

            //var entityInfo = $scope.entityInformation ? angular.extend(entityScope, $scope.entityInformation) : angular.copy(entityScope);
            //angular.extend($scope.entityInformation,entityInfo);
            $scope.$watch('entityInformation', function () {
                //$scope.entityInformation.isUploadAddress = angular.isNullorEmpty($scope.entityInformation.isUploadAddress) ? false : $scope.entityInformation.isUploadAddress;
                $scope.entityInformation.IsUploadAddress = $scope.entityInformation.UploadListOfAddresses == undefined ? false : ($scope.entityInformation.UploadListOfAddresses != null && $scope.entityInformation.UploadListOfAddresses.length > 0 ? true : false);
            });

            $scope.$watch('entityInformation.EntityMailingAddress', function (newValue, oldValue) {
                //if (newValue != oldValue) {
                if ($scope.isDocumentLoaded && $scope.entityInformation.IsSameAsEntityMailingAddress) {
                    angular.copy(oldValue, EntityStreetAddressForCopy);
                    //$scope.entityInformation.EntityStreetAddress = {
                    //    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                    //        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    //    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    //    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                    //};
                    //$scope.entityInformation.IsSameAsEntityMailingAddress = false;
                    $scope.CopyStreetFromMailing(); // CopyStreetFromMailing method is available in this file only
                }
                if ($scope.entityInformation.EntityMailingAddress != null || $scope.entityInformation.EntityMailingAddress != undefined) {
                    $scope.mailingAddress1HasPOBOX = wacorpService.ispOBoxExist($scope.entityInformation.EntityMailingAddress.StreetAddress1);
                    $scope.mailingAddress2HasPOBOX = wacorpService.ispOBoxExist($scope.entityInformation.EntityMailingAddress.StreetAddress2);
                }
            }, true);

          

            //Copy Mailing Addresses to Street address on same check box checked
            $scope.CopyStreetFromMailing = function () {
                if ($scope.entityInformation.IsSameAsEntityMailingAddress){
                    var county = $scope.entityInformation.EntityStreetAddress.County;
                    $scope.entityInformation.EntityStreetAddress = $scope.entityInformation.EntityMailingAddress;
                    $scope.entityInformation.EntityStreetAddress.County = county;
                }
                else {
                    $scope.entityInformation.EntityStreetAddress = {
                        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                            FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                        }, FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                        State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                    };
                    //$scope.entityInformation.EntityStreetAddress = EntityStreetAddressForCopy;
                }
            };


            $scope.deleteAllFiles = function (flag,files) {
                if (!flag && files.length > constant.ZERO) {
                    //files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    if ($scope.entityInformation.UploadListOfAddresses.length > 0)
                    {
                        // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js 
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            //$scope.entityInformation.UploadListOfAddresses = [];
                            
                            angular.forEach($scope.entityInformation.UploadListOfAddresses, function (value, data) {
                                if (value.BusinessFilingDocumentId > 0) {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.entityInformation.UploadListOfAddresses.indexOf(value);
                                    $scope.entityInformation.UploadListOfAddresses.splice(index, 1);
                                }
                            });
                            //wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files,
                            //function (response) {
                            $scope.entityInformation.IsUploadAddress = false;

                            //},
                            //);
                        },
                    function () {
                        $scope.entityInformation.IsUploadAddress = true;
                    });
                    }
                    
                }
            };

            $scope.isForeignContact = function () {
                //$scope.entityInformation.AreaCode = '';
                $scope.entityInformation.CountryCode = $scope.entityInformation.IsForeignContact ? '' : '1';
            };
            $scope.ValidateConfirmEmailAddress = function () {               
                if (($scope.entityInformation.EntityEmailAddress).toUpperCase() != ($scope.entityInformation.EntityConfirmEmailAddress).toUpperCase()) {
                    // Folder Name: app Folder
                    // Alert Name: emailMatch method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.PrincipalOffice.emailMatch);
                    $('#txtFund1emailFocus').focus();
                }
            }
            $scope.isDocumentLoaded = false;
            angular.element(document).ready(function () {
                $scope.isDocumentLoaded = true;
            });
        },

    };


});
wacorpApp.directive('fundraiserGlobalUpload', function ($http) {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserGlobalUploads/FundraiserGlobalUpload.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            isReview: '=?isReview',
            uploadList: '=?uploadList',
            uploadData: '=?uploadData',
            showErrorMessage: '=?showErrorMessage',
            fileSize: '=?fileSize',
            fileType: '=?fileType',
            validateFileType: '=?validateFileType',
            validateFileSize: '=?validateFileSize',
            isCorporation: '=?isCorporation',
        },
        controller: function ($scope, $http, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.isReview = $scope.isReview || false;
            $scope.uploadList = $scope.uploadList || [];
            $scope.uploadData = $scope.uploadData || {};
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.fileSize = angular.isNullorEmpty($scope.fileSize) ? uploadedFiles.FILESIZE : $scope.fileSize;
            $scope.fileType = angular.isNullorEmpty($scope.fileType) ? uploadedFiles.FILETYPES : $scope.fileType;
            $scope.validateFileType = angular.isNullorEmpty($scope.validateFileType) ? true : $scope.validateFileType;
            $scope.validateFileSize = angular.isNullorEmpty($scope.validateFileSize) ? true : $scope.validateFileSize;
            $scope.fileSizeMessage = $scope.messages.UploadFiles.fileSizeNote.replace('{0}', ($scope.fileSize / (uploadedFiles.FILESIZEMB)));
            $scope.fileTypeMessage = ($scope.fileType.toString() == 'NONE' || $scope.fileType.toString() == '') ? "" : $scope.messages.UploadFiles.fileTypeNote.replace('{0}', $scope.fileType.toString());
            $scope.DocumentTypes = [];
            $scope.DocumentType = $scope.DocumentType || "";
            $scope.DocumentTypeId = $scope.DocumentTypeId || "";
            $scope.isCorporation = angular.isNullorEmpty($scope.isCorporation) ? true : $scope.isCorporation;

            $scope.selectedDocumentType = function (items, selectedVal) {
                var result = "";
                angular.forEach(items, function (item) {
                    if (selectedVal == item.Key) {
                        result = item.Value;
                    }
                });
                return result;
            }

            if ($scope.isCorporation) {
                var lookupDocumentParams = { params: { name: 'UploadDocumentType' } };
                // GetLookUpData method is available in constants.js
                wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupDocumentParams, function (response) {
                    $scope.DocumentTypes = response.data;
                }, function (response) {
                });

                $scope.changeDocumentType = function (DocumentTypeId) {
                    $scope.DocumentType = $scope.selectedDocumentType($scope.DocumentTypes, DocumentTypeId); // selectedDocumentType method is available in this file only
                    $scope.DocumentTypeId = DocumentTypeId;
                };
            } else {
                var lookupDocumentParams = { params: { name: 'CharityUploadDocumentType' } };
                // GetLookUpData method is available in constants.js
                wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupDocumentParams, function (response) {
                    $scope.DocumentTypes = response.data;
                }, function (response) {
                });

                $scope.changeDocumentType = function (DocumentTypeId) {
                    $scope.DocumentType = $scope.selectedDocumentType($scope.DocumentTypes, DocumentTypeId); // selectedDocumentType method is available in this file only
                    $scope.DocumentTypeId = DocumentTypeId;
                };
            }

            $scope.$watch(function () {

                $scope.UploadLableText = $scope.sectionName.replace($scope.sectionName.split(' ')[0], '').trim();

                $scope.uploadConfirmation = $scope.messages.UploadFiles.uploadFilesSectionConfirmation.replace('{0}', $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName);
                $scope.uploadText = "";
                $scope.uploadText = $scope.sectionName;
            });

            // NOW UPLOAD THE FILES.
            $scope.upload = function (e) {
                if ($scope.DocumentTypeId <= 0 || $scope.DocumentTypeId == "") {
                    // Folder Name: app Folder
                    // Alert Name: uplodDocumentType method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.UploadFiles.uplodDocumentType);
                }
                else {
                    var validFormats = $scope.fileType;
                    $scope.files = [];
                    $scope.$apply(function () {
                        for (var i = constant.ZERO; i < e.files.length; i++) {
                            $scope.files.push(e.files[i])
                        }
                    });
                    var data = new FormData();
                    var selectedFiles = [];
                    for (var i in $scope.files) {
                        data.append("uploadedFile", $scope.files[i]);

                        var value = $scope.files[i];
                        if (value.name != "") {
                            var fileInfo = {
                                extenstion: value.name.substring(value.name.lastIndexOf('.') + constant.ONE).toLowerCase(),
                                size: value.size,
                            };
                            selectedFiles.push(fileInfo);
                        }
                    }
                    angular.forEach(selectedFiles, function (file) {
                        var fileTypeindex = constant.ZERO, filesizeValid = true, formatValid = false;
                        if ($scope.validateFileType) {
                            angular.forEach(validFormats, function (item) {
                                if (item.replace(/\s/g, '') == file.extenstion) {
                                    formatValid = true;
                                }
                            });
                            fileTypeindex = formatValid ? 1 : -1;
                        }
                        if ($scope.validateFileSize)
                            filesizeValid = file.size <= $scope.fileSize;
                        if (fileTypeindex > constant.NEGATIVE && filesizeValid) {
                            if ($rootScope.repository.loggedUser != undefined)
                                $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                            // fundraiserfileUpload method is available in constants.js
                            var uri = webservices.CFT.fundraiserfileUpload + '?DocumentType=' + $scope.DocumentType + '&DocumentTypeId=' + $scope.DocumentTypeId + '&FullUserName=' + ($rootScope.repository.loggedUser != undefined ? $rootScope.repository.loggedUser.FullUserName : '');
                            $http({
                                url: uri,
                                method: "POST",
                                cache: false,
                                data: data,
                                transformRequest: angular.identity,
                                headers: {
                                    'Content-Type': undefined
                                }
                            }).success(function (result) {
                                $scope.uploadList.push(result[constant.ZERO]);


                                angular.forEach($scope.DocumentTypes, function (item) {
                                    if ($scope.DocumentType == item.Value) {
                                        $scope.DocumentTypeId = "";
                                    }
                                });
                                $scope.DocumentTypeId = "";


                            }).error(function (result, status) {
                                // Folder Name: app Folder
                                // Alert Name: uploadFailed method is available in alertMessages.js
                                wacorpService.alertDialog($scope.messages.UploadFiles.uploadFailed);
                            });
                            $scope.filenotSupported = "";
                        }
                        else {
                            if (fileTypeindex == constant.NEGATIVE)
                                $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                            else if (fileTypeindex == constant.NEGATIVE && file.size > $scope.fileSize)
                                $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                            else if (file.size > $scope.fileSize) {
                                var size = ($scope.fileSize / (uploadedFiles.FILESIZEMB));
                                $scope.filenotSupported = $scope.messages.UploadFiles.fileSizeNotSupport.replace('{0}', size);
                            }
                        }
                    });

                    angular.element(e).val(null);
                }                
            }

            $scope.deleteFile = function (file, index) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                    // deleteUploadedFile method is available in constants.js
                    wacorpService.post(webservices.CFT.deleteUploadedFile, file,
                        function (response) {
                            if (response.data.BusinessFilingDocumentId > 0) {
                                angular.forEach($scope.uploadList, function (value, key) {
                                    if (response.data.BusinessFilingDocumentId == value.BusinessFilingDocumentId) {
                                        value.Status = response.data.Status;
                                    }
                                });
                            }
                            else {
                                //var index = $scope.uploadList.indexOf(response);
                                $scope.uploadList.splice(index, constant.ONE);
                            }
                            // Folder Name: app Folder
                            // Alert Name: fileDelete method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDelete);
                            if ($scope.uploadList.length == 0) {
                                $scope.uploadList = [];
                            }
                        },
                        function (response) {
                            // Folder Name: app Folder
                            // Alert Name: fileDeleteFailed method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDeleteFailed);
                        }
                    );
                });
            };

            $scope.globalUploadClick = function () {
                var uploadID = $scope.modalName + '_UploadGlobalFile';
                $('#' + uploadID).trigger('click');
            };
        },

    };
});
wacorpApp.directive('newEntityName', function () {
    return {
        templateUrl: 'ng-app/directives/NewEntityName/NewEntityName.html',
        restrict: 'A',
        scope: {
            entity: '=?entity',
            showErrorMessage: '=?showErrorMessage',
            sectionName: '=?sectionName',
            isReinstatement: '=?isReinstatement'
        },
        controller: function ($scope, wacorpService, $timeout, lookupService, $rootScope) {
            if ($scope.entity.businessNames) {
                $scope.entity.businessNames.length = 0;
            }

            if ($scope.entity.IsAmendmentEntityNameChange && ($rootScope.transactionID || $rootScope.isIncompleteFiling)) {
                $timeout(function () {
                    if ($scope.entity.BusinessName && $scope.entity.IsNameReserved && $rootScope.isIncompleteFiling) {
                        $scope.entity.isBusinessNameAvailable = true;
                    }
                    else
                    {
                        $scope.entity.isBusinessNameAvailable = false;
                    }

                    $scope.entity.isDBANameAvailable = false;
                    $rootScope.isIncompleteFiling = false;
                    $rootScope.transactionID = '';
                }, 2000);
            }

            $scope.messages = messages;
            $scope.entity = $scope.entity || {};
            $scope.entity.NameReservedId = $scope.entity.NameReservedId == constant.ZERO ? null : $scope.entity.NameReservedId;
            var entityScope = { Indicators: [], IndicatorsCSV: null, ID: constant.ZERO, BusinessTypeID: constant.ZERO, Note: null, IsValidEntityName: false, IsValidDBAName: false, IndicatorsDisplay: null, PSIndicatorsDisplay: null };
            //var entityScope = { Indicators: [], IndicatorsCSV: null, ID: constant.ZERO, BusinessTypeID: constant.ZERO, Note: null, IsValidEntityName: false, IsValidDBAName: false };
            $scope.entity.Indicator = $scope.entity.Indicator ? angular.extend(entityScope, $scope.entity.Indicator) : entityScope;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.CheckforLookUp = true;
            $scope.businessNameNotAvailCount = 0;
            $scope.NameChanged = false;
            // $scope.entity.isBusinessReserved = $scope.entity.isBusinessReserved || false;
            $scope.entity.oldBusinessName = angular.copy($scope.entity.BusinessName || '');
            //$scope.entity.NewBusinessName = angular.copy($scope.entity.BusinessName || '');
            $scope.entity.NewBusinessName = !angular.isNullorEmpty($scope.entity.NewBusinessName) ? $scope.entity.NewBusinessName : $scope.entity.BusinessName;
            $scope.entity.BusinessName = $scope.entity.BusinessName;
            $scope.sectionName = angular.isNullorEmpty($scope.sectionName) ? "" : $scope.sectionName;
            $scope.entity.IsAmendmentEntityNameChange = angular.isNullorEmpty($scope.entity.IsAmendmentEntityNameChange) ? false : $scope.entity.IsAmendmentEntityNameChange; //Is Entity Type Radio button


            if ($scope.entity.DBABusinessName) {
                $scope.entity.IsDBAInUse = true;
            }

            //$scope.$watch("entity.IsAmendmentEntityNameChange", function (newValue,oldValue) {

            //    $scope.entity.isBusinessNameAvailable = !newValue;

            //    if (!newValue) {
            //        $scope.entity.DBABusinessName = $scope.entity.DBABusinessName || $scope.oldDBAName;
            //    }
            //});
            // here BusinessStatusID = 1 is Active, BusinessStatusID = 2 is Delinquent, BusinessStatusID = 10 is Active Pending,
            if ($scope.entity.BusinessStatusID && ($scope.entity.BusinessStatusID == 1 || $scope.entity.BusinessStatusID == 2 || $scope.entity.BusinessStatusID == 10)) {
                if ($scope.entity.BusinessName && !$scope.entity.IsAmendmentEntityNameChange) {
                    $scope.entity.isBusinessNameAvailable = true;
                }
            }


            if ($scope.entity.BusinessName && $scope.entity.IsNameReserved && $rootScope.isIncompleteFiling) {
                $scope.entity.isBusinessNameAvailable = true;
            }

            $scope.GetReservedBusiness = function (EntityName) {

                $scope.validateReservedName = true;
                if ($scope[EntityName].ReservedName.$valid) {
                    $scope.validateReservedName = false;
                    var config = {
                        params: { registrationID: parseInt($scope.entity.NameReservedId) }
                    };
                    // GetReservedBusiness method is available in constants.js
                    wacorpService.get(webservices.Common.GetReservedBusiness, config, function (response) {
                        if (response.data.BusinessName != null) {
                            $scope.entity.IsNameReservedChecked = true;
                            $scope.entity.holdOldBusinessName = $scope.entity.OldBusinessName;
                            $scope.entity.NewBusinessName = response.data.BusinessName;
                            $scope.entity.BusinessName = response.data.BusinessName;
                            //$scope.entity.BusinessID = response.data.BusinessID;
                            $scope.entity.NameReservedId = response.data.BusinessID;
                            $scope.entity.BusinessIndicator = response.data.BusinessIndicator;
                        }
                        else {
                            $scope.entity.NewBusinessName = null;
                            // $scope.entity.BusinessName = null;
                            //   $scope.entity.BusinessID = constant.ZERO;
                            //$scope.entity.NameReservedId = null;
                            // Folder Name: app Folder
                            // Alert Name: noReservedName method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.EntityName.noReservedName);
                        }

                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
            };

            $scope.GetReservedBusinessClear = function (EntityName) {
                if ($scope[EntityName].ReservedName.$valid) {
                    $scope.entity.NewBusinessName = "";
                    $scope.entity.BusinessName = "";
                    //$scope.entity.BusinessID = "";
                    //$scope.entity.IsNameReserved = "";
                }
            };

            $scope.isValidIndicator = function (isLookup, indicator) {
                if (indicator)
                {
                    $scope.entity.Indicator = indicator;
                }
                if ($scope.entity.DBABusinessName) {
                    $scope.entity.IsDBAInUse = true;
                } else {
                    $scope.entity.IsDBAInUse = false;
                }

                //if ($scope.entity.businessNames) {
                //    $scope.entity.businessNames.length = 0;
                //}

                var indicatorsCSV = null;
                var indicatorslist = null;
                var indicatorsMustNotCSV = null;
                var IndicatorsDisplay = null;
                indicatorsMustNotCSV = $scope.entity.Indicator.IndicatorsMustNotCSV;
                //$scope.entity.BusinessIndicator = '';
                // is dental service checked true
                if ($scope.entity.Indicator.isDentalCheck) {
                    indicatorsCSV = $scope.entity.Indicator.PSIndicatorsCSV;
                    indicatorslist = $scope.entity.Indicator.PSIndicatorList;
                    indicatorsDisplay = $scope.entity.Indicator.PSIndicatorsDisplay;
                }
                else {
                    indicatorsCSV = $scope.entity.Indicator.IndicatorsCSV;
                    indicatorslist = $scope.entity.Indicator.Indicators;
                    indicatorsDisplay = $scope.entity.Indicator.IndicatorsDisplay;
                }
                var isValid = constant.ZERO;
                var isInValidIndicator = constant.ZERO;
                var entityName;

                if ($scope.entity.IsNameReservedChecked) {
                    //$scope.entity.BusinessName = $scope.entity.holdOldBusinessName;
                    //!!!***** Replaced line above with line below, Ref. TFS#1134; KK, 10/7/2019
                    $scope.entity.OldBusinessName = $scope.entity.holdOldBusinessName; 
                }

                if ($scope.entity.isUpdate != undefined && $scope.entity.isUpdate && $scope.entity.isUpdate != false) {
                    entityName = $scope.entity.BusinessName + ' ' + indicatorsCSV;
                    entityName = entityName.toLowerCase().replace(/[{|}|(|)|-|;|'|\"]/g, '');
                }
                else {
                    entityName = $scope.entity.BusinessName != null ? $scope.entity.BusinessName.toLowerCase().replace(/[{|}|(|)|-|;|'|\"]/g, '') : null;
                }

                if (indicatorsCSV != null && indicatorsCSV != undefined && indicatorsCSV != '') {

                    angular.forEach(indicatorslist, function (value) {
                        value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                        //isValid = new RegExp("^" + value + "\\s").test(entityName) ? isValid + constant.ONE : isValid;
                        // Start With indicator
                        if (new RegExp("^" + value + "\\s").test(entityName)) {
                            if (entityName.indexOf(value + ' ') != -1) {
                                isValid = isValid + constant.ONE;
                                return;
                            }
                        }
                    });

                    if (isValid == constant.ZERO) {
                        angular.forEach(indicatorslist, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            // isValid = new RegExp("\\s" + value + "\\s").test(entityName) ? isValid + constant.ONE : isValid;
                            // Middile With indicator
                            if (new RegExp("\\s" + value + "\\s").test(entityName)) {
                                if (entityName.indexOf(' ' + value + ' ') != -1) {
                                    isValid = isValid + constant.ONE;
                                    return;
                                }
                            }
                        });
                    }
                    if (isValid == constant.ZERO) {
                        angular.forEach(indicatorslist, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            //isValid = new RegExp("\\s" + value + "$").test(entityName) ? isValid + constant.ONE : isValid;
                            // Last With indicator
                            if (new RegExp("\\s" + value + "$").test(entityName)) {
                                if (entityName.indexOf(' ' + value) != -1) {
                                    isValid = isValid + constant.ONE;
                                    return;
                                }
                            }
                        });
                    }
                }
                else {
                    isValid = constant.ONE; //For all entities we are not going to have Indicators, that's the reason default we are considering as true.
                }

                if (indicatorsMustNotCSV != null && indicatorsMustNotCSV != undefined && indicatorsMustNotCSV != '') {
                    var isNonCorp = false;
                    var aNonprofitCorp = "a nonprofit corporation";
                    var aNonprofitMutualCorp = "a nonprofit mutual corporation";
                    var corporation = "corporation";

                    if (entityName != "" && entityName != null) {
                        isNonCorp = new RegExp("^" + aNonprofitCorp + "\\s").test(entityName) || new RegExp("^" + aNonprofitMutualCorp + "\\s").test(entityName);

                        if (!isNonCorp) {
                            isNonCorp = new RegExp("\\s" + aNonprofitCorp + "\\s").test(entityName) || new RegExp("\\s" + aNonprofitMutualCorp + "\\s").test(entityName);
                        }
                        if (!isNonCorp) {
                            isNonCorp = new RegExp("\\s" + aNonprofitCorp + "$").test(entityName) || new RegExp("\\s" + aNonprofitMutualCorp + "$").test(entityName);
                        }
                    }

                    var indicatorsMustNot = indicatorsMustNotCSV.toLowerCase().split(',');
                    angular.forEach(indicatorsMustNot, function (value) {
                        value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                        if (isNonCorp && value == corporation) {
                            isInValidIndicator = constant.ZERO;
                        }
                        else {
                            //isInValidIndicator = new RegExp("^" + value + "\\s").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                            // Start With indicator
                            if (new RegExp("^" + value + "\\s").test(entityName)) {
                                if (entityName.indexOf(value + ' ') != -1) {
                                    isInValidIndicator = isInValidIndicator + constant.ONE;
                                    return;
                                }
                            }
                        }
                    });

                    if (isInValidIndicator == constant.ZERO) {
                        angular.forEach(indicatorsMustNot, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            if (isNonCorp && value == corporation) {
                                isInValidIndicator = constant.ZERO;
                            }
                            else {
                                //isInValidIndicator = new RegExp("\\s" + value + "\\s").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                                // Middile With indicator
                                if (new RegExp("\\s" + value + "\\s").test(entityName)) {
                                    if (entityName.indexOf(' ' + value + ' ') != -1) {
                                        isInValidIndicator = isInValidIndicator + constant.ONE;
                                        return;
                                    }
                                }
                            }
                        });
                    }
                    if (isInValidIndicator == constant.ZERO) {
                        angular.forEach(indicatorsMustNot, function (value) {
                            value = value.replace(/[{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                            if (isNonCorp && value == corporation) {
                                isInValidIndicator = constant.ZERO;
                            }
                            else {
                                //isInValidIndicator = new RegExp("\\s" + value + "$").test(entityName) ? isInValidIndicator + constant.ONE : isInValidIndicator;
                                // Last With indicator
                                if (new RegExp("\\s" + value + "$").test(entityName)) {
                                    if (entityName.indexOf(' ' + value) != -1) {
                                        isInValidIndicator = isInValidIndicator + constant.ONE;
                                        return;
                                    }
                                }
                            }
                        });
                    }
                }

                var dbaInvalidMsg = "";
                if (isInValidIndicator >= 1) {
                    $scope.indicatorValidMessage = "The business name contains an invalid indicator like (" + indicatorsMustNotCSV.replace(/,/g, ', ').toUpperCase() + ").";
                    dbaInvalidMsg = $scope.messages.EntityName.UseDBANameForMustNotIndicator;
                }
                else {
                    if ($scope.entity.BusinessName != null && $scope.entity.BusinessName != "") {
                        $scope.indicatorValidMessage = isValid > constant.ZERO ? "" : "The business name requested does not contain the necessary designation. Please input one of the required designations (" + indicatorsDisplay.replace(/,/g, ', ').toUpperCase() + ").";// TFS ID 12017
                        dbaInvalidMsg = $scope.messages.EntityName.UseDBANameForIndicator;
                        if ($scope.entity.oldBusinessName != $scope.entity.BusinessName) {
                            $scope.entity.isBusinessNameAvailable = false;

                            if (!isLookup && $scope.entity.businessNames)
                                $scope.entity.businessNames.length = 0;
                        }

                        if ($scope.availableBusinessCount() > constant.ZERO) {
                            $scope.entity.isBusinessNameAvailable = false;
                        }

                        if ($scope.entity.oldBusinessName == $scope.entity.BusinessName) {
                            $scope.entity.isBusinessNameAvailable = true;
                            $scope.entity.Indicator.IsValidEntityName = true;
                        }
                    }
                    else {
                        $scope.indicatorValidMessage = $scope.entity.isBusinessNameAvailable = "";
                    }
                }

                if ($scope.entity.oldBusinessName != $scope.entity.BusinessName)
                    $scope.entity.isBusinessNameAvailable = false;

                $scope.entity.isDBANameAvailable = false; //Ticket - 75938

                // validate and show alert to continue with DBA 
                $scope.entity.IsDBASectionExist = (lookupService.canShowScreenPart($scope.entity.AllScreenParts.DbaName, $scope.entity, $scope.entity.BusinessTypeID)) ? true : false

                // DBA lOOK UP ISSUE, if Look up issue we have to display DBA Confirmation issue 
                if ($scope.entity.IsDBASectionExist && isLookup) {
                    $scope.showErrorMessage = false;
                    $scope.isContinueDBAName = false;
                }
                else if ($scope.entity.IsDBASectionExist && ($scope.isContinueDBAName == undefined || !$scope.isContinueDBAName)) {
                    $scope.showErrorMessage = false;
                    $scope.isContinueDBAName = false;
                }
                else if ($scope.isContinueDBAName) {
                    $scope.isContinueDBAName = false;
                    $scope.showErrorMessage = true;
                }

                if ($scope.indicatorValidMessage && $scope.entity.IsDBASectionExist && $scope.entity.IsAmendmentEntityNameChange && !$scope.showErrorMessage) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.confirmOkCancel(dbaInvalidMsg,
                        function () {
                            $scope.entity.IsDBAInUse = true;
                            //$scope.entity.DBABusinessName = $scope.oldDBAName;
                        },
                        function () {
                            $scope.entity.IsDBAInUse = false;
                            $scope.entity.OldDBABusinessName = $scope.entity.DBABusinessName;
                            $scope.entity.DBABusinessName = '';
                        }
                    );
                }
                else if ($scope.entity.IsDBASectionExist && $scope.entity.IsDBAInUse) {
                    //$scope.entity.IsDBAInUse = false; //75938 
                    $scope.entity.OldDBABusinessName = $scope.entity.DBABusinessName || $scope.entity.OldDBABusinessName;
                    //$scope.entity.DBABusinessName = ''; //75938 
                    $scope.entity.isBusinessNameAvailable = false;// $scope.messages.EntityName.businessNameAvaibilityCheck;;
                }

                if ($scope.entity.IsAmendmentEntityNameChange && $scope.entity.oldBusinessName != $scope.entity.BusinessName) {
                    $scope.entity.isBusinessNameAvailable = false;
                }
                else {
                    $scope.entity.isBusinessNameAvailable = true;
                }
            };

            $scope.$watch("entity.BusinessName", function () {
                if (!$scope.entity.isValidIndicator)
                    $scope.entity.isValidIndicator = $scope.isValidIndicator;
            });


            $scope.searchBusinessNames = function (EntityName) {
                $scope.entity.isBusinessNameAvailable = "";
                $scope.NameChanged = false;
                $scope.businessNameNotAvailCount = 0;
                $scope.entity.oldBusinessName = $scope.entity.OldBusinessName
                $scope.validateBusinessName = true;
                if ($scope[EntityName].txtBusiessName.$valid) {
                    $scope.validateBusinessName = false;
                    var config = {
                        params: { businessName: $scope.entity.BusinessName, isInhouse: false, businessId: angular.isNullorEmpty($scope.entity.BusinessID) ? 0 : $scope.entity.BusinessID }
                    };
                    // GetBusinessNames method is available in constants.js
                    wacorpService.get(webservices.Common.GetBusinessNames, config, function (response) {
                        $scope.entity.businessNames = response.data;
                        $scope.entity.isBusinessNameAvailable = false;
                        angular.forEach($scope.entity.businessNames, function (item, index) {
                            //if (item.AvailableStatus == "Available") {
                            //    $scope.entity.isBusinessNameAvailable = true;
                            //    $scope.entity.IsDBAInUse = false;
                            //    $scope.entity.DBABusinessName = '';
                            //}

                            if (item.AvailableStatus == "Available") {
                                $scope.entity.isBusinessNameAvailable = true;
                                $scope.entity.IsDBAInUse = false;
                                $scope.entity.DBABusinessName = '';
                                $scope.businessNameNotAvailCount = 0;
                                $scope.CheckforLookUp = false;
                            }
                            else if (item.AvailableStatus == "Not Available") {
                                $scope.businessNameNotAvailCount = 1;
                                $scope.CheckforLookUp = false;
                            }
                        });

                        //TFS ticket 
                        // Service Folder: services
                        // File Name: lookupService.js (you can search with file name in solution explorer)
                        $scope.entity.IsDBASectionExist = (lookupService.canShowScreenPart($scope.entity.AllScreenParts.DbaName, $scope.entity, $scope.entity.BusinessTypeID)) ? true : false
                        if (!$scope.entity.isBusinessNameAvailable && $scope.entity.IsDBASectionExist) {
                            // Folder Name: app Folder
                            // Alert Name: UseDBAName method is available in alertMessages.js 
                            wacorpService.confirmOkCancel($scope.messages.EntityName.UseDBAName,
                                  function () {
                                      $scope.entity.IsDBAInUse = true;
                                      $scope.entity.DBABusinessName = $scope.entity.DBABusinessName ? $scope.entity.DBABusinessName : $scope.entity.OldDBABusinessName;
                                  },
                                  function () {
                                      $scope.entity.IsDBAInUse = false;
                                      $scope.entity.OldDBABusinessName = $scope.entity.DBABusinessName;
                                      $scope.entity.DBABusinessName = '';
                                  }
                                  );
                        }
                        else if ($scope.isReinstatement && !$scope.entity.isBusinessNameAvailable) {
                            // Folder Name: app Folder
                            // Alert Name: nameAlreadyUsed method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.EntityName.nameAlreadyUsed);
                        }
                        if ($scope.entity.isBusinessNameAvailable && $scope.entity.IsDBASectionExist) {
                            $scope.isValidIndicator(true); // isValidIndicator method is available in this file only.
                        }

                        //$scope.entity.UBINumber = ((response.UBINumber == "" || response.UBINumber == null || response.UBINumber == undefined) ? "" : response.UBINumber);
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
            };

            $scope.selectBusiness = function (businessName) {
                $scope.entity.NewBusinessName = businessName;
            };

            $scope.resetOnReserveClick = function () {
                var previousBusinessName = $scope.entity.OldBusinessName;
                $scope.entity.DontShowMessage = false;
                if ($scope.entity.IsNameReserved) {
                    $scope.entity.NewBusinessName = '';
                    $scope.indicatorValidMessage = '';
                    $scope.entity.isBusinessNameAvailable = '';
                    $scope.validateBusinessName = '';
                    $scope.entity.businessNames = [];
                    $scope.entity.BusinessName = '';
                    $scope.entity.BusinessIndicator = '';
                    //Newly added as per ticket 44757
                    $scope.entity.IsDBAInUse = false;
                    $scope.entity.DBABusinessName = '';
                    $scope.entity.DontShowMessage = true;
                }
                else {
                    $scope.entity.NameReservedId = '';
                    $scope.indicatorValidMessage = '';
                    $scope.entity.isBusinessNameAvailable = '';
                    $scope.validateReservedName = '';
                    $scope.entity.BusinessName = previousBusinessName;
                    $scope.entity.DBABusinessName = $scope.entity.OldDBABusinessName;
                    $scope.entity.DontShowMessage = true;
                    $scope.entity.BusinessIndicator = '';
                    $scope.entity.IsNameReservedChecked = false;
                    $scope.entity.NewBusinessName = '';
                    $scope.entity.NewDBABusinessName = '';
                }
            };

            $scope.availableBusinessCount = function () {
                if ($scope.entity.businessNames == undefined || $scope.entity.businessNames == null) {
                    return constant.ZERO;
                }
                else {
                    var availableBusinessList = $scope.entity.businessNames.filter(function (name) {
                        return (name.IsAvailable || name.IsOrgBusinessName);
                    });
                    return availableBusinessList.length;
                }
            };

            var changeBusinessTypeFunction = function (value) {
                if (parseInt($scope.entity.BusinessTypeID) == $scope.entity.oldAmendmentEntity.BusinessTypeID) {
                    $scope.entity.IsAmendmentEntityNameChange = false;
                    $scope.entity.BusinessName = $scope.entity.oldAmendmentEntity.BusinessName;
                    $scope.entity.IsNameReserved = $scope.entity.oldAmendmentEntity.IsNameReserved;
                    $scope.entity.NameReservedId = $scope.entity.oldAmendmentEntity.NameReservedId == constant.ZERO ? null : $scope.entity.oldAmendmentEntity.NameReservedId;
                    var entityScope = { Indicators: [], IndicatorsCSV: null, ID: constant.ZERO, BusinessTypeID: constant.ZERO, Note: null, IsValidEntityName: false, IsValidDBAName: false, IndicatorsDisplay: null, PSIndicatorsDisplay: null };
                    var entityScope = { Indicators: [], IndicatorsCSV: null, ID: constant.ZERO, BusinessTypeID: constant.ZERO, Note: null, IsValidEntityName: false, IsValidDBAName: false };
                    $scope.entity.Indicator = $scope.entity.oldAmendmentEntity.Indicator ? angular.extend(entityScope, $scope.entity.oldAmendmentEntity.Indicator) : entityScope;
                }

                $scope.entity.oldBusinessName = angular.copy($scope.entity.oldAmendmentEntity.BusinessName || '');
                $scope.entity.NewBusinessName = !angular.isNullorEmpty($scope.entity.oldAmendmentEntity.NewBusinessName) ? $scope.entity.oldAmendmentEntity.NewBusinessName : $scope.entity.oldAmendmentEntity.BusinessName;
                $scope.entity.NewDBABusinessName = !angular.isNullorEmpty($scope.entity.oldAmendmentEntity.NewDBABusinessName) ? $scope.entity.oldAmendmentEntity.NewDBABusinessName : $scope.entity.oldAmendmentEntity.DBABusinessName;

                $scope.entity.BusinessName = $scope.entity.oldAmendmentEntity.BusinessName;
                $scope.entity.DBABusinessName = $scope.entity.oldAmendmentEntity.DBABusinessName;
                $scope.entity.BusinessIndicator = '';
                $scope.showErrorMessage = false;
                if ($scope.entity.IsDBASectionExist && $scope.entity.DBABusinessName && !$scope.entity.invalidDBAIndicator) {
                    $scope.entity.IsDBAInUse = true;
                    $scope.entity.isDBANameAvailable = true;
                }
                else {
                    $scope.entity.IsDBAInUse = false;
                }
                if ($scope.entity.IsAmendmentEntityType)
                {
                    if ($scope.entity.isForeign) {
                        $rootScope.$broadcast('isFAmendmentEntityTypeChange', value);
                    }
                    else {
                        $rootScope.$broadcast('isBAmendmentEntityTypeChange', value);
                    }
                }
            };

            //  Amendment Entity Name Change Radio button change click
            $scope.isAmendmentEntityNameChange = function (value) {
                // No radio button Click
                if (!value) {
                    if ($scope.entity.IsAmendmentEntityType && (parseInt($scope.entity.BusinessTransaction.BusinessTypeID) != $scope.entity.oldAmendmentEntity.BusinessTypeID)) {
                        //Ticket-3186
                        wacorpService.confirmOkCancel($scope.messages.EntityName.ResetAmendBusinessType,
                            function () {
                                changeBusinessTypeFunction(value); // changeBusinessTypeFunction method is available in this file only.
                            },
                            function () {
                                $scope.entity.IsAmendmentEntityNameChange = true;
                            }
                        );
                    }
                    else {
                        changeBusinessTypeFunction(value); // changeBusinessTypeFunction method is available in this file only.
                    }
                }
                    // Yes radio button Click
                else {
                    $scope.entity.IsAmendmentEntityNameChange = true;
                }
            };

            // Reservation Number stop the alphanumeric text
            $scope.setPastedReservednumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 15);
                    $scope.entity.NameReservedId = pastedText;
                    $scope.checkValue($scope.entity.NameReservedId); // checkValue method is available in this file only.
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 15);
                        $scope.entity.NameReservedId = pastedText;
                    });
                }
            };

            // Check the value
            $scope.checkValue = function (value, id) {
                if (value != "" && value != undefined && value.length > 0) {
                    $scope.formValid = true;
                }
                else
                    $scope.formValid = false;

                //$('#'+id).focus();
            };

            $scope.$watch('entity.BusinessName', function (newValue, oldValue) {
                if (newValue != oldValue) {
                    $scope.NameChanged = angular.equals($scope.project, $scope.original);
                    if ($scope.NameChanged) {
                        $scope.CheckforLookUp = !$scope.entity.IsNameReserved && !$scope.entity.IsDBAInUse;
                    }
                }
                else {
                    $scope.NameChanged = false;
                }
            }, true);

            var onBusinessTypeChange = function () {
                $scope.isValidIndicator();
            };

            //Here we are declaring the Method which will be calling in PO and RA Components
            var businessTypeChanged = $scope.$on("onBusinessTypeChange", function () {
                onBusinessTypeChange(); // onBusinessTypeChange method is available in this file only.
            });

            $scope.$on('$destroy', function () {
                businessTypeChanged(); // businessTypeChanged method is available in this file only.
            });
            //$scope.isValidIndicator();

            var checkIndicatorValidation = $scope.$on("checkIndicator", function (evt, data) {
                $scope.isContinueDBAName = true;
                $scope.isValidIndicator();
            });

            $scope.$on('$destroy', checkIndicatorValidation);
        }
    };
});
wacorpApp.directive('entityInfo', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/EntityInfo/_EntityInfo.html',
        restrict: 'A',
        scope: {
            entityInformation: '=?entityInformation',
            sectionName: '=?sectionName',
            showStreetAddress: '=?showStreetAddress',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
        },
        controller: function ($scope, lookupService, wacorpService, $timeout, $rootScope, $location) {
            $scope.messages = messages;
            $scope.sectionName = $scope.sectionName || "";
            $scope.showStreetAddress = $scope.showStreetAddress || false;
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.entityInformation.EntityConfirmEmailAddress = ($scope.entityInformation != undefined && $scope.entityInformation != null) ? $scope.entityInformation.EntityEmailAddress : null;
            $scope.UploadListOfAddresses = [];
            $scope.FederalTaxTypes = [];
            var isPageLoad = true;
            $scope.mailingAddressHasPOBOX = false;
            var entityScope = {
                EntityName: null, EntityEmailAddress: null, EntityConfirmEmailAddress: null, EntityWebsite: null, EntityPhoneNumber: null, CountryCode: null, PhoneExtension: null,
                EntityMailingAddress: {
                    Attention: null, ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                EntityStreetAddress: {
                    Attention: null, ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, IsSameAsEntityMailingAddress: false, BusinessID: constant.ZERO, Status: null, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                , UploadListOfAddresses: [], IsUploadAddress: false
            };

            var EntityStreetAddressForCopy = {
                Attention: null, ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                    FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                }, FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
            }

            $scope.resetScope = {
                EntityMailingAddress: {
                    Attention: null, ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
            };

            $scope.IsAlphaNumeric = function (e) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                var result = wacorpService.IsAlphaNumeric(e);
                var keyCode = e.which || e.keyCode;
                if (!result && keyCode == 8 || keyCode == 46 || e.key == "ArrowLeft" || e.key == "ArrowRight") { }
                else if (!result && e.key != "Tab") {
                    e.preventDefault();
                }
            };

            //var entityInfo = $scope.entityInformation ? angular.extend(entityScope, $scope.entityInformation) : angular.copy(entityScope);
            //angular.extend($scope.entityInformation,entityInfo);
            $scope.$watch('entityInformation', function () {
                //$scope.entityInformation.isUploadAddress = angular.isNullorEmpty($scope.entityInformation.isUploadAddress) ? false : $scope.entityInformation.isUploadAddress;
                $scope.entityInformation.IsUploadAddress = $scope.entityInformation.UploadListOfAddresses == undefined ? false : ($scope.entityInformation.UploadListOfAddresses != null && $scope.entityInformation.UploadListOfAddresses.length > 0 ? true : false);
            });


            $scope.$watch('entityInformation.EntityMailingAddress', function (newValue, oldValue) {
                var isReview = ($location.path().indexOf("Review")) != -1 ? true : false;
                if (newValue != undefined && newValue != "" && newValue != null && oldValue != undefined && oldValue != "" && oldValue != null) {
                    if (newValue.FullAddressWithoutCounty == $scope.entityInformation.EntityStreetAddress.FullAddressWithoutCounty) {
                        return;
                    }
                    else if ($scope.isDocumentLoaded && $scope.entityInformation.IsSameAsEntityMailingAddress && !isReview)
                    {
                        //angular.copy(oldValue, EntityStreetAddressForCopy);

                        $scope.entityInformation.EntityStreetAddress = {
                            ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                            }, FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                            State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                        };
                        //$scope.CopyStreetFromMailing();
                        $scope.entityInformation.IsSameAsEntityMailingAddress = false;
                    }
                    else if ($scope.entityInformation.IsSameAsEntityMailingAddress) {
                        $scope.CopyStreetFromMailing(); // CopyStreetFromMailing method is available in this file only
                    }

                    if ($('#chkIsSameAsOrganization').is(":checked")) {
                        $rootScope.$broadcast('onMailingAddressChanged');
                    }
                }

                //if ($scope.isDocumentLoaded && $scope.entityInformation.IsSameAsEntityMailingAddress) {
                //    angular.copy(oldValue, EntityStreetAddressForCopy);

                //    //$scope.entityInformation.EntityStreetAddress = {
                //    //    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                //    //        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                //    //    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                //    //    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                //    //};
                //    $scope.CopyStreetFromMailing();

                //    $scope.entityInformation.IsSameAsEntityMailingAddress = false;

                //}
                //else {
                //    $scope.entityInformation.EntityStreetAddress = {
                //        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                //            FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                //        }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                //        State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                //    };
                //}
                if ($scope.entityInformation.EntityMailingAddress != null || $scope.entityInformation.EntityMailingAddress != undefined) {
                    $scope.mailingAddressHasPOBOX = wacorpService.ispOBoxExist($scope.entityInformation.EntityMailingAddress.StreetAddress1) || wacorpService.ispOBoxExist($scope.entityInformation.EntityMailingAddress.StreetAddress2);
                }
            }, true);


            //$scope.$watch('entityInformation.EntityMailingAddress', function (newValue, oldValue) {

            //    if ($scope.isDocumentLoaded && $scope.entityInformation.IsSameAsEntityMailingAddress && isPageLoad) {
            //        angular.copy(oldValue, EntityStreetAddressForCopy);
            //        $scope.CopyStreetFromMailing();
            //        isPageLoad = false;
            //    }
            //    else if ($scope.isDocumentLoaded && $scope.entityInformation.IsSameAsEntityMailingAddress) {
            //        $scope.entityInformation.EntityStreetAddress = {
            //            ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
            //                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            //            }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
            //            State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
            //        };
            //        isPageLoad = false;
            //        $scope.entityInformation.IsSameAsEntityMailingAddress = false;
            //    }

            //    if ($scope.entityInformation.EntityMailingAddress != null || $scope.entityInformation.EntityMailingAddress != undefined) {
            //        $scope.mailingAddressHasPOBOX = wacorpService.ispOBoxExist($scope.entityInformation.EntityMailingAddress.StreetAddress1) || wacorpService.ispOBoxExist($scope.entityInformation.EntityMailingAddress.StreetAddress2);
            //    }
            //}, true);

            $scope.selectedJurisdiction = function (items, selectedVal) {
                var result = "";
                angular.forEach(items, function (item) {
                    if (selectedVal == item.Key) {
                        result = item.Value;
                    }
                });
                return result;
            }

            $scope.FederalTaxTypesChangeDesc = function () {
                $scope.entityInformation.FederalTaxExemptText = $scope.selectedJurisdiction($scope.FederalTaxTypes, $scope.entityInformation.FederalTaxExemptId); // selectedJurisdiction method is available in this file only
            };

            //Get Federal Tax Types List
            $scope.getFederalTaxTypes = function () {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                lookupService.FederalTaxTypes(function (response) { $scope.FederalTaxTypes = response.data; });
            };

            $scope.getFederalTaxTypes(); // getFederalTaxTypes method is available in this file only

            //Copy Mailing Addresses to Street address on same check box checked
            $scope.CopyStreetFromMailing = function () {
                if ($scope.entityInformation.IsSameAsEntityMailingAddress)
                    if ($scope.entityInformation.EntityStreetAddress.ID == 0) {
                        if ($scope.entityInformation.EntityStreetAddress.County != "" && $scope.entityInformation.EntityStreetAddress.County != undefined)
                            var County = $scope.entityInformation.EntityStreetAddress.County;
                        var returnMail = $scope.entityInformation.EntityStreetAddress.IsAddressReturnedMail;
                        var streetAddressId = $scope.entityInformation.EntityStreetAddress.ID;
                        angular.copy($scope.entityInformation.EntityMailingAddress, $scope.entityInformation.EntityStreetAddress);
                        $scope.entityInformation.EntityStreetAddress.IsAddressReturnedMail = returnMail;
                        $scope.entityInformation.EntityStreetAddress.ID = streetAddressId;
                        if (County != "" && County != undefined)
                            $scope.entityInformation.EntityStreetAddress.County = County;
                    }

                        //$scope.entityInformation.EntityStreetAddress = $scope.entityInformation.EntityMailingAddress;
                    else
                        $scope.CopyMailingAddress(); // CopyMailingAddress method is available in this file only
                else {
                    if ($scope.entityInformation.EntityStreetAddress.ID == 0) {
                        $scope.entityInformation.EntityStreetAddress = {
                            ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                            }, FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                            State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                        };
                    }
                    else {
                        var isReturmMail = $scope.entityInformation.EntityStreetAddress.IsAddressReturnedMail;
                        $scope.entityInformation.EntityStreetAddress = {
                            ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                                FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                            }, FullAddress: null, FullAddressWithoutCounty: null, ID: $scope.entityInformation.EntityStreetAddress.ID, StreetAddress1: null, StreetAddress2: null, City: null,
                            State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                        };
                        $scope.entityInformation.EntityStreetAddress.IsAddressReturnedMail = isReturmMail;
                    }
                    //$scope.entityInformation.EntityStreetAddress = EntityStreetAddressForCopy;
                }
            };


            $scope.CopyMailingAddress = function () {
                $scope.entityInformation.EntityStreetAddress.Country = $scope.entityInformation.EntityMailingAddress.Country;
                $scope.entityInformation.EntityStreetAddress.StreetAddress1 = $scope.entityInformation.EntityMailingAddress.StreetAddress1;
                $scope.entityInformation.EntityStreetAddress.StreetAddress2 = $scope.entityInformation.EntityMailingAddress.StreetAddress2;
                $scope.entityInformation.EntityStreetAddress.Zip5 = $scope.entityInformation.EntityMailingAddress.Zip5;
                $scope.entityInformation.EntityStreetAddress.Zip4 = $scope.entityInformation.EntityMailingAddress.Zip4;
                $scope.entityInformation.EntityStreetAddress.City = $scope.entityInformation.EntityMailingAddress.City;
                $scope.entityInformation.EntityStreetAddress.PostalCode = $scope.entityInformation.EntityMailingAddress.PostalCode;
                $scope.entityInformation.EntityStreetAddress.OtherState = $scope.entityInformation.EntityMailingAddress.OtherState;
                $scope.entityInformation.EntityStreetAddress.State = $scope.entityInformation.EntityMailingAddress.State;
            };

            $scope.deleteAllFiles = function (flag, files) {
                if (!flag && files.length > constant.ZERO) {
                    //files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    if ($scope.entityInformation.UploadListOfAddresses.length > 0) {
                        // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            angular.forEach($scope.entityInformation.UploadListOfAddresses, function (value, data) {
                                if (value.BusinessFilingDocumentId > 0) {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.entityInformation.UploadListOfAddresses.indexOf(value);
                                    $scope.entityInformation.UploadListOfAddresses.splice(index, 1);
                                }
                            })
                            //wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files,
                            //function (response) {
                            $scope.entityInformation.IsUploadAddress = false;

                            //},
                            //);
                        },
                    function () {
                        $scope.entityInformation.IsUploadAddress = true;
                    });
                    }

                }
            };

            $scope.isForeignContact = function () {
                //$scope.entityInformation.AreaCode = '';
                $scope.entityInformation.CountryCode = $scope.entityInformation.IsForeignContact ? '' : '1';
            };

            //Email validation
            $scope.ValidateConfirmEmailAddress = function () {

                if (($scope.entityInformation.EntityConfirmEmailAddress).toUpperCase() != ($scope.entityInformation.EntityEmailAddress).toUpperCase()) {
                    // Folder Name: app Folder
                    // Alert Name: emailMatch method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.PrincipalOffice.emailMatch);
                    $('#txtemailFocus').focus();
                }
            };
            $scope.isDocumentLoaded = false;
            angular.element(document).ready(function () {
                $timeout(function () {
                    $scope.isDocumentLoaded = true;
                }, 4000);
            });

            // ACP PO BOX
            $scope.ChangeACP = function () {
                if ($scope.entityInformation.IsACP) {
                    $("#divACPConfirmation").modal('toggle');
                }
                else {
                    var returnMail = $scope.entityInformation.EntityStreetAddress.IsAddressReturnedMail;
                    var streetAddressId = $scope.entityInformation.EntityStreetAddress.ID;
                    var emptyAdd = {
                        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                            FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                        }, FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                        State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                    };
                    angular.copy(emptyAdd, $scope.entityInformation.EntityStreetAddress);
                    $scope.entityInformation.EntityStreetAddress.IsAddressReturnedMail = returnMail;
                    $scope.entityInformation.EntityStreetAddress.ID = streetAddressId;
                }
            };

            $scope.clickOk = function () {
                $("#divACPConfirmation").modal('toggle');
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                var poaddress = wacorpService.getpoboxAddress();
                var returnMail = $scope.entityInformation.EntityStreetAddress.IsAddressReturnedMail;
                var streetAddressId = $scope.entityInformation.EntityStreetAddress.ID;
                angular.copy(poaddress, $scope.entityInformation.EntityStreetAddress);
                $scope.entityInformation.EntityStreetAddress.IsAddressReturnedMail = returnMail;
                $scope.entityInformation.EntityStreetAddress.ID = streetAddressId;

            };

            $scope.cancel = function () {
                $scope.entityInformation.IsACP = false;
                $("#divACPConfirmation").modal('toggle');
            };

            //$scope.validatePoBox = function () {
            //    $scope.entityInformation.IsACP = wacorpService.validatePoBox($scope.entityInformation.EntityStreetAddress.StreetAddress1);
            //}

            //$timeout(function () {
            //    $scope.validatePoBox();
            //}, 1000);

            $scope.checkOrganizationEmail = function () {
                if ($scope.entityInfo.txtEntityEmailID.$viewValue == "" && ($scope.entityInformation.EntityEmailAddress == "" || $scope.entityInformation.EntityEmailAddress == null || $scope.entityInformation.EntityEmailAddress == undefined)) {
                    //Here we are calling the method which is declared in another controller(EmailOption.js)
                    $rootScope.$broadcast('onEmailEmpty');
                }
            };

            var checkIsSameAsStreetAddress = $scope.$on("checkIsSameAsStreetAddress", function (event) {
                if ($scope.entityInformation.IsSameAsEntityMailingAddress)
                {
                    $scope.entityInformation.IsSameAsEntityMailingAddress = false;
                    $scope.CopyStreetFromMailing();
                }
            });

            $scope.$on('$destroy', function () {
                checkIsSameAsStreetAddress();
            })

        },

    };


});
wacorpApp.directive('cftAddress', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CFTAddress/_CFTAddress.html',
        restrict: 'A',
        scope: {
            address: '=?address',
            isStreetAddress: '=?isStreetAddress',
            isCorrespAddress: '=?isCorrespAddress',
            showErrorMessage: '=?showErrorMessage',
            isCountyNotNeed: '=?isCountyNotNeed',
            enableCounty: '=?enableCounty',
            isSameasMailingAddress: '=?isSameasMailingAddress',
            isPoBoxValidationNeeded: '=?isPoBoxValidationNeeded',
            otherAddress: '=?otherAddress',
            isAcpAddress: '=?isAcpAddress',
            isHideShow: '=?isHideShow',
            zip5Validate: '=?zip5Validate',
            isOfficerAddress: '=?isOfficerAddress',
            isTrustBeneficiary: '=?isTrustBeneficiary',
            isFinPrep: '=?isFinPrep',
            isRafAddress: '=?isRafAddress',
            isValidate: '=?isValidate'
        },
        controller: function ($scope, lookupService, wacorpService, $timeout, $rootScope) {

            $scope.messages = messages;
            $scope.isHideShow = $scope.isHideShow || false;
            $scope.isValidate=$scope.isValidate||false;
            $scope.isValidAddressForZip = $scope.isValidAddressForZip || false;

            if ($scope.CFTAddress) {
                $scope.CFTAddress.ValidAddressCheck.$setValidity("text", true);
            }

            //if ($scope.otherAddress)
            //{
            //    $scope.$watch('otherAddress', function () {
            //        if ($scope.isSameasMailingAddress) {
            //            angular.extend($scope.address, $scope.otherAddress);
            //        }

            //    },true);
            //}



            var addressScope = {
                ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                FullAddress: null,FullAddressWithoutCounty:null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null, IsInValidAddress: false
            };

            //Set default values of scope variables
            angular.extend(addressScope, $scope.address);


            //$scope.address = $scope.address ? angular.extend(addressScope, $scope.address) : angular.copy(addressScope);
            $scope.isStreetAddress = $scope.isStreetAddress || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;

            //Prepped comma indicator in front of a object
            $scope.PrependComa = function (val, indicator) {
                return val == "" ? "" : indicator + val;
            };

            //Get Full Address
            $scope.$parent.fullAddress = function (addScope) {
                var fullAddres = (addScope.StreetAddress1 || "") + $scope.PrependComa((addScope.StreetAddress2 || ""), ', ')
                         + $scope.PrependComa((addScope.City || ""), ', ')
                         + ((addScope.Country == codes.USA || addScope.Country == 'CAN') ? $scope.PrependComa((addScope.State || ""), ', ') : $scope.PrependComa((addScope.OtherState || ""), ', '))
                         + ((addScope.Country == codes.USA) ? $scope.PrependComa((addScope.Zip5 || ""), ', ')
                         + $scope.PrependComa((addScope.Zip4 || ""), "-") : $scope.PrependComa((addScope.PostalCode || ""), ', '))
                         + $scope.PrependComa((addScope.Country || ""), ', ');
                return (fullAddres == null || fullAddres == '') ? ResultStatus.NONE : fullAddres;
            };

            $scope.Countries = [];
            $scope.States = [];
            $scope.Counties = [];

            //Get Countries List
            $scope.getCountries = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.countriesList(function (response) { $scope.Countries = response.data; });
            };

            //Get States List
            $scope.getStates = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.statesList(function (response) {
                    $scope.States = response.data;
                    $scope.initCFTLoadCountry(); // initCFTLoadCountry method is available in this file only.
                });
            };

            //Get Counties List
            $scope.getCounties = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.countiesList(function (response) { $scope.Counties = response.data; });
            };

            $scope.getCountries(); // getCountries method is available in this file only.
            $scope.getStates(); // getStates method is available in this file only.
            $scope.getCounties(); // getCounties method is available in this file only.

            $scope.isRunning = false;
            $scope.isAddressValidated = false;

            $scope.$watch('address', function () {
                $scope.isAddressValidated = false;
            }, true);


            //USPS Address Validation on city blur
            $scope.getValidAddress = function () {
                $scope.isValidAddressForZip = false;
                $scope.CFTAddress.ValidAddressCheck.$setValidity("text", true);
                if ($scope.isRunning || $scope.isAddressValidated) return false;

                if (isUSPSServiceValid && $scope.address.StreetAddress1 != "") {
                    var addressorg = {
                        Address1: $scope.address.StreetAddress1,
                        Address2: $scope.address.StreetAddress2,
                        City: $scope.address.City,
                        State: $scope.address.State,
                        Zip5: $scope.address.Zip5,
                        Zip4: $scope.address.Zip4,
                    };

                    var isvalusExist = (angular.isDefined(addressorg.Address1) && !angular.isNullorEmpty(addressorg.Address1)
                                      && angular.isDefined(addressorg.City) && !angular.isNullorEmpty(addressorg.City)
                                      && angular.isDefined(addressorg.State) && !angular.isNullorEmpty(addressorg.State))
                                      && (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5));

                    if ($scope.address.Country === codes.USA && isvalusExist) {
                        $scope.isRunning = true;
                        // getValidAddress method is available in constants.js
                        wacorpService.post(webservices.Common.getValidAddress, addressorg, function (response) {
                            var result = response.data;
                            if (result.HasErrors) {
                                if (result.ErrorDescription.trim() == "Invalid City." || result.ErrorDescription.trim() == "Invalid Zip Code.") {
                                    // Service Folder: services
                                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                                    wacorpService.alertDialog(result.ErrorDescription);
                                    $scope.address.Zip5 = '';
                                    $scope.address.Zip4 = '';
                                    //$scope.address.City = '';
                                }
                                else {
                                    if ($scope.isOfficerAddress) {
                                        //$scope.isValidAddressForZip = true;
                                        $scope.address.Zip4 = '';
                                        $scope.CFTAddress.ValidAddressCheck.$setValidity("text", false);
                                    }
                                    else {
                                        $scope.isValidAddressForZip = false;
                                        $scope.CFTAddress.ValidAddressCheck.$setValidity("text", true);
                                        //$scope.businessAddress.ValidAddressCheck.$setValidity("invalid", false);
                                    }
                                    if (result.ErrorDescription && result.ErrorDescription == "usps service is down") {
                                        $scope.isValidAddressForZip = true;
                                    }
                                    else {
                                        // Service Folder: services
                                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                                        wacorpService.alertDialog(result.ErrorDescription);
                                    }
                                }
                                $scope.address.IsInValidAddress = true;
                            }
                            else if (result.IsAddressModifed) {
                                if ($scope.isAgentAddress) {
                                    if (result.State == codes.WA) {
                                        // Folder Name: app Folder
                                        // Alert Name: invalidAddressData method is available in alertMessages.js
                                        wacorpService.confirmDialog($scope.messages.Address.invalidAddressData, function () {
                                            $scope.address.Zip5 = result.Zip5;
                                            $scope.address.Zip4 = result.Zip4;
                                            $scope.address.City = result.City;
                                            $scope.address.State = result.State;
                                            $scope.address.StreetAddress1 = result.Address1;

                                            $timeout(function () {
                                                $scope.isAddressValidated = true;
                                            }, 1000);
                                        });
                                    }
                                    else
                                        if (result.ErrorDescription && result.ErrorDescription == "usps service is down") {
                                            $scope.isAddressValidated = true;
                                        }
                                        else {
                                            // Folder Name: app Folder
                                            // Alert Name: invalidAddressData method is available in alertMessages.js
                                            wacorpService.alertDialog($scope.messages.Address.notWashingtonAddress);
                                        }
                                }
                                else {
                                    // Folder Name: app Folder
                                    // Alert Name: invalidAddressData method is available in alertMessages.js
                                    wacorpService.confirmDialog($scope.messages.Address.invalidAddressData, function () {
                                        $scope.address.Zip5 = result.Zip5;
                                        $scope.address.Zip4 = result.Zip4;
                                        $scope.address.City = result.City;
                                        $scope.address.State = result.State;
                                        $scope.address.StreetAddress1 = result.Address1;
                                        $scope.address.IsInValidAddress = false;

                                        $timeout(function () {
                                            $scope.isAddressValidated = true;
                                        }, 1000);
                                    });
                                }

                            }
                            else {
                                if (result.ErrorDescription && result.ErrorDescription == "usps service is down") {
                                    $scope.address.IsValidAddress = true;
                                }
                                else {
                                    $scope.address.Zip4 = result.Zip4;
                                    $scope.address.IsInValidAddress = false;
                                }

                                $timeout(function () {
                                    $scope.isAddressValidated = true;
                                }, 1000);
                            }
                            $timeout(function () {
                                $scope.isRunning = false;
                            }, 1000);

                        }, function (response) {
                            $scope.isRunning = false;
                        });
                    }
                }
            }

            //Get City State on Zip5 blur
            $scope.getCityStateAddress = function () {
                if ($scope.isRunning || $scope.isAddressValidated) return false;
                var addressorg = {
                    Address1: $scope.address.StreetAddress1,
                    Address2: $scope.address.StreetAddress2,
                    City: $scope.address.City,
                    State: $scope.address.State,
                    Zip5: $scope.address.Zip5,
                    Zip4: $scope.address.Zip4,
                };

                var isvalusExist = (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5) && addressorg.Zip5.length==5);

                if ($scope.address.Zip5 == undefined) {
                    $scope.address.City = '';
                    $scope.address.Zip4 = '';
                    $scope.address.invalidZip = true;
                }

                if (isvalusExist) {
                    // getCityStateZip method is available in constants.js
                    wacorpService.post(webservices.Common.getCityStateZip, addressorg, function (response) {
                        var result = response.data;
                        if (result.HasErrors) {
                            // Folder Name: app Folder
                            // Alert Name: validZipExtension method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.Address.validZipExtension);
                            $scope.address.Zip5 = '';
                            $scope.address.Zip4 = '';
                            $scope.address.City = '';
                            $scope.address.State = 'WA';
                            $scope.address.IsInValidAddress = true;
                        }
                        else if ($scope.isAgentAddress) {
                            if (result.State == codes.WA) {
                                $scope.address.Zip5 = result.Zip5;
                                $scope.address.Zip4 = result.Zip4;
                                $scope.address.City = result.City;
                                $scope.address.State = result.State;
                                $scope.address.StreetAddress1 = result.Address1;
                                $scope.getValidAddress(); // getValidAddress method is available in this file only.
                            }
                            else
                                if (result.ErrorDescription && result.ErrorDescription.toLowerCase() == "usps service is down") {
                                    $scope.address.invalidZip = false;
                                    $scope.isAddressValidated = true;
                                }
                                else {
                                    // Folder Name: app Folder
                                    // Alert Name: notWashingtonAddress method is available in alertMessages.js
                                    wacorpService.alertDialog($scope.messages.Address.notWashingtonAddress);
                                }

                        }
                        else {
                            $scope.address.Zip5 = result.Zip5;
                            $scope.address.Zip4 = result.Zip4;
                            $scope.address.City = result.City;
                            $scope.address.State = result.State;
                            $scope.address.StreetAddress1 = result.Address1;
                            if (result.ErrorDescription && result.ErrorDescription.toLowerCase() == "usps service is down") {
                                $scope.address.invalidZip = false;
                                $scope.isAddressValidated = true;
                            }
                            else {
                                $scope.getValidAddress(); // getValidAddress method is available in this file only.
                            }

                        }
                        if (result.ErrorDescription && result.ErrorDescription.toLowerCase() == "usps service is down") {
                            $scope.address.invalidZip = false;
                            $scope.isAddressValidated = true;
                        }
                        else {
                            $scope.validateMailingAddress(); // validateMailingAddress method is available in this file only.
                        }
                    }, function (response) { });
                }

            }

            $scope.$watch('address', function () {
                angular.forEach($scope.Counties, function (county) {
                    if (county.Key == $scope.address.County)
                        $scope.address.CountyName = county.Value;
                });
                if ($scope.address.Country == 'USA') {
                    $scope.address.PostalCode = '';
                }
                //console.log($scope.address.CountyName);
                if (angular.isNullorEmpty($scope.address))
                    return;
                else {
                    var fullAddr = ($scope.address.StreetAddress1 || "") + PrependComa(($scope.address.StreetAddress2 || ""), ', ')
                                + (($scope.address.Country == codes.USA && $scope.address.State == "WA") ? PrependComa(($scope.address.CountyName || ""), ', ') : "")
                                + PrependComa(($scope.address.City || ""), ', ')
                                + (($scope.address.Country == codes.USA) ? PrependComa(($scope.address.State || ""), ', ') : ($scope.address.Country == 'CAN' ? PrependComa(($scope.address.State || ""), ', ') : PrependComa(($scope.address.OtherState || ""), ', ')))
                                //+ (($scope.address.Country == codes.USA && $scope.address.State == codes.WA) ? PrependComa(($scope.address.CountyName || ""), ', ') : "")
                                + (($scope.address.Country == codes.USA) ? PrependComa(($scope.address.Zip5 || ""), ', ')
                                + PrependComa(($scope.address.Zip4 || ""), "-") : PrependComa(($scope.address.PostalCode || ""), ', '))
                                + PrependComa(($scope.address.Country || ""), ', ');
                    $scope.address.FullAddress = (fullAddr == null || fullAddr == '') ? '' : fullAddr;

                    //Full Address Without County For Same as Address CHeckbox
                    var fullAddrWithoutCounty = ($scope.address.StreetAddress1 || "") + PrependComa(($scope.address.StreetAddress2 || ""), ', ')
                                + PrependComa(($scope.address.City || ""), ', ')
                                + (($scope.address.Country == codes.USA) ? PrependComa(($scope.address.State || ""), ', ') : ($scope.address.Country == 'CAN' ? PrependComa(($scope.address.State || ""), ', ') : PrependComa(($scope.address.OtherState || ""), ', ')))
                                //+ (($scope.address.Country == codes.USA && $scope.address.State == codes.WA) ? PrependComa(($scope.address.CountyName || ""), ', ') : "")
                                + (($scope.address.Country == codes.USA) ? PrependComa(($scope.address.Zip5 || ""), ', ')
                                + PrependComa(($scope.address.Zip4 || ""), "-") : PrependComa(($scope.address.PostalCode || ""), ', '));
                    $scope.address.FullAddressWithoutCounty = (fullAddrWithoutCounty == null || fullAddrWithoutCounty == '') ? '' : fullAddrWithoutCounty;
                }
            }, true);

            var PrependComa = function (val, indicator) {
                return val == "" ? "" : indicator + val;
            };

            /* New chagnes for Canada */

            $scope.requiredStatesForCountry = ["USA", "CAN"];
            var canadaStates = ["AB", "BC", "MB", "NB", "NL", "NS", "NT", "NU", "ON", "PE", "QC", "SK", "YT"];
            $scope.statesArray = [];

            $scope.changeState = function () {
                if ($scope.isOfficerAddress) {
                    $rootScope.$broadcast('onMailingAddressChanged');
                }
                $scope.clearStreetAddress();// to clear street Address when mailing address is changed
            };

            $scope.changeCountry = function () {
                var $country = angular.element(event.target);
                if ($scope.requiredStatesForCountry.indexOf($country.val()) > -1) {

                    if ($scope.statesArray.length == 0)
                        angular.copy($scope.States, $scope.statesArray);

                    $scope.States.length = 0;

                    angular.forEach($scope.statesArray, function (data, index) {
                        if (canadaStates.indexOf(data.Key) > -1 && $country.val() == "CAN") {
                            $scope.States.push(data);
                        }
                        else if (canadaStates.indexOf(data.Key) == -1 && $country.val() == "USA") {
                            $scope.States.push(data);
                        }
                    });

                    // set default state
                    $timeout(function () {
                        //if ($scope.address.State == "" && $country.val() == "USA")
                        if ((canadaStates.indexOf($scope.address.State) > -1 || $scope.address.State == "") && $country.val() == "USA")
                            $scope.address.State = "WA";
                        else if ($country.val() == "CAN")
                            //$scope.address.State = $scope.address.State || "";
                            $scope.address.State = "";
                    }, 200);
                }

                //Retrun Address Mail Issue Fix
                //if ($scope.isCorrespAddress != undefined && $scope.isCorrespAddress) {
                //    $scope.isStreetAddress = true;
                //    $scope.showErrorMessage = false;
                //    $scope.zip5Validate = false;

                //    $scope.address.StreetAddress1 = "";
                //    $scope.address.StreetAddress2 = "";
                //    $scope.address.City = "";
                //    $scope.address.Zip5 = "";
                //    $scope.address.Zip4 = "";
                //    $scope.address.PostalCode = "";
                //    $scope.address.OtherState = ""
                //}

                if ($scope.isOfficerAddress) {
                    $rootScope.$broadcast('onMailingAddressChanged');
                }
                $scope.clearStreetAddress();// to clear street Address when mailing address is changed
            }

            $scope.initCFTLoadCountry = function () {
                if ($scope.requiredStatesForCountry.indexOf($scope.address.Country) > -1) {

                    if ($scope.statesArray.length == 0)
                        angular.copy($scope.States, $scope.statesArray);

                    $scope.States.length = 0;

                    angular.forEach($scope.statesArray, function (data, index) {
                        if (canadaStates.indexOf(data.Key) > -1 && $scope.address.Country == "CAN") {
                            $scope.States.push(data);
                        }
                        else if (canadaStates.indexOf(data.Key) == -1 && $scope.address.Country == "USA") {
                            $scope.States.push(data);
                        }
                    });

                    // set default state
                    $timeout(function () {
                        if ((canadaStates.indexOf($scope.address.State) > -1 || $scope.address.State == "") && $scope.address.Country == "USA")
                            $scope.address.State = "WA";
                        else if ($scope.address.Country == "CAN")
                            $scope.address.State = $scope.address.State || "";
                    }, 200);
                }
            }

            $scope.$watch("address.StreetAddress1", function (newValue, oldValue) {
                if ($scope.isPoBoxValidationNeeded && $scope.address)
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.isAcpAddress = wacorpService.validatePoBoxAddress($scope.address);
            });

            $scope.validatePoBox = function () {
                if ($scope.isPoBoxValidationNeeded && $scope.address)
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.isAcpAddress = wacorpService.validatePoBoxAddress($scope.address);
            }

            $scope.validatePoBox();

            $scope.$watch('address.Country', function () {
                $scope.initCFTLoadCountry(); // initCFTLoadCountry method is available in this file only.
            });

            $scope.validateMailingAddress = function (value,e) {
                  
                if ($scope.isFinPrep!=undefined  && !$scope.isFinPrep) {
                    $scope.address.invalidZip = false;
                    if (value && !value.flag && value != undefined) {
                        if (value && value.type == "Zip5") {
                            $scope.address.invalidZip = false;
                            if ($scope.address.Zip5 == undefined) {
                                $scope.address.City = '';
                                $scope.address.Zip4 = '';
                                $scope.address.invalidZip = true;
                            }
                            else {
                                $scope.address.City = angular.copy($scope.address.City);
                                $scope.address.Zip4 = angular.copy($scope.address.Zip4);
                                $scope.address.Zip5 = angular.copy($scope.address.Zip5);
                                $scope.address.invalidZip = false;
                            }
                        }

                        else if (value && value.type == "address1") {
                            if (angular.isUndefined($scope.address.Zip5)) {
                                $scope.address.invalidZip = true
                            }
                            if ($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") {
                                $scope.address.invalidZip = false;
                                $scope.address.Zip5 = '';
                                $scope.address.Zip4 = '';
                                $scope.address.City = '';
                                $scope.address.StreetAddress2 = '';
                                $scope.address.PostalCode = '';
                            }
                            if ($scope.address.StreetAddress1 && $scope.address.Zip5 && $scope.address.Zip4) {
                                $scope.address.Zip4 = "";
                                $scope.isAddressValidated = false;
                            }
                        }

                        $scope.address.StreetAddress1 = $scope.address.StreetAddress1 ? angular.copy($scope.address.StreetAddress1.trim()) : (($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") ? $scope.address.StreetAddress1 = null : $scope.address.StreetAddress1);

                        //clear Zip4 values if Street address is changed
                        if ($scope.address.StreetAddress1 && $scope.address.Zip5 && $scope.address.Zip4) {
                            $scope.address.Zip4 = "";
                            $scope.isAddressValidated = false;
                        }

                        //This section is to validate Filing Correspondence Address
                        if ($scope.isRafAddress != undefined && $scope.isRafAddress)//new flag for CorrespondenceAddress
                        {
                            if ($scope.CFTAddress.Zip5 != undefined && $scope.CFTAddress.Zip5 != "" && $scope.CFTAddress.Zip5.$viewValue != "")
                                $scope.address.Zip5 = $scope.CFTAddress.Zip5.$viewValue;
                            if ($scope.address.StreetAddress1 || $scope.address.Zip5) {
                                $scope.isStreetAddress = false;
                                $scope.showErrorMessage = true;
                                $scope.zip5Validate = true;
                            }
                            else {
                                $scope.isStreetAddress = true;
                                $scope.showErrorMessage = false;
                                $scope.zip5Validate = false;
                                //$scope.isCorrespAddress = true;
                            }
                            if (e.key == "Del" || e.key == "Delete") {
                                $scope.clearCorrpAddress();
                            }
                            else if (e.key == "Backspace" && ($scope.CFTAddress != undefined && $scope.CFTAddress.Zip5.$viewValue != undefined && $scope.CFTAddress.Zip5.$viewValue.length == 0)) {
                                $scope.clearCorrpAddress();
                            }
                        }
                        else if ($scope.isCorrespAddress != undefined && $scope.isCorrespAddress && $scope.isCorrespAddress != undefined) {
                            if ($scope.CFTAddress.Zip5 != undefined && $scope.CFTAddress.Zip5 != "" && $scope.CFTAddress.Zip5.$viewValue != "")
                                $scope.address.Zip5 = $scope.CFTAddress.Zip5.$viewValue;
                            if ($scope.address.StreetAddress1 || $scope.address.Zip5) {
                                $scope.isStreetAddress = false;
                                $scope.showErrorMessage = true;
                                $scope.zip5Validate = true;
                            }
                            else {
                                $scope.isStreetAddress = true;
                                $scope.showErrorMessage = false;
                                $scope.zip5Validate = false;
                                //$scope.isCorrespAddress = true;
                            }
                            if (e.key == "Del" || e.key == "Delete")
                            {
                                $scope.clearCorrpAddress();
                            }
                            else if (e.key == "Backspace" && ($scope.CFTAddress != undefined && $scope.CFTAddress.Zip5.$viewValue != undefined && $scope.CFTAddress.Zip5.$viewValue.length == 0))
                            {
                                $scope.clearCorrpAddress();
                            }
                        }
                    }
                    else if ((value && value.isCorrespAddress)) {
                        $scope.address.StreetAddress1 = $scope.address.StreetAddress1 ? angular.copy($scope.address.StreetAddress1.trim()) : (($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") ? $scope.address.StreetAddress1 = null : $scope.address.StreetAddress1);
                        //clear Zip4 values if Street address is changed
                        if ($scope.address.StreetAddress1 && $scope.address.Zip5 && $scope.address.Zip4) {
                            $scope.address.Zip4 = "";
                            $scope.isAddressValidated = false;
                        }
                        //This section is to validate Filing Correspondence Address
                        if ($scope.isRafAddress != undefined && $scope.isRafAddress)//new flag for CorrespondenceAddress
                        {
                            if ($scope.CFTAddress.Zip5 != undefined && $scope.CFTAddress.Zip5 != "" && $scope.CFTAddress.Zip5.$viewValue != "")
                                $scope.address.Zip5 = $scope.CFTAddress.Zip5.$viewValue;
                            if ($scope.address.StreetAddress1 || $scope.address.Zip5) {
                                $scope.isStreetAddress = false;
                                $scope.showErrorMessage = true;
                                $scope.zip5Validate = true;
                            }
                            else {
                                $scope.isStreetAddress = true;
                                $scope.showErrorMessage = false;
                                $scope.zip5Validate = false;
                                //$scope.isCorrespAddress = true;
                            }
                            if (e.key == "Del" || e.key == "Delete") {
                                $scope.clearCorrpAddress();
                            }
                            else if (e.key == "Backspace" && ($scope.CFTAddress != undefined && $scope.CFTAddress.Zip5.$viewValue != undefined && $scope.CFTAddress.Zip5.$viewValue.length == 0)) {
                                $scope.clearCorrpAddress();
                            }
                        }
                        else if ($scope.isCorrespAddress != undefined && $scope.isCorrespAddress && $scope.isCorrespAddress != undefined) {
                            if ($scope.CFTAddress.Zip5 != undefined && $scope.CFTAddress.Zip5 != "" && $scope.CFTAddress.Zip5.$viewValue != "")
                                $scope.address.Zip5 = $scope.CFTAddress.Zip5.$viewValue;
                            if ($scope.address.StreetAddress1 || $scope.address.Zip5) {
                                $scope.isStreetAddress = false;
                                $scope.showErrorMessage = true;
                                $scope.zip5Validate = true;
                            }
                            else {
                                $scope.isStreetAddress = true;
                                $scope.showErrorMessage = false;
                                $scope.zip5Validate = false;
                                //$scope.isCorrespAddress = true;
                            }
                            if (e.key == "Del" || e.key == "Delete") {
                                $scope.clearCorrpAddress();
                            }
                            else if (e.key == "Backspace" && ($scope.CFTAddress != undefined && $scope.CFTAddress.Zip5.$viewValue != undefined && $scope.CFTAddress.Zip5.$viewValue.length == 0)) {
                                $scope.clearCorrpAddress();
                            }
                        }
                    }
                    else if (value && value.flag) {
                        var data = $scope.CFTAddress.StreetAddress1.$viewValue;
                        var test = false;
                        if (data) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            test = wacorpService.validatePoBox(data);
                        }

                        if (!test) {
                            if (angular.isUndefined($scope.address.Zip5)) {
                                $scope.address.invalidZip = true
                            }

                            $scope.address.StreetAddress1 = $scope.address.StreetAddress1 ? angular.copy($scope.address.StreetAddress1.trim()) : (($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") ? $scope.address.StreetAddress1 = null : $scope.address.StreetAddress1);

                            if ($scope.address.StreetAddress1 == undefined || $scope.address.StreetAddress1 == "") {
                                $scope.address.invalidZip = false;
                                $scope.address.Zip5 = '';
                                $scope.address.Zip4 = '';
                                $scope.address.City = '';
                            }
                            if ($scope.address.StreetAddress1 && $scope.address.Zip5 && $scope.address.Zip4) {
                                $scope.address.Zip4 = "";
                                $scope.isAddressValidated = false;
                            }
                        }
                    }
                }
            }

            //Here we are declaring the Method which will be calling in _newTrustBeneficaries
            var trustClearBtnClicked = $scope.$on("onTrustBeneficiaryClearClicked", function (event) {
                if (event.currentScope.isTrustBeneficiary !=undefined && event.currentScope.isTrustBeneficiary != null && event.currentScope.isTrustBeneficiary) {
                    var obj = {};
                    obj.type = "address1";
                    obj.flag = false;
                    obj.isCorrespAddress = true;
                    $scope.isCorrespAddress = true;
                    $scope.address = addressScope;
                    $scope.validateMailingAddress(obj); // This method is available in this file only.
                }
            });

            $scope.$on('$destroy', function () {
                trustClearBtnClicked(); // trustClearBtnClicked method is available in this file only.
            });

            //validate for city textbox only
            $scope.validateCityAddress = function (e) {
                 
                $scope.address.invalidZip = false;
                if ($scope.address.City == "") {
                    if ($scope.address.Zip5 == undefined) {
                        $scope.address.invalidZip = true
                    }
                }
                $scope.address.City = $scope.address.City ? angular.copy($scope.address.City.trim()) : (($scope.address.City == undefined || $scope.address.City == "") ? $scope.address.City = null : $scope.address.City);

                if (!$scope.address.StreetAddress1 && !$scope.address.Zip5) {
                    $scope.address.Zip4 = "";
                }

                if ($scope.isCorrespAddress != undefined && $scope.isRafAddress != undefined && $scope.isCorrespAddress && $scope.isRafAddress) {
                    if ($scope.address.StreetAddress1 || $scope.address.City || $scope.address.Zip5) {
                        $scope.isStreetAddress = false;
                        $scope.showErrorMessage = true;
                        $scope.zip5Validate = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showErrorMessage = false;
                        $scope.zip5Validate = false;
                    }

                    if (e.key == "Del" || e.key == "Delete") {
                        $scope.clearCorrpAddress();
                    }
                    else if (e.key == "Backspace" && ($scope.CFTAddress != undefined && $scope.CFTAddress.City.$viewValue != undefined && $scope.CFTAddress.City.$viewValue.length == 0))
                    {
                        $scope.clearCorrpAddress();
                    }
                }

            }

            $scope.clearCorrpAddress = function()
            {
                $scope.address.Zip5 = null;
                $scope.address.Zip4 = '';
                $scope.address.StreetAddress1 = "";
                $scope.address.StreetAddress2 = '';
                $scope.address.PostalCode = '';
                $scope.address.OtherState = '';
                $scope.address.City = '';

                $scope.isStreetAddress = true;
                $scope.showErrorMessage = false;
                $scope.zip5Validate = false;
            }

            angular.element(function () {
                if ($scope.isFinPrep!=undefined && !$scope.isFinPrep) {
                    if ($scope.address != null && $scope.address != undefined && ($scope.address.StreetAddress1 || $scope.address.Zip5)) {
                        $scope.isStreetAddress = false;
                        $scope.showErrorMessage = true;
                        $scope.zip5Validate = true;
                    }
                }
                if ($scope.isCorrespAddress != undefined && $scope.isRafAddress != undefined && $scope.isCorrespAddress && $scope.isRafAddress)
                {
                    if ($scope.address.StreetAddress1 || $scope.address.City || $scope.address.Zip5) {
                        $scope.isStreetAddress = false;
                        $scope.showErrorMessage = false;
                        $scope.zip5Validate = true;
                    }
                    else {
                        $scope.isStreetAddress = true;
                        $scope.showErrorMessage = false;
                        $scope.zip5Validate = false;
                    }
                }
            });
            $scope.clearStreetAddress = function () {
                if ($scope.isValidate != undefined && $scope.isValidate)
                {
                    $rootScope.$broadcast("checkIsSameAsStreetAddress");
                }
            }
        },
    };
});

wacorpApp.directive('cftEntityName', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CFTEntityName/_CFTEntityName.html',
        restrict: 'A',
        scope: {
            entity: '=?entity',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
            entityNameValid: '=?entityNameValid'
        },
        controller: function ($scope, wacorpService) {
            $scope.helptext = helptext;
            $scope.messages = messages;
            $scope.entity = $scope.entity || {};
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.entityNameValid = $scope.entityNameValid || false;
            $scope.entity.oldBusinessName = angular.copy($scope.entity.EntityName) || '';
            $scope.validateBusinessName = false;

            //$scope.isBusinessNameChanged = false;

            $scope.isBusinessNameAvailableCheck = function () {
                if ($scope.entity.EntityName != null && $scope.entity.EntityName != "") {
                    if ($scope.entity.oldBusinessName != $scope.entity.EntityName)
                        $scope.entity.isBusinessNameAvailable = false;
                    if ($scope.availableBusinessCount() > constant.ZERO)
                        $scope.entity.isBusinessNameAvailable = true;
                    //if (($scope.entity.oldBusinessName != $scope.entity.EntityName) || $scope.availableBusinessCount() > constant.ZERO)
                    //    $scope.entity.isBusinessNameAvailable = false;
                    if ($scope.entity.oldBusinessName == $scope.entity.EntityName)
                        $scope.entity.isBusinessNameAvailable = true;
                    //if ($scope.entity.businessNames != null || $scope.entity.businessNames != undefined) {
                    //    $scope.entity.businessNames.filter(function (data) {
                    //        if (data.BusinessName == $scope.entity.EntityName && data) {
                    //            $scope.entity.isBusinessNameAvailable = false;
                    //        }
                    //    });
                    //}
                }
                else {
                    $scope.entity.isBusinessNameAvailable = true;
                }
            };

            $scope.searchBusinessNames = function (EntityName) {
                $scope.entity.isBusinessNameAvailable = true;
                $scope.entity.oldBusinessName = $scope.entity.EntityName;
                $scope.validateBusinessName = true;
                if ($scope[EntityName].txtBusinessName.$valid) {
                    //$scope.validateBusinessName = false;
                    var config = {
                        //params: { businessName: $scope.entity.EntityName, businessId: $scope.entity.CFTId }
                        params: { businessName: $scope.entity.EntityName, businessTypeID: $scope.entity.BusinessTypeID, businessId: $scope.entity.CFTId }
                    };
                    // getBusinessNames method is available in constants.js
                    wacorpService.get(webservices.CFT.getBusinessNames, config, function (response) {
                        $scope.entity.businessNames = response.data;
                        $scope.entity.isBusinessNameAvailable = $scope.availableBusinessCount() > 0;
                        if ($scope.entity.isBusinessNameAvailable) {
                            $scope.validateBusinessName = false;
                            $scope.entityNameValid = false;
                        }
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
            };

            //New code to Check Businessname count 
            // check business count availability
            $scope.availableBusinessCount = function () {
                if ($scope.entity.businessNames == undefined || $scope.entity.businessNames == null) {
                    return 0;
                }
                else if ($scope.entity.oldBusinessName != $scope.entity.EntityName) {
                    return 0;
                }
                else {
                    var availableBusinesscount = 0;
                    for (var index in $scope.entity.businessNames) {
                        //if ($scope.entity.businessNames[index].AvailableStatus == "Available") {
                        if ($scope.entity.businessNames[index].ID == -1 && $scope.entity.businessNames[index].Status == "Available") {
                            availableBusinesscount++;
                            break;
                        }
                    }
                    return availableBusinesscount;
                }
            };

            $scope.$watch('entity.EntityName', function (nval, oval) {
                if ((nval != null && nval != "") && (oval != null && oval != "") && (typeof (nval && oval) != typeof (undefined)) && (angular.lowercase(nval) != angular.lowercase(oval))) {
                    $scope.entity.OldEntityName = oval;
                    $scope.entity.NewEntityName = nval;
                    //$scope.entity.isBusinessNameChanged = true;
                    $scope.validateBusinessName = true;
                    $scope.isBusinessNameAvailableCheck(); // isBusinessNameAvailableCheck method is available in this file only.
                }
                if ($scope.entity.IsOrgNameExists) {
                    $scope.validateBusinessName = false;
                    $scope.entityNameValid = false;
                }
                //else {
                //    $scope.validateBusinessName = true;
                //}
                //$scope.entity.oldBusinessName = oval;
                //$scope.isBusinessNameAvailableCheck();
            });
        },
    };
});
wacorpApp.directive('fundraiserLegalInfo', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/LegalInfo/_FundraiserLegalInfo.html',
        restrict: 'A',
        scope: {
            fundraiserLegalInfoData: '=?fundraiserLegalInfoData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
            isUpdated: '=?isUpdated'
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.LegalInfoAttachDocuments = $scope.LegalInfoAttachDocuments || [];
            $scope.addbuttonName = "Add Legal Information";

            var fundraiserLegalInfoScope = {
                LegalInfoEntityName: '', FirstName: '', Title: '', LastName: '', EntityRepresentativeFirstName: '', EntityRepresentativeLastName: '', SequenceNo: "", LegalInfoTypeID: "I", IsAnyLegalActions: false, isUploadDocument: false,
                Court: '', Case: '', TitleofLegalAction: '', LegalActionDate: null,
                LegalInfoAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                LegalInfoAttachDocuments: [], isUploadDocument: false
            };

            $scope.fundraiserLegalInfoData = $scope.fundraiserLegalInfoData ? angular.extend(fundraiserLegalInfoScope, $scope.fundraiserLegalInfoData) : angular.copy(fundraiserLegalInfoScope);

            $scope.$watch('fundraiserLegalInfoData', function () {
                //$scope.fundraiserLegalInfoData.isUploadDocument = angular.isNullorEmpty($scope.fundraiserLegalInfoData.isUploadDocument) ? true : $scope.fundraiserLegalInfoData.isUploadDocument;
                $scope.fundraiserLegalInfoData.isUploadDocument = $scope.fundraiserLegalInfoData.LegalInfoAttachDocuments.length > 0 ? true : false;
            });

            //Get User Login details during MySelf Select
            $scope.getUserLoginDetails = function (mySelfLegal) {
                var currentTypeID = angular.copy($scope.fundraiserLegalInfoData.LegalInfoTypeID);
                if (mySelfLegal) {
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        $scope.fundraiserLegalInfoData.LegalInfoTypeID = angular.copy($scope.newUser.Agent.AgentType);
                        $scope.fundraiserLegalInfoData.LegalInfoEntityName = angular.copy($scope.newUser.EntityName);
                        $scope.fundraiserLegalInfoData.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.fundraiserLegalInfoData.LastName = angular.copy($scope.newUser.LastName);
                        $scope.fundraiserLegalInfoData.EntityRepresentativeFirstName = angular.copy($scope.newUser.EntityRepresentativeFirstName);
                        $scope.fundraiserLegalInfoData.EntityRepresentativeLastName = angular.copy($scope.newUser.EntityRepresentativeLastName);
                        $scope.fundraiserLegalInfoData.Title = angular.copy($scope.newUser.Title);
                        $scope.fundraiserLegalInfoData.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.fundraiserLegalInfoData.ConfirmEmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.fundraiserLegalInfoData.LegalInfoPhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        $scope.fundraiserLegalInfoData.LegalInfoAddress = angular.copy($scope.newUser.Address);
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    $scope.fundraiserLegalInfoData = angular.copy(fundraiserLegalInfoScope);
                    $scope.fundraiserLegalInfoData.LegalInfoTypeID = currentTypeID;
                }
            };


            $scope.legalInfoSelection = function (value) {
                if (value == "I") {
                    $scope.fundraiserLegalInfoData.FirstName = '';
                    $scope.fundraiserLegalInfoData.LastName = '';
                    $scope.fundraiserLegalInfoData.Title = '';
                }
                else {
                    $scope.fundraiserLegalInfoData.EntityRepresentativeFirstName = '';
                    $scope.fundraiserLegalInfoData.EntityRepresentativeLastName = '';
                    $scope.fundraiserLegalInfoData.Title = '';

                }
                $scope.fundraiserLegalInfoData.LegalInfoEntityName = '';
            };

            $scope.AddLegalAction = function myfunction(fundraiserLegalInfo) {

                //if ($scope.fundraiserLegalInfoScope.SequenceNo!=0) {
                angular.forEach(fundraiserLegalInfoData.LegalInfoList, function (leagl) {

                    if (leagl.SequenceNo == $scope.fundraiserLegalInfoScope.SequenceNo) {
                        //$scope.cftOfficer.OfficerAddress.FullAddress = wacorpService.cftFullAddressService($scope.cftOfficer.OfficerAddress);
                        angular.copy($scope.fundraiserLegalInfoScope, leagl);
                    }
                });
                //}
            };

            //Delete attachments
            $scope.deleteAllFiles = function (files) {
                if (files.length > constant.ZERO) {
                    //files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js 
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        // deleteAllUploadedFiles method is available in constants.js
                        wacorpService.post(webservices.Common.deleteAllUploadedFiles, files,
                            function (response) {
                                $scope.fundraiserLegalInfoData.LegalInfoAttachDocuments = [];
                            },
                            function (response) {
                            }
                        );
                    },
                    function () {
                        $scope.fundraiserLegalInfoData.isUploadDocument = false;
                    });
                }
            };
        },
    };
});

wacorpApp.directive('legalActions', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/LegalActions/_LegalActions.html',
        restrict: 'A',
        scope: {
            legalInfoEntity: '=?legalInfoEntity',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope, $location) {
            $scope.helptext = helptext;
            $scope.messages = messages;
         //   $scope.legalInfoEntityList = $scope.legalInfoEntityList || [];
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add Legal Information";
            $scope.hasValues = false;
            $scope.LegalCount = false;
            $scope.LegalUploadCount = false;
            $scope.legalInfo = {
                LegalInfoId:'',LegalInfoEntityName: '', FirstName: '', Title: '', LastName: '',SequenceNo:null, LegalInfoTypeID: "I", IsAnyLegalActions: false, isUploadDocument: false,
                Court: '', Case: '', TitleofLegalAction: '', LegalActionDate: null, LegalInfoAttachDocuments: [],LegalActionsUploads:[]
            };
           
            $scope.hasValues = $scope.legalInfo.Court != '' || $scope.legalInfo.Case != '' ||
                               $scope.legalInfo.TitleofLegalAction != '' || $scope.legalInfo.legalActionData != null;

            var legalInfoScopeData = {
                LegalInfoId:'',LegalInfoEntityName: '', FirstName: '', Title: '', LastName: '', SequenceNo: null, LegalInfoTypeID: "I", IsAnyLegalActions: false, isUploadDocument: false,
                Court: '', Case: '', TitleofLegalAction: '', LegalActionDate: null, LegalInfoAttachDocuments: [], LegalActionsUploads: []
            };


            $scope.$watch('legalInfo', function () {
                //$scope.fundraiserLegalInfoData.isUploadDocument = angular.isNullorEmpty($scope.fundraiserLegalInfoData.isUploadDocument) ? true : $scope.fundraiserLegalInfoData.isUploadDocument;
                $scope.legalInfo.isUploadDocument = $scope.legalInfo.LegalActionsUploads.length > 0 ? true : false;
                //$scope.LegalUploadCount = 0;
                
                //$scope.LegalCount = 0;
                //angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (legalInfoItem) {
                //    if (legalInfoItem.Status != "D") {
                //        $scope.LegalCount++;
                //    }
                //});
                //angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (value, data) {
                //    if (value.Status != "D")
                //    {
                //        $scope.LegalCount = false;
                //    }
                //    else {
                //        $scope.LegalCount = true;
                //    }
                //});

                //angular.forEach($scope.legalInfoEntity.LegalActionsUploads, function (value, data) {
                //    if (value.Status != "D") {
                //        $scope.LegalUploadCount = false;
                //    }
                //    else {
                //        $scope.LegalUploadCount = true;
                //    }
                //});
            });

            //Reset the legal action
            $scope.resetLegalAction = function () {
                $scope.legalInfo = angular.copy(legalInfoScopeData);
               // $scope.ValidateErrorMessage = false;
                $scope.addbuttonName = "Add Legal Information";
            };

            //Add Legal Action data
            $scope.AddLeglAction = function (legalActionsForm) {
                 
                $scope.ValidateErrorMessage = true;
                if ($scope[legalActionsForm].$valid) {
                    $scope.ValidateErrorMessage = false;
                    if ($scope.legalInfo.SequenceNo!=null && $scope.legalInfo.SequenceNo!=''&& $scope.legalInfo.SequenceNo != 0) {
                        angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (legalInfoItem) {
                            if (legalInfoItem.SequenceNo == $scope.legalInfo.SequenceNo) {
                                angular.copy($scope.legalInfo, legalInfoItem);
                                ////////////////Cross check.
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (legalInfoItem) {
                            if (maxId == constant.ZERO || legalInfoItem.SequenceNo > maxId)
                                maxId = legalInfoItem.SequenceNo;
                        });
                        $scope.legalInfo.SequenceNo = ++maxId;
                        $scope.legalInfo.Status = principalStatus.INSERT;
                        $scope.legalInfoEntity.LegalInfoEntityList.push($scope.legalInfo);
                    }
                    $scope.resetLegalAction(); // resetLegalAction method is available in this file only
                }
                 
            };

            //Edit fundraiser charitable organization data
            $scope.editLegalAction = function (legalActionData) {
                $scope.legalInfo = angular.copy(legalActionData);
                $scope.legalInfo.LegalActionDate = $scope.legalInfo.LegalActionDate == "0001-01-01T00:00:00" ? null : wacorpService.dateFormatService($scope.legalInfo.LegalActionDate);
                $scope.legalInfo.Status = principalStatus.UPDATE;
                $scope.addbuttonName = "Update Legal Information";
            };

            //Delete fundraiser charitable organization data
            $scope.deleteLegalAction = function (legalActionData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (legalActionData.LegalInfoId <= 0 || legalActionData.LegalInfoId == "")
                    {
                        var index = $scope.legalInfoEntity.LegalInfoEntityList.indexOf(legalActionData);
                        $scope.legalInfoEntity.LegalInfoEntityList.splice(index, 1);
                    }
                    else
                        legalActionData.Status = principalStatus.DELETE;
                    
                    //angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (legalInfoItem) {
                    //    if (legalInfoItem.Status!="D")
                    //    {
                    //        $scope.LegalCount++;
                    //    }
                    //});
                    $scope.resetLegalAction();  // resetLegalAction method is available in this file only
                });
            };
            
            $scope.deleteAllFiles = function (flag,files) {
                if (!flag && files.length > constant.ZERO) {
                    //files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js 
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        if ($scope.legalInfoEntity.LegalActionsUploads.length > 0)
                        {
                            angular.forEach($scope.legalInfoEntity.LegalActionsUploads, function (value, data) {
                                if (value.BusinessFilingDocumentId > 0)
                                {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.legalInfoEntity.LegalActionsUploads.indexOf(value);
                                    $scope.legalInfoEntity.LegalActionsUploads.splice(index, 1);
                                }
    
                            });
                        }
                        if ($scope.legalInfoEntity.LegalInfoEntityList.length > 0) {
                            angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (value, data) {
                                if (value.LegalInfoId > 0) {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.legalInfoEntity.LegalInfoEntityList.indexOf(value);
                                    $scope.legalInfoEntity.LegalInfoEntityList.splice(index, 1);
                                }

                            });
                        }
                        //wacorpService.post(webservices.CFT.deleteAllUploadedFiles,files,
                        //    function (response) {
                        //        $scope.legalInfoEntity.LegalInfo.IsAnyLegalActions = false;
                        //        $scope.legalInfoEntity.LegalActionsUploads = [];
                        //        $scope.legalInfoEntity.LegalInfoEntityList = [];
                        //    },
                        //    function (response) {
                        //    }
                        //);
                    },
                    function () {
                        $scope.legalInfoEntity.LegalInfo.IsAnyLegalActions = true;
                    });
                }
            };

            $scope.amendmentLink = function () {
                $location.path('/BusinessAmendmentIndex');
            };

        },
    };
});

wacorpApp.directive('fundraiserCharitableOrganization', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserCharitableOrganization/_FundraiserCharitableOrganization.html',
        restrict: 'A',
        scope: {
            fundraiserCharitableData: '=?fundraiserCharitableData',
            charitableOrganizationsList: '=?charitableOrganizationsList',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.charitableOrganizationsList = $scope.charitableOrganizationsList || [];
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add New";
            $scope.ValidateErrorMessage = false;
            $scope.ValidateEndDateMessage = false;

            $scope.fundraiserCharitable = {
                CharityRegistrationNo: "", CharitableOrganizationName: null, ContractBeginningDate: "", ContractEndingDate: "", CharitablePhoneNumber: null, SequenceNo: "",
                CharitableOrganizationAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, CharitableOrganizationStatus: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            var fundraiserCharitableScopeData = {
                CharityRegistrationNo: "", CharitableOrganizationName: null, ContractBeginningDate: "", ContractEndingDate: "", CharitablePhoneNumber: null, SequenceNo: "",
                CharitableOrganizationAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, CharitableOrganizationStatus: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            $scope.$watch('charitableOrganizationsList', function () {
                angular.forEach($scope.charitableOrganizationsList, function (incor) {
                    incor.ContractBeginningDate = incor.ContractBeginningDate == "0001-01-01T00:00:00" ? wacorpService.dateFormatService(new Date()) : wacorpService.dateFormatService(incor.ContractBeginningDate);
                    incor.ContractEndingDate = incor.ContractEndingDate == "0001-01-01T00:00:00" ? wacorpService.dateFormatService(new Date()) : wacorpService.dateFormatService(incor.ContractEndingDate);
                });
            }, true);

            //Reset the fundraiser charitable organization
            $scope.resetfundraiserCharitable = function () {
                $scope.fundraiserCharitable = angular.copy(fundraiserCharitableScopeData);
                $scope.ValidateErrorMessage = false;
                $scope.ValidateEndDateMessage = false;
                $scope.addbuttonName = "Add New";
            };

            //Add fundraiser charitable organization data
            $scope.AddFundraiserCharitable = function (fundraiserCharitableOrganization) {
                $scope.ValidateErrorMessage = true;
                if (new Date($scope.fundraiserCharitable.ContractEndingDate) < new Date($scope.fundraiserCharitable.ContractBeginningDate)) {
                    $scope.ValidateEndDateMessage = true;
                    return;
                }
                else
                    $scope.ValidateEndDateMessage = false;
                if ($scope[fundraiserCharitableOrganization].$valid) {
                    $scope.ValidateErrorMessage = false;
                    if ($scope.fundraiserCharitable.SequenceNo != "") {
                        angular.forEach($scope.charitableOrganizationsList, function (incorp) {
                            if (incorp.SequenceNo == $scope.fundraiserCharitable.SequenceNo) {
                                $scope.fundraiserCharitable.CharitableOrganizationAddress.FullAddress = wacorpService.fullAddressService($scope.fundraiserCharitable.CharitableOrganizationAddress);
                                angular.copy($scope.fundraiserCharitable, incorp);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.charitableOrganizationsList, function (incorp) {
                            if (maxId == constant.ZERO || incorp.SequenceNo > maxId)
                                maxId = incorp.SequenceNo;
                        });
                        $scope.fundraiserCharitable.SequenceNo = ++maxId;
                        $scope.fundraiserCharitable.CharitableOrganizationAddress.FullAddress = wacorpService.fullAddressService($scope.fundraiserCharitable.CharitableOrganizationAddress);
                        $scope.fundraiserCharitable.CharitableOrganizationStatus = principalStatus.INSERT;
                        $scope.charitableOrganizationsList.push($scope.fundraiserCharitable);
                    }
                    $scope.resetfundraiserCharitable(); // resetfundraiserCharitable method is available in this file only
                }
            };

            //Edit fundraiser charitable organization data
            $scope.editFundraiserCharitable = function (fundraiserCharitabledata) {
                fundraiserCharitabledata.CharitableOrganizationAddress.Country = fundraiserCharitabledata.CharitableOrganizationAddress.Country || codes.USA;
                fundraiserCharitabledata.CharitableOrganizationAddress.State = fundraiserCharitabledata.CharitableOrganizationAddress.State || codes.USA;
                $scope.fundraiserCharitable = angular.copy(fundraiserCharitabledata);
                $scope.fundraiserCharitable.CharitableOrganizationStatus = principalStatus.UPDATE;
                $scope.addbuttonName = "Update";
            };

            //Delete fundraiser charitable organization data
            $scope.deleteFundraiserCharitable = function (fundraiserCharitabledata) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    var index = $scope.charitableOrganizationsList.indexOf(fundraiserCharitabledata);
                    //$scope.charitableOrganizationsList.splice(index, 1);
                    fundraiserCharitabledata.CharitableOrganizationStatus = principalStatus.DELETE;
                    $scope.resetfundraiserCharitable(); // resetfundraiserCharitable method is available in this file only
                });
            };

            // Clear all controls data
            $scope.clearFundraiserCharitable = function () {
                $scope.resetfundraiserCharitable(); // resetfundraiserCharitable method is available in this file only
            };


            $scope.searchCharity = function (CharityId) {
                if ($scope[CharityId].txtCharityRegistration.$valid) {
                    var config = {
                        params: { CharityID: $scope.fundraiserCharitable.CharityRegistrationNo }
                    };
                    // getCharityDetailsByCharityId method is available in constants.js
                    wacorpService.get(webservices.CFT.getCharityDetailsByCharityId, config, function (response) {
                        $scope.fundraiserCharitable = response.data;
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.fundraiserCharitable.ContractBeginningDate = wacorpService.dateFormatService(response.data.ContractBeginningDate);
                        $scope.fundraiserCharitable.ContractEndingDate = wacorpService.dateFormatService(response.data.ContractEndingDate);

                        if (response.data.CharityRegistrationNo == null) {
                            // Folder Name: app Folder
                            // Alert Name: noDataFound method is available in alertMessages.js 
                            wacorpService.alertDialog(messages.noDataFound);
                        }
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
            };

        },
    };
});

wacorpApp.directive('charityOrganizational', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CharitiesOrganization/_CharityOrganization.html',
        restrict: 'A',
        scope: {
            charityOrganization: '=?charityOrganization',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isReview = $scope.isReview || false;
            $scope.messages = messages;
            $scope.usaCode = usaCode;
            $scope.washingtonCode = washingtonCode;

            $scope.isNeedValidation = function () {
                return $scope.showErrorMessage || false;
            };
            $scope.charityOrganization.AKANamesList = $scope.charityOrganization.AKANamesList || [];

            
            $scope.FederalTaxTypes = [];
            $scope.Countries = [];
            $scope.States = [];

            //Get Federal Tax Types List
            $scope.getFederalTaxTypes = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.FederalTaxTypes(function (response) { $scope.FederalTaxTypes = response.data; });
            };
            $scope.getFederalTaxTypes(); // getFederalTaxTypes method is available in this file only

            var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
                $scope.Countries = response.data;
            }, function (response) {
            });

            var lookupStatesParams = { params: { name: 'JurisdictionStates' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
                $scope.States = response.data;
            }, function (response) {
            });

            $scope.selectedJurisdiction = function (items, selectedVal) {
                var result = "";
                angular.forEach(items, function (item) {
                    if (selectedVal == item.Key) {
                        result = item.Value;
                    }
                });
                return result;
            }

            $scope.CountryChangeDesc = function () {
                $scope.charityOrganization.OSJurisdictionCountyDesc = $scope.selectedJurisdiction($scope.Countries, $scope.charityOrganization.OSJurisdictionCountyId); // selectedJurisdiction method is available in this file only.
            };

            $scope.StateChangeDesc = function () {
                $scope.charityOrganization.OSJurisdictionStateDesc = $scope.selectedJurisdiction($scope.States, $scope.charityOrganization.OSJurisdictionStateId); // selectedJurisdiction method is available in this file only.
            };

            $scope.$watch('charityOrganization', function () {               

                angular.forEach($scope.FederalTaxTypes, function (tax) {
                    if (tax.Key == $scope.charityOrganization.FederalTaxExemptId)
                        $scope.charityOrganization.FederalTaxExemptText = tax.Value;
                });
                angular.forEach($scope.Countries, function (county) {
                    if (county.Key == $scope.charityOrganization.OSJurisdictionCountyId)
                        $scope.charityOrganization.OSJurisdictionCountyDesc = county.Value;
                });
                angular.forEach($scope.States, function (state) {
                    if (state.Key == $scope.charityOrganization.OSJurisdictionStateId)
                        $scope.charityOrganization.OSJurisdictionStateDesc = state.Value;
                });

            }, true);

            $scope.deleteAllFiles = function (files) {
                if (files.length > constant.ZERO) {
                    //files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        // deleteAllUploadedFiles method is available in constants.js
                        wacorpService.post(webservices.Common.deleteAllUploadedFiles, files,
                            function (response) {
                                $scope.charityOrganization.FederaltaxUpload = [];
                            },
                            function (response) {
                            }
                        );
                    },
                    function () {
                        $scope.charityOrganization.IsFederalTax = true;
                    });
                }
            };

            
        },
    };
});
wacorpApp.directive('akaNames', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/AKANames/_AKANames.html',
        restrict: 'A',
        scope: {
            akaNameData: '=?akaNameData',
            akaNamesList: '=?akaNamesList',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService) {
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.showAKANameValidation = false;
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add";
            $scope.messages = messages;
            $scope.akaNamesList = $scope.akaNamesList || [];

            $scope.akaName = {
                ID: constant.ZERO, Name: "", Status: "", SequenceNo: ""
            };
          
            var AKANameScopeData = {
                ID: constant.ZERO, Name: "", Status: "", SequenceNo: ""
            };

            //Reset the AKA Name
            $scope.resetAKAName = function () {
                $scope.akaName = angular.copy(AKANameScopeData);
                $scope.addbuttonName = "Add";
            };

            //Clear AKA Name
            $scope.clearAKAName = function () {
                $scope.resetAKAName();
                $scope.showAKANameValidation = false;
            };

            //Add AKA Name data
            $scope.AddAkaName = function () {
                $scope.showAKANameValidation = true;
                if ($scope["akaNames"].$valid) {
                    $scope.showAKANameValidation = false;
                    if ($scope.akaName.SequenceNo != "" && $scope.akaName.SequenceNo != null && $scope.akaName.SequenceNo != 0) {
                        angular.forEach($scope.akaNamesList, function (akname) {
                            if (akname.SequenceNo == $scope.akaName.SequenceNo) {
                                $scope.akaName.AKAName = $scope.trim($scope.akaName.AKAName);
                                if ($scope.akaName.AKAName)
                                     angular.copy($scope.akaName, akname);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.akaNamesList, function (akname) {
                            if (maxId == constant.ZERO || akname.SequenceNo > maxId)
                                maxId = akname.SequenceNo;
                        });
                        $scope.akaName.SequenceNo = ++maxId;                       
                        $scope.akaName.Status = principalStatus.INSERT;
                        $scope.akaName.AKAName = $scope.trim($scope.akaName.AKAName);
                        if ($scope.akaName.AKAName)
                             $scope.akaNamesList.push($scope.akaName);
                    }
                    $scope.resetAKAName(); // resetAKAName method is available in this file only.
                }
            };

            //Edit AKA NAme data
            $scope.editAKAName = function (akaNameData) {
                $scope.akaName = angular.copy(akaNameData);
                if ($scope.akaName.Status != principalStatus.INSERT) {
                    $scope.akaName.Status = principalStatus.UPDATE;
                }                
                $scope.addbuttonName = "Update";
            };

            //Delete AKA NAme data
            $scope.deleteAKAName = function (akaNameData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (akaNameData.ID <= 0)
                    {
                        var index = $scope.akaNamesList.indexOf(akaNameData);
                        $scope.akaNamesList.splice(index, 1);
                    }
                    else
                      akaNameData.Status = principalStatus.DELETE;
                    $scope.resetAKAName(); // resetAKAName method is available in this file only.
                });
            };

            $scope.$watch('akaNamesList', function () {               

                angular.forEach($scope.akaNamesList, function (akaname) {
                    if (akaname.Status == principalStatus.DELETE) {
                        angular.forEach($scope.akaNameData.CharityAkaInfoEntityList, function (charityAKA) {
                            if (charityAKA.SequenceNo == akaname.SequenceNo)
                                charityAKA.Status = principalStatus.DELETE;
                        });
                    }
                    else if (akaname.Status == principalStatus.UPDATE) {
                        angular.forEach($scope.akaNameData.CharityAkaInfoEntityList, function (charityAKA) {
                            if (charityAKA.SequenceNo == akaname.SequenceNo)
                                charityAKA.AkaName = akaname.AKAName;
                        });                      
                    }
                });

            }, true);

            $scope.trim = function (value) {
                var name = value;
                return  name = name.trim();
            }

        },
    };
});
wacorpApp.directive('fundraiserOrganizationalStructure', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserOrganizationalStructure/_FundraiserOrganizationalStructure.html',
        restrict: 'A',
        scope: {
            organizationalStructureData: '=?organizationalStructureData',
            showStreetAddress: '=?showStreetAddress',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.usaCode = usaCode;
            $scope.washingtonCode = washingtonCode;
            $scope.showStreetAddress = $scope.showStreetAddress || false;
            $scope.isReview = $scope.isReview || false;
            //$scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.UploadSurityBondList = $scope.UploadSurityBondList || [];
            $scope.organizationalStructureData.AKANamesList = $scope.organizationalStructureData.AKANamesList || [];
            $scope.Countries = [];
            $scope.States = [];
            $scope.FederalTaxTypes = [];
            $scope.FederaltaxUpload = $scope.FederaltaxUpload || [];
            $scope.organizationalStructureData.SubContractorsList = $scope.organizationalStructureData.SubContractorsList || [];
            $scope.organizationalStructureData.SearchType = 'feinnumber';

            var fundraiserOrganizationalStructureScope = {
                IsOrganizationalStructureType: null, OrganizationalStructureJurisdictionId: null, OrganizationStructureJurisdictionCountryId: codes.USA,
                OrganizationStructureJurisdictionCountryDesc: null, OrganizationalStructureStateJurisdictionId: codes.WA, OrganizationalStructureStateJurisdictionDesc: null,
                OtherComments: null, BondingCompanyName: null, BondNumber: null, CancellationDate: null, IsFundraiserUsesSubContractors: false, SubContractorsList: [],
                IsFederalTax: false, Purpose: null, SearchType: 'feinnumber', SearchValue: null, SequenceNo: null, NewStatus: null, SubContractorFEINNumber: null, SubContractorRegistrationNo: null
            };

            $scope.resetScope = {
                IsOrganizationalStructureType: null, OrganizationalStructureJurisdictionId: null, OrganizationStructureJurisdictionCountryId: codes.USA,
                OrganizationStructureJurisdictionCountryDesc: null, OrganizationalStructureStateJurisdictionId: codes.WA, OrganizationalStructureStateJurisdictionDesc: null,
                OtherComments: null, BondingCompanyName: null, BondNumber: null, CancellationDate: null, IsFundraiserUsesSubContractors: false, SearchType: 'feinnumber', SearchValue: null, SequenceNo: null, NewStatus: null,
                SubContractorFEINNumber: null, SubContractorRegistrationNo: null, SubContractorsList: []
            };

            $scope.organizationalStructureData = $scope.organizationalStructureData ? angular.extend(fundraiserOrganizationalStructureScope, $scope.organizationalStructureData) : angular.copy(fundraiserOrganizationalStructureScope);


            $scope.selectedJurisdiction = function (items, selectedVal) {
                var result = "";
                angular.forEach(items, function (item) {
                    if (selectedVal == item.Key) {
                        result = item.Value;
                    }
                });
                return result;
            }

            $scope.CountryChangeDesc = function () {
                $scope.organizationalStructureData.OrganizationStructureJurisdictionCountryDesc = $scope.selectedJurisdiction($scope.Countries, $scope.organizationalStructureData.OrganizationStructureJurisdictionCountryId);
            };

            $scope.StateChangeDesc = function () {
                $scope.organizationalStructureData.OrganizationalStructureStateJurisdictionDesc = $scope.selectedJurisdiction($scope.States, $scope.organizationalStructureData.OrganizationalStructureStateJurisdictionId);
            };

            $scope.FederalTaxTypesChangeDesc = function () {
                $scope.organizationalStructureData.FederalTaxExemptText = $scope.selectedJurisdiction($scope.FederalTaxTypes, $scope.organizationalStructureData.FederalTaxExemptId);
            };


            var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
                $scope.Countries = response.data;
            }, function (response) {
            });

            var lookupStatesParams = { params: { name: 'JurisdictionStates' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
                $scope.States = response.data;
            }, function (response) {
            });

            //Get Federal Tax Types List
            $scope.getFederalTaxTypes = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.FederalTaxTypes(function (response) { $scope.FederalTaxTypes = response.data; });
            };

            $scope.getFederalTaxTypes(); // getFederalTaxTypes method is available in this file only

            $scope.$watch('organizationalStructureData', function () {
                $scope.organizationalStructureData.IsOrganizationalStructureType = angular.isNullorEmpty($scope.organizationalStructureData.IsOrganizationalStructureType) ? 'O' : $scope.organizationalStructureData.IsOrganizationalStructureType;

                $scope.organizationalStructureData.OrganizationalStructureJurisdictionId = angular.isNullorEmpty($scope.organizationalStructureData.OrganizationalStructureJurisdictionId) ? $scope.washingtonCode : $scope.organizationalStructureData.OrganizationalStructureJurisdictionId.toString();

                angular.forEach($scope.States, function (state) {
                    if (state.Key == $scope.organizationalStructureData.OrganizationalStructureJurisdictionId.toString())
                        $scope.organizationalStructureData.OrganizationalStructureStateJurisdictionDesc = state.Value;
                });

                angular.forEach($scope.Countries, function (country) {
                    if (country.Key == $scope.organizationalStructureData.OrganizationalStructureJurisdictionId.toString())
                        $scope.organizationalStructureData.OrganizationStructureJurisdictionCountryDesc = country.Value;
                });

                angular.forEach($scope.FederalTaxTypes, function (tax) {
                    if (tax.Key == $scope.organizationalStructureData.FederalTaxExemptId)
                        $scope.organizationalStructureData.FederalTaxExemptText = tax.Value;
                });

                $scope.organizationalStructureData.SearchType = angular.isNullorEmpty($scope.organizationalStructureData.SearchType) ? 'feinnumber' : $scope.organizationalStructureData.SearchType;

                $scope.organizationalStructureData.IsFederalTax = angular.isNullorEmpty($scope.organizationalStructureData.IsFederalTax) ? true : $scope.organizationalStructureData.IsFederalTax;

            });

            $scope.deleteAllFiles = function (files) {
                if (files.length > constant.ZERO) {
                    files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        // deleteAllUploadedFiles method is available in constants.js
                        wacorpService.post(webservices.Common.deleteAllUploadedFiles, files,
                            function (response) {
                                $scope.organizationalStructureData.FederaltaxUpload = [];
                            },
                            function (response) {
                            }
                        );
                    },
                    function () {
                        $scope.organizationalStructureData.IsFederalTax = true;
                    });
                }
            };

            //clear text on selecting radiobutton
            $scope.cleartext = function () {
                $scope.organizationalStructureData.SubContractorFEINNumber = null;
                $scope.organizationalStructureData.SubContractorRegistrationNo = null;
            };

            //reset form
            $scope.resetForm = function () {
                $scope.organizationalStructureData.SubContractorFEINNumber = null;
                $scope.organizationalStructureData.SubContractorRegistrationNo = null;
                $scope.organizationalStructureData.SearchType = 'feinnumber';
            };

            //Add fundraiser subcontractors data
            $scope.AddSubContractor = function (searchform) {
                var config = {
                    params: { FEINNo: $scope.organizationalStructureData.SubContractorFEINNumber == undefined ? "" : $scope.organizationalStructureData.SubContractorFEINNumber, RegistrationId: $scope.organizationalStructureData.SubContractorRegistrationNo == undefined ? "" : $scope.organizationalStructureData.SubContractorRegistrationNo }
                };
                // getFundraiserSubContractorDetails method is available in constants.js
                wacorpService.get(webservices.CFT.getFundraiserSubContractorDetails, config, function (response) {
                    $scope.organizationalStructureData.SubContractorsList = response.data;
                    $scope.resetForm(); // resetForm method is available in this file only
                    if (response.data.length == 0) {
                        // Folder Name: app Folder
                        // Alert Name: noDataFound method is available in alertMessages.js
                        wacorpService.alertDialog(messages.noDataFound);
                    }
                }, function (response) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data.Message);
                });
            };

            //Delete fundraiser subcontractors data
            $scope.deleteSubContractor = function (subContractor) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    var index = $scope.organizationalStructureData.SubContractorsList.indexOf(subContractor);
                    //$scope.organizationalStructureData.SubContractorsList.splice(index, 1);
                    subContractor.NewStatus = principalStatus.DELETE;
                    $scope.resetForm(); // resetForm method is available in this file only
                });
            };


        },
    };
});
wacorpApp.directive('cftOfficers', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CFTOfficers/_CFTOfficers.html',
        restrict: 'A',
        scope: {
            cftOfficersList: '=?cftOfficersList',
            showErrorMessage: '=?showErrorMessage',
            mainModel: '=?mainModel',
            isReview: '=?isReview',
            isOfficerAddress: '=?isOfficerAddress',
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope, $location, $timeout) {
            $scope.messages = messages;
            $scope.cftOfficersList = $scope.cftOfficersList || [];
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add New Officer";
            $scope.ValidateErrorMessage = false;
            $scope.IsIamOfficer = false;
            $scope.cftOfficer = {
                OfficerID: "", FirstName: null, LastName: null, Title: null, FullName: null, SequenceNo: "", PhoneNumber: "", EmailAddress: "", TypeID: "", OfficerBaseType: "", IsCFTOfficer: false,Status:null,
                OfficerAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, Status: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO, OfficerStatus: principalStatus.INSERT,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null, IsSameAsAddressContactInfo: false
            };

            var cftOfficersScopeData = {
                OfficerID: "", FirstName: null, LastName: null, Title: null, FullName: null, SequenceNo: "", PhoneNumber: "", EmailAddress: "", TypeID: "", OfficerBaseType: "", IsCFTOfficer: false,Status:null,
                OfficerAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, Status: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO, OfficerStatus: principalStatus.INSERT,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null, IsSameAsAddressContactInfo: false
            };

            //Reset the fundraiser charitable organization
            $scope.resetCFTOfficer = function () {
                $scope.cftOfficer = angular.copy(cftOfficersScopeData);
                $scope.ValidateErrorMessage = false;
                $scope.addbuttonName = "Add New Officer";
                //$scope.IsIamOfficer = false;
                $("#loginOfficer").prop("checked", false);
            };

            //Add fundraiser charitable organization data
            $scope.AddCFTOfficer = function (cftOfficersForm) {
                $scope.ValidateErrorMessage = true;

                $scope.cftOfficer.OfficerAddress.StreetAddress1 = (($scope.cftOfficer.OfficerAddress.StreetAddress1 != null && $scope.cftOfficer.OfficerAddress.StreetAddress1.trim() == "" || $scope.cftOfficer.OfficerAddress.StreetAddress1 == undefined) ? $scope.cftOfficer.OfficerAddress.StreetAddress1 = null : $scope.cftOfficer.OfficerAddress.StreetAddress1.trim());
                if (!$scope.cftOfficer.OfficerAddress.StreetAddress1) {
                    $scope.cftOfficersForm.CFTAddress.StreetAddress1.$setValidity("text", false);
                }
                else {
                    $scope.cftOfficersForm.CFTAddress.StreetAddress1.$setValidity("text", true);
                }

                if ($scope[cftOfficersForm].$valid) {
                    $scope.ValidateErrorMessage = false;
                    $scope.addbuttonName = "Add New Officer";
                    if ($scope.cftOfficer.SequenceNo != 0) {
                        angular.forEach($scope.cftOfficersList, function (officer) {

                            if (officer.SequenceNo == $scope.cftOfficer.SequenceNo) {
                                //officer.OfficerStatus = principalStatus.UPDATE;
                                //$scope.cftOfficer.OfficerAddress.FullAddress = wacorpService.cftFullAddressService($scope.cftOfficer.OfficerAddress);
                                angular.copy($scope.cftOfficer, officer);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.cftOfficersList, function (officer) {
                            if (maxId == constant.ZERO || officer.SequenceNo > maxId)
                                maxId = officer.SequenceNo;
                        });
                        $scope.cftOfficer.SequenceNo = ++maxId;
                        //$scope.cftOfficer.OfficerAddress.FullAddress = wacorpService.cftFullAddressService($scope.cftOfficer.OfficerAddress);
                        $scope.cftOfficer.OfficerStatus = principalStatus.INSERT;
                        $scope.cftOfficer.IsCFTOfficer = true;
                        $scope.cftOfficersList.push($scope.cftOfficer);
                    }
                    $scope.resetCFTOfficer(); // resetCFTOfficer method is available in this file only.
                }
            };

            //Edit fundraiser charitable organization data
            $scope.editCFTOfficer = function (cftOfficersData) {
                cftOfficersData.OfficerAddress.Country = cftOfficersData.OfficerAddress.Country || codes.USA;
                cftOfficersData.OfficerAddress.State = cftOfficersData.OfficerAddress.State || codes.USA;
                cftOfficersData.IsSameAsAddressContactInfo = false;
                $scope.cftOfficer = angular.copy(cftOfficersData);
                $scope.cftOfficer.OfficerStatus = principalStatus.UPDATE;
                $scope.addbuttonName = "Update Officer";
            };

            //Delete fundraiser charitable organization data
            $scope.deleteCFTOfficer = function (cftOfficersData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (cftOfficersData.OfficerID <= 0 || cftOfficersData.OfficerID == "")
                    {
                        var index = $scope.cftOfficersList.indexOf(cftOfficersData);
                        $scope.cftOfficersList.splice(index, 1);
                    }
                    else
                        cftOfficersData.OfficerStatus = principalStatus.DELETE;
                    $scope.resetCFTOfficer(); // resetCFTOfficer method is available in this file only.
                });
            };

            // Clear all controls data
            $scope.clearCFTOfficer = function () {
                $scope.resetCFTOfficer(); // resetCFTOfficer method is available in this file only.
            };

            //Get User Login details during MySelf Select
            $scope.getUserLoginDetails = function (IsIamOfficer) {
                if (IsIamOfficer) {
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        $scope.cftOfficer.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.cftOfficer.LastName = angular.copy($scope.newUser.LastName);
                        $scope.cftOfficer.Title = angular.copy($scope.newUser.Title);
                        $scope.cftOfficer.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.cftOfficer.ConfirmEmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.cftOfficer.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        var addressId = $scope.cftOfficer.OfficerAddress.ID;
                        $scope.cftOfficer.OfficerAddress = angular.copy($scope.newUser.Address);
                        $scope.cftOfficer.OfficerAddress.ID = addressId;
                        $scope.cftOfficer.IsCFTOfficer = false;
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    var seqNo = $scope.cftOfficer.SequenceNo;
                    var officerId = $scope.cftOfficer.OfficerID;
                    var addressId = $scope.cftOfficer.OfficerAddress.ID;
                    var status = $scope.cftOfficer.OfficerStatus;
                    $scope.cftOfficer = angular.copy(cftOfficersScopeData);
                    $scope.cftOfficer.OfficerAddress.ID = addressId;
                    $scope.cftOfficer.SequenceNo = seqNo;
                    $scope.cftOfficer.OfficerID = officerId;
                    $scope.cftOfficer.OfficerStatus = status;

                }
            };

            $scope.amendmentLink = function () {
                window.open('#/BusinessAmendmentIndex', '_blank');
                //$location.path('/BusinessAmendmentIndex');
            };

            $scope.copyFromContactInformation = function () {
                if ($scope.cftOfficer.IsSameAsAddressContactInfo)
                {
                    var addressId=$scope.cftOfficer.OfficerAddress.ID;
                    $scope.cftOfficer.OfficerAddress = angular.copy($scope.mainModel.EntityMailingAddress);
                    $scope.cftOfficer.OfficerAddress.ID = addressId;
                    $scope.cftOfficer.PhoneNumber = $scope.mainModel.EntityPhoneNumber;
                }
                else {
                    var addressId = $scope.cftOfficer.OfficerAddress.ID;
                    $scope.cftOfficer.OfficerAddress = angular.copy(cftOfficersScopeData.OfficerAddress);
                    $scope.cftOfficer.OfficerAddress.ID = addressId;
                    $scope.cftOfficer.PhoneNumber = "";
                }
            }

            $scope.changedAddress = function () {
                if ($scope.cftOfficer.IsSameAsAddressContactInfo) {
                    $scope.cftOfficer.IsSameAsAddressContactInfo = false;
                }
            };

            var changedMailingAddress = $scope.$on("onMailingAddressChanged", function () {
                $scope.changedAddress(); 
            });

            $scope.$on('$destroy', function () {
                changedMailingAddress(); 
            });
        },
    };
});

wacorpApp.directive('cftGenericUploadFiles', function ($http) {
    return {
        templateUrl: 'ng-app/directives/CFT/CFTUploadFiles/CFTGenericUploadFiles.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            isReview: '=?isReview',
            uploadList: '=?uploadList',
            showErrorMessage: '=?showErrorMessage',
            fileSize: '=?fileSize',
            fileType: '=?fileType',
            validateFileType: '=?validateFileType',
            validateFileSize: '=?validateFileSize',
            documentTypeId: '=?documentTypeId',
            documentType: '=?documentType',
            cftType: '=?cftType'
        },
        controller: function ($scope, $http, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.isReview = $scope.isReview || false;
            $scope.uploadList = $scope.uploadList || [];
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.fileSize = angular.isNullorEmpty($scope.fileSize) ? uploadedFiles.FILESIZE : $scope.fileSize;
            $scope.fileType = angular.isNullorEmpty($scope.fileType) ? uploadedFiles.FILETYPES : $scope.fileType;
            $scope.validateFileType = angular.isNullorEmpty($scope.validateFileType) ? true : $scope.validateFileType;
            $scope.validateFileSize = angular.isNullorEmpty($scope.validateFileSize) ? true : $scope.validateFileSize;
            $scope.fileSizeMessage = $scope.messages.UploadFiles.fileSizeNote.replace('{0}', ($scope.fileSize / (uploadedFiles.FILESIZEMB)));
            $scope.fileTypeMessage = ($scope.fileType.toString() == 'NONE' || $scope.fileType.toString() == '') ? "" : $scope.messages.UploadFiles.fileTypeNote.replace('{0}', $scope.fileType.toString());
            $scope.documentTypeId = $scope.documentTypeId || '';
            $scope.documentType = $scope.documentType || '';
            $scope.cftType = $scope.cftType||'';

            $scope.$watch(function () {
                $scope.uploadConfirmation = $scope.messages.UploadFiles.uploadFilesSectionConfirmation.replace('{0}', $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName);
                $scope.uploadText = "";
                $scope.uploadText = $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName;

                if ($scope.uploadText.slice(1) == "a List of Addresses Used") {
                    $scope.uploadText = "A List of Addresses Used"
                }
                else
                    $scope.uploadText;
            });

            // NOW UPLOAD THE FILES.
            $scope.upload = function (e) {
                var validFormats = $scope.fileType;
                $scope.files = [];
                $scope.$apply(function () {
                    for (var i = constant.ZERO; i < e.files.length; i++) {
                        $scope.files.push(e.files[i])
                    }
                });
                var data = new FormData();
                var selectedFiles = [];
                for (var i in $scope.files) {
                    data.append("uploadedFile", $scope.files[i]);
                    var value = $scope.files[i];
                    if (value.name != "") {
                        var fileInfo = {
                            extenstion: value.name.substring(value.name.lastIndexOf('.') + constant.ONE).toLowerCase(),
                            size: value.size,
                        };
                        selectedFiles.push(fileInfo);
                    }
                }
                angular.forEach(selectedFiles, function (file) {
                    var fileTypeindex = constant.ZERO, filesizeValid = true, formatValid = false;
                    if ($scope.validateFileType) {
                        angular.forEach(validFormats, function (item) {
                            if (item.replace(/\s/g, '') == file.extenstion) {
                                formatValid = true;
                            }
                        });
                        fileTypeindex = formatValid ? 1 : -1;
                        //fileTypeindex = validFormats.indexOf(file.extenstion);
                    }
                    if ($scope.validateFileSize)
                        filesizeValid = file.size <= $scope.fileSize;
                    if (fileTypeindex > constant.NEGATIVE && filesizeValid) {

                        if ($scope.documentType == uploadedFiles.FederalTaxDocuments) {
                            $scope.documentTypeId = docuementTypeIds.FederalTaxDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.LegalInfoAddressDocuments) {
                            $scope.documentTypeId = docuementTypeIds.LegalInfoAddressDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.ArticlesofIncorporation) {
                            $scope.documentTypeId = docuementTypeIds.UploadArticlesofIncorporation;
                        }
                        else if ($scope.documentType == uploadedFiles.ListOfAddressesDocuments) {
                            $scope.documentTypeId = docuementTypeIds.ListOfAddressesDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.TaxReturnListDocuments) {
                            $scope.documentTypeId = docuementTypeIds.TaxReturnListDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.OverrideDocuments) {
                            $scope.documentTypeId = docuementTypeIds.OverrideDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.UploadBondwaiverSosBondDocument) {
                            $scope.documentTypeId = docuementTypeIds.UploadBondwaiverSosBondDocument;
                        }
                        else if ($scope.documentType == uploadedFiles.UploadBondwaiverSuretyBondDocuments) {
                            $scope.documentTypeId = docuementTypeIds.UploadBondwaiverSuretyBondDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.FinancialInformationIrsDocumentUpload) {
                            $scope.documentTypeId = docuementTypeIds.FinancialInformationIrsDocumentUpload;
                        }
                        else if ($scope.documentType == uploadedFiles.DeclarationOfTrust) {
                            $scope.documentTypeId = docuementTypeIds.DeclarationOfTrust;
                        }
                        else if ($scope.documentType == uploadedFiles.UploadSuretyBondsDocuments) {
                            $scope.documentTypeId = docuementTypeIds.UploadSuretyBondsDocuments;
                        }
                        else if ($scope.documentType == uploadedFiles.SuretyBond) {
                            $scope.documentTypeId = docuementTypeIds.SuretyBond;
                        }

                        if ($rootScope.repository.loggedUser != undefined)
                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                        var uri = webservices.CFT.fileUpload + '?DocumentType=' + $scope.documentType + '&DocumentTypeId=' + $scope.documentTypeId + '&FullUserName=' + ($rootScope.repository.loggedUser != undefined ? $rootScope.repository.loggedUser.FullUserName : '') + '&cftType=' + $scope.cftType;
                        $http({
                            url: uri,
                            method: "POST",
                            cache: false,
                            data: data,
                            transformRequest: angular.identity,
                            headers: {
                                'Content-Type': undefined
                            }
                        }).success(function (result) {
                            $(e).closest('form')[0].reset();
                            $scope.uploadList.push(result[constant.ZERO]);
                        }).error(function (result, status) {
                            $(e).closest('form')[0].reset();
                            // Folder Name: app Folder
                            // Alert Name: uploadFailed method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.uploadFailed);
                        });
                        $scope.filenotSupported = "";
                    }
                    else {
                        if (fileTypeindex == constant.NEGATIVE)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (fileTypeindex == constant.NEGATIVE && file.size > $scope.fileSize)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (file.size > $scope.fileSize) {
                            var size = ($scope.fileSize / (uploadedFiles.FILESIZEMB));
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileSizeNotSupport.replace('{0}', size);
                        }
                    }
                });

                angular.element(e).val(null);
            }

            $scope.deleteFile = function (file, index) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                    // deleteUploadedFile method is available in constants.js
                    wacorpService.post(webservices.CFT.deleteUploadedFile, file,
                        function (response) {
                            if (response.data.BusinessFilingDocumentId > 0) {
                                angular.forEach($scope.uploadList, function (value, key) {
                                    if (response.data.BusinessFilingDocumentId == value.BusinessFilingDocumentId) {
                                        value.Status = response.data.Status;
                                    }
                                });
                            }
                            else {
                                //var index = $scope.uploadList.indexOf(response);
                                $scope.uploadList.splice(index, constant.ONE);
                            }
                            // Folder Name: app Folder
                            // Alert Name: fileDelete method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDelete);
                            if ($scope.uploadList.length == 0) {
                                $scope.uploadList = [];
                            }
                        },
                        function (response) {
                            // Folder Name: app Folder
                            // Alert Name: fileDeleteFailed method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDeleteFailed);
                        }
                    );
                });
            };

            $scope.genericUploadClick = function () {
                var uploadID = $scope.modalName + '_UploadGenericFile';
                $('#' + uploadID).trigger('click');
            };
        },
    };
});
wacorpApp.directive('cftGlobalUpload', function ($http) {
    return {
        templateUrl: 'ng-app/directives/CFT/CFTGlobalUpload/CFTGlobalUpload.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            isReview: '=?isReview',
            uploadList: '=?uploadList',
            uploadData: '=?uploadData',
            showErrorMessage: '=?showErrorMessage',
            fileSize: '=?fileSize',
            fileType: '=?fileType',
            validateFileType: '=?validateFileType',
            validateFileSize: '=?validateFileSize',
            isCorporation: '=?isCorporation',
            note: '=?note',
            cftType: '=?cftType'
        },
        controller: function ($scope, $http, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.isReview = $scope.isReview || false;
            $scope.uploadList = $scope.uploadList || [];
            $scope.uploadData = $scope.uploadData || {};
            $scope.uploadData.IsAdditionalDocumentsExist = angular.isNullorEmpty($scope.uploadData.IsAdditionalDocumentsExist) ? true : $scope.uploadData.IsAdditionalDocumentsExist;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.note = angular.isNullorEmpty($scope.note) ? "" : $scope.note;
            $scope.fileSize = angular.isNullorEmpty($scope.fileSize) ? uploadedFiles.FILESIZE : $scope.fileSize;
            $scope.fileType = angular.isNullorEmpty($scope.fileType) ? uploadedFiles.FILETYPES : $scope.fileType;
            $scope.validateFileType = angular.isNullorEmpty($scope.validateFileType) ? true : $scope.validateFileType;
            $scope.validateFileSize = angular.isNullorEmpty($scope.validateFileSize) ? true : $scope.validateFileSize;
            $scope.fileSizeMessage = $scope.messages.UploadFiles.fileSizeNote.replace('{0}', ($scope.fileSize / (uploadedFiles.FILESIZEMB)));
            $scope.fileTypeMessage = ($scope.fileType.toString() == 'NONE' || $scope.fileType.toString() == '') ? "" : $scope.messages.UploadFiles.fileTypeNote.replace('{0}', $scope.fileType.toString());
            $scope.DocumentTypes = [];
            $scope.DocumentType = $scope.DocumentType || "";
            $scope.DocumentTypeId = $scope.DocumentTypeId || "";
            $scope.isCorporation = angular.isNullorEmpty($scope.isCorporation) ? true : $scope.isCorporation;
            $scope.cftType = $scope.cftType || '';

            //$scope.selectedDocumentType = function (items, selectedVal) {
            //    var result = "";
            //    angular.forEach(items, function (item) {
            //        if (selectedVal == item.Key) {
            //            result = item.Value;
            //        }
            //    });
            //    return result;
            //}

            //if ($scope.isCorporation) {
            //    var lookupDocumentParams = { params: { name: 'UploadDocumentType' } };
            //    wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupDocumentParams, function (response) {
            //        $scope.DocumentTypes = response.data;
            //    }, function (response) {
            //    });

            //    $scope.changeDocumentType = function (DocumentTypeId) {
            //        $scope.DocumentType = $scope.selectedDocumentType($scope.DocumentTypes, DocumentTypeId);
            //        $scope.DocumentTypeId = DocumentTypeId;
            //    };
            //} else {
            //    var lookupDocumentParams = { params: { name: 'CharityUploadDocumentType' } };
            //    wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupDocumentParams, function (response) {
            //        $scope.DocumentTypes = response.data;
            //    }, function (response) {
            //    });

            //    $scope.changeDocumentType = function (DocumentTypeId) {
            //        $scope.DocumentType = $scope.selectedDocumentType($scope.DocumentTypes, DocumentTypeId);
            //        $scope.DocumentTypeId = DocumentTypeId;
            //    };
            //}

            $scope.$watch(function () {

                $scope.UploadLableText = $scope.sectionName.replace($scope.sectionName.split(' ')[0], '').trim();

                $scope.uploadConfirmation = $scope.messages.UploadFiles.uploadFilesSectionConfirmation.replace('{0}', $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName);
                $scope.uploadText = "";
                $scope.uploadText = $scope.sectionName;
            });

            $scope.$watch('uploadList', function () {
                if ($scope.uploadList != null && $scope.uploadList != undefined) {
                    if ($scope.uploadList.length > 0) {
                        $scope.uploadData.IsAdditionalDocumentsExist = true;
                    }
                }
            });

            // NOW UPLOAD THE FILES.
            $scope.upload = function (e) {
                var validFormats = $scope.fileType;
                $scope.files = [];
                $scope.$apply(function () {
                    for (var i = constant.ZERO; i < e.files.length; i++) {
                        $scope.files.push(e.files[i])
                    }
                });
                var data = new FormData();
                var selectedFiles = [];
                for (var i in $scope.files) {
                    data.append("uploadedFile", $scope.files[i]);

                    var value = $scope.files[i];
                    if (value.name != "") {
                        var fileInfo = {
                            extenstion: value.name.substring(value.name.lastIndexOf('.') + constant.ONE).toLowerCase(),
                            size: value.size,
                        };
                        selectedFiles.push(fileInfo);
                    }
                }
                angular.forEach(selectedFiles, function (file) {
                    var fileTypeindex = constant.ZERO, filesizeValid = true, formatValid = false;
                    if ($scope.validateFileType) {
                        angular.forEach(validFormats, function (item) {
                            if (item.replace(/\s/g, '') == file.extenstion) {
                                formatValid = true;
                            }
                        });
                        fileTypeindex = formatValid ? 1 : -1;
                    }
                    if ($scope.validateFileSize)
                        filesizeValid = file.size <= $scope.fileSize;
                    if (fileTypeindex > constant.NEGATIVE && filesizeValid) {
                        if ($rootScope.repository.loggedUser != undefined)
                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                        var uri = webservices.CFT.fileUpload + '?DocumentType=' + $scope.DocumentType + '&DocumentTypeId=' + $scope.DocumentTypeId + '&FullUserName=' + ($rootScope.repository.loggedUser != undefined ? $rootScope.repository.loggedUser.FullUserName : '') + '&cftType=' + $scope.cftType;
                        $http({
                            url: uri,
                            method: "POST",
                            cache: false,
                            data: data,
                            transformRequest: angular.identity,
                            headers: {
                                'Content-Type': undefined
                            }
                        }).success(function (result) {
                            $scope.uploadList.push(result[constant.ZERO]);

                            //for (i = 0; i < $scope.uploadList.length; i++) {
                            //    var number = parseInt(i) + parseInt(1);
                            //    $scope.uploadList[i].UploadFileName = $scope.uploadData.BusinessFiling.FilingTypeName + " " + number;
                            //}

                            //angular.forEach($scope.DocumentTypes, function (item) {
                            //    if ($scope.DocumentType == item.Value) {
                            //        $scope.DocumentTypeId = "";
                            //    }
                            //});
                            //$scope.DocumentTypeId = "";


                        }).error(function (result, status) {
                            // Folder Name: app Folder
                            // Alert Name: uploadFailed method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.UploadFiles.uploadFailed);
                        });
                        $scope.filenotSupported = "";
                    }
                    else {
                        if (fileTypeindex == constant.NEGATIVE)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (fileTypeindex == constant.NEGATIVE && file.size > $scope.fileSize)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (file.size > $scope.fileSize) {
                            var size = ($scope.fileSize / (uploadedFiles.FILESIZEMB));
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileSizeNotSupport.replace('{0}', size);
                        }
                    }
                });

                angular.element(e).val(null);
            }

            $scope.deleteFile = function (file, index) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                    // deleteUploadedFile method is available in constants.js
                    wacorpService.post(webservices.CFT.deleteUploadedFile, file,
                        function (response) {
                            if (response.data.BusinessFilingDocumentId > 0) {
                                angular.forEach($scope.uploadList, function (value, key) {
                                    if (response.data.BusinessFilingDocumentId == value.BusinessFilingDocumentId) {
                                        value.Status = response.data.Status;
                                    }
                                });
                            }
                            else {
                                //var index = $scope.uploadList.indexOf(response);
                                $scope.uploadList.splice(index, constant.ONE);
                            }
                            // Folder Name: app Folder
                            // Alert Name: fileDelete method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDelete);
                            if ($scope.uploadList.length == 0) {
                                $scope.uploadList = [];
                            }
                        },
                        function (response) {
                            // Folder Name: app Folder
                            // Alert Name: fileDeleteFailed method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDeleteFailed);
                        }
                    );
                });
            };

            $scope.deleteGlobalAllFiles = function (files) {
                 
                if (files.length > 0) {
                    //files[constant.ZERO].TempFileLocation = "";
                    if (files.length > constant.ZERO) {
                        var fileList = { ListCFTUploadEntity: files }
                        // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            // deleteAllUploadedFiles method is available in constants.js
                            wacorpService.post(webservices.CFT.deleteAllUploadedFiles, fileList,
                                function (response) {
                                    if (response.data.length > 0) {
                                        angular.copy(response.data, $scope.uploadList);
                                        //angular.forEach($scope.uploadList, function (value, key) {
                                        //    if (response.data.BusinessFilingDocumentId == value.BusinessFilingDocumentId) {
                                        //        value.Status = response.data.Status;
                                        //    }
                                        //});
                                    }
                                    else {
                                        $scope.uploadList = [];
                                    }
                                },
                                function (response) {
                                }
                            );
                        },
                        function () {
                            $scope.uploadData.IsAdditionalDocumentsExist = true;
                            files = [];
                        });
                    }
                }
            };

            $scope.globalUploadClick = function () {
                var uploadID = $scope.modalName + '_UploadGlobalFile';
                $('#' + uploadID).trigger('click');
            };
        },

    };
});
wacorpApp.directive('charityFinancial', function () {

    return {
        templateUrl: 'ng-app/directives/CFT/CharitiesFinancialInfo/_CharitiesFinancialInfo.html',
        restrict: 'A',
        scope: {
            charityFinancialInfo: '=?charityFinancialInfo',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            officerNotRequired: '=?officerNotRequired',
            showFinancialHistory: '=?showFinancialHistory',
            financialBtn: '=?financialBtn',
            accDate: '=?accDate'
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope) {
            $scope.initialLoad = true;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isReview = $scope.isReview || false;
            $rootScope.isGlobalEdited = false;
            $scope.isEdited = false;
            $scope.messages = messages;
            $scope.Countries = [];
            $scope.States = [];
            $scope.ValidateFinancialEndDateMessage = false;
            $scope.addbuttonName = "Add";
            $scope.currentFinancialObj = {};
            $scope.FinancialInfoButtonName = $scope.FinancialInfoButtonName ? $scope.FinancialInfoButtonName : "Add Financial Information";
            $scope.showEndDateErrorMessage = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.currentDate = wacorpService.dateFormatService(new Date());
            $scope.endCurrentDate = wacorpService.dateFormatService(new Date());
            $scope.isMandetory = true;
            $scope.officerHighPayFirstName = false;
            $scope.officerHighPayLastName = false;
            $scope.newRenewalDate = "";

            var charityFinancialInfoScope = {
                FinancialSeqNo: null,
                IsFIFullAccountingYear: false,
                AccountingyearBeginningDate: null,
                AccountingyearEndingDate: null,
                FirstAccountingyearEndDate: null,
                BeginingGrossAssets: null,
                RevenueGDfromSolicitations: null,
                RevenueGDRevenueAllOtherSources: null,
                TotalDollarValueofGrossReceipts: null,
                ExpensesGDExpendituresProgramServices: null,
                ExpensesGDValueofAllExpenditures: null,
                EndingGrossAssets: null,
                PercentToProgramServices: null,
                IsFISolicitCollectcontributionsinWA: true,
                Comments: null,
                CFTOfficersList: [],
                OfficersHighPay: null,
                OfficersHighPayList: [],
                CFTFinancialHistoryList: [],
                shortFiscalYearEntity: {
                    FiscalStartDate: "", FiscalEndDate: "", BeginingGrossAssetsForShortFY: null, RevenueGDfromSolicitationsForShortFY: null, RevenueGDRevenueAllOtherSourcesForShortFY: null,
                    TotalDollarValueofGrossReceiptsForShortFY: null, ExpensesGDExpendituresProgramServicesForShortFY: null, ExpensesGDValueofAllExpendituresForShortFY: null,
                    EndingGrossAssetsForShortFY: null, PercentToProgramServicesForShortFY: null
                }
            };
            angular.copy($scope.currentFinancialObj, charityFinancialInfoScope);

            $scope.OfficershighPayData = { ID: '', FirstName: '', LastName: '', SequenceNo: null, Status: '', IsPayOfficers: false, CreatedBy: null };

            $scope.OfficershighPayScopeData = { ID: '', FirstName: '', LastName: '', SequenceNo: null, Status: '', IsPayOfficers: false, CreatedBy: null };

            $scope.charityFinancialInfo = $scope.charityFinancialInfo ? angular.extend(charityFinancialInfoScope, $scope.charityFinancialInfo) : angular.copy(charityFinancialInfoScope);

            $scope.isNeedValidation = function () {
                return $scope.showErrorMessage || false;
            };
            //Get Countries List
            $scope.getCountries = function () {
                lookupService.countriesList(function (response) {
                    $scope.Countries = response.data;
                });
            };

            //Get States List
            $scope.getStates = function () {
                lookupService.statesList(function (response) {
                    $scope.States = response.data;
                });
            };

            $scope.getCountries(); // getCountries method is available in this file only.
            $scope.getStates(); // getCountries method is available in this file only.

            //For Current Financial Info
            $scope.$watchGroup(['charityFinancialInfo.ExpensesGDExpendituresProgramServices', 'charityFinancialInfo.ExpensesGDValueofAllExpenditures'], function () {

                var value1 = parseFloat($scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices == null || $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices == '') ? 0 : $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices;
                var value2 = parseFloat($scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures == null || $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures == '') ? 0 : $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures;
                var percentage = null;
                if (value1 && value2)
                    percentage = ((value1 / value2) * 100).toFixed(2);
                else
                    percentage = null;

                //$scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = parseFloat($scope.charityFinancialInfo.TotalDollarValueofGrossReceipts).toFixed(2);

                if (isNaN(percentage) || percentage === 0)
                    $scope.charityFinancialInfo.PercentToProgramServices = null;
                else {
                    if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                        $scope.charityFinancialInfo.PercentToProgramServices = "-" + Math.round(percentage);
                    } else {
                        $scope.charityFinancialInfo.PercentToProgramServices = Math.round(percentage);
                    }
                }
            }, true);


            //For History Financial Info
            $scope.$watchGroup(['currentFinancialObj.ExpensesGDExpendituresProgramServices', 'currentFinancialObj.ExpensesGDValueofAllExpenditures'], function () {

                var value1 = parseFloat($scope.currentFinancialObj.ExpensesGDExpendituresProgramServices == null || $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices == '') ? 0 : $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices;
                var value2 = parseFloat($scope.currentFinancialObj.ExpensesGDValueofAllExpenditures == null || $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures == '') ? 0 : $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures;
                var percentage = null;
                if (value1 && value2)
                    percentage = ((value1 / value2) * 100).toFixed(2);
                else
                    percentage = null;
                if (isNaN(percentage) || percentage === 0)
                    $scope.currentFinancialObj.PercentToProgramServices = null;
                else {
                    if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                        $scope.currentFinancialObj.PercentToProgramServices = "-" + Math.round(percentage);
                    } else {
                        $scope.currentFinancialObj.PercentToProgramServices = Math.round(percentage);
                    }
                }
            }, true);


            //For Short Fiscal Financial Info
            $scope.$watchGroup(['charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY', 'charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY'], function () {
                if ($scope.charityFinancialInfo.shortFiscalYearEntity != undefined && $scope.charityFinancialInfo.shortFiscalYearEntity != null) {
                    var value1 = parseFloat($scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY == null || $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY == '') ? 0 : $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY;
                    var value2 = parseFloat($scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY == null || $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY == '') ? 0 : $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY;
                    var percentage = null;
                    if (value1 && value2)
                        percentage = ((value1 / value2) * 100).toFixed(2);
                    else
                        percentage = null;

                    if (isNaN(percentage) || percentage === 0)
                        $scope.charityFinancialInfo.shortFiscalYearEntity.PercentToProgramServicesForShortFY = null;
                    else {
                        if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                            $scope.charityFinancialInfo.shortFiscalYearEntity.PercentToProgramServicesForShortFY = "-" + Math.round(percentage);
                        }
                        else {
                            $scope.charityFinancialInfo.shortFiscalYearEntity.PercentToProgramServicesForShortFY = Math.round(percentage);
                        }
                    }
                }
            }, true);

            //Current
            $scope.calCulateTGDV = function () {
                if ($scope.charityFinancialInfo.RevenueGDfromSolicitations == null && $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources == null) {
                    $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = null;
                }
                else {
                    var totalVal =
                               parseFloat(($scope.charityFinancialInfo.RevenueGDfromSolicitations == null || $scope.charityFinancialInfo.RevenueGDfromSolicitations == '') ? 0 : $scope.charityFinancialInfo.RevenueGDfromSolicitations) +
                               parseFloat(($scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources == '' || $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources == null) ? 0 : $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources);

                    if (totalVal === 0)
                        $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = 0;
                    else
                        $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = Math.round(totalVal);
                }
            };

            $scope.$watch('charityFinancialInfo', function () {
                if ($scope.charityFinancialInfo.Comments)
                {
                    if ($scope.charityFinancialInfo.Comments.length > 500)
                    {
                        $scope.charityFinancialInfo.Comments = $scope.charityFinancialInfo.Comments.replace(/(\r\n|\n|\r)/gm, "");
                        $scope.charityFinancialInfo.Comments = $scope.charityFinancialInfo.Comments.substring(0, 500);
                    }
                        
                }
            });
            //History
            $scope.calCulateHistoryTGDV = function () {
                var totalVal =
                               parseFloat(($scope.currentFinancialObj.RevenueGDfromSolicitations == null || $scope.currentFinancialObj.RevenueGDfromSolicitations == '') ? 0 : $scope.currentFinancialObj.RevenueGDfromSolicitations) +
                               parseFloat(($scope.currentFinancialObj.RevenueGDRevenueAllOtherSources == '' || $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources == null) ? 0 : $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources);

                if (totalVal === 0)
                    $scope.currentFinancialObj.TotalDollarValueofGrossReceipts = 0;
                else
                    $scope.currentFinancialObj.TotalDollarValueofGrossReceipts = Math.round(totalVal);

            };

            //Short Fiscal Year
            $scope.calCulateShortFiscalTGDV = function () {
                var totalVal =
                               parseFloat(($scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY == null || $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY == '') ? 0 : $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY) +
                               parseFloat(($scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY == '' || $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY == null) ? 0 : $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY);

                if (totalVal === 0)
                    $scope.charityFinancialInfo.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY = 0;
                else
                    $scope.charityFinancialInfo.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY = Math.round(totalVal);
            };


            var resultHistoryDate = "";
            $scope.ValidateHistoryEndDate = function () {
                if ($scope.currentFinancialObj.AccountingyearBeginningDate != null && $scope.currentFinancialObj.AccountingyearBeginningDate != "") {
                    var value = $scope.currentFinancialObj.AccountingyearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultHistoryDate = lastDayWithSlashes;
                        $scope.currentFinancialObj.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idHisEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.currentFinancialObj.AccountingyearEndingDate = null;
                    }
                }
                else {
                    $scope.currentFinancialObj.AccountingyearEndingDate = null;
                }
                $scope.CheckHistoryEndDate(); // CheckHistoryEndDate method is available in this file only.
            };

            //$scope.charityFinancialInfo.PercentToProgramServices = ((value1 / value2) * 100).toFixed(2);
            var resultDate = "";
            $scope.ValidateEndDate = function () {
                if ($scope.charityFinancialInfo.AccountingyearBeginningDate != null && $scope.charityFinancialInfo.AccountingyearBeginningDate != "") {
                    var value = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultDate = lastDayWithSlashes;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                    }
                }
                else {
                    $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                }

                //if (typeof ($scope.charityFinancialInfo.BusinessFiling) != typeof (undefined) && $scope.charityFinancialInfo.BusinessFiling != null && $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION AMENDMENT') {
                //    $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = false;
                //    if ($scope.charityFinancialInfo.IsFIFullAccountingYear) {
                //        $scope.charityFinancialInfo.AccYearStartDateForAmendment = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                //        //$scope.charityFinancialInfo.AccStartDateMoreThanOneYear = wacorpService.checkForAccYearMaxThenOneYear($scope.charityFinancialInfo.AccYearStartDateForAmendment, $scope.charityFinancialInfo.CurrentEndDateForAmendment);
                //    }
                //}

                if (typeof ($scope.charityFinancialInfo.AccountingyearBeginningDate) != typeof (undefined)
                    && $scope.charityFinancialInfo.AccountingyearBeginningDate != null
                    && typeof ($scope.charityFinancialInfo.BusinessFiling) != typeof (undefined)
                    && $scope.charityFinancialInfo.BusinessFiling != null && $scope.charityFinancialInfo.CFTFinancialHistoryList.length > 0
                    && ($scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION AMENDMENT'
                    || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION OPTIONAL AMENDMENT')) {
                    $scope.checkStartDate = false;
                    if ($scope.charityFinancialInfo.AccountingyearEndingDate && $scope.charityFinancialInfo.CurrentStartDateForAmendment) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        var val = wacorpService.checkDateValidity($scope.charityFinancialInfo.CurrentEndDateForAmendment, $scope.charityFinancialInfo.AccountingyearBeginningDate, $scope.charityFinancialInfo.IsShortFiscalYear);

                        if (val == 'SFY') {
                            $scope.charityFinancialInfo.IsShortFiscalYear = true;
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            var startDate = wacorpService.getShortYearStartDate($scope.charityFinancialInfo.CurrentEndDateForAmendment);

                            $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalStartDate = wacorpService.dateFormatService(startDate);
                            var endDate = wacorpService.getShortYearEndDate($scope.charityFinancialInfo.AccountingyearBeginningDate);
                            $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalEndDate = wacorpService.dateFormatService(endDate);
                            $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = false;
                            $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = false;
                        } else if (val == 'SDgPnD') {
                            $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = true;
                            $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = false;
                            $scope.charityFinancialInfo.IsShortFiscalYear = false;
                            $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalStartDate = null;
                            $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalEndDate = null;
                        } else if (val == 'Y1Plus') {
                            $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = true;
                            $scope.charityFinancialInfo.IsShortFiscalYear = false;
                            $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = false;
                            $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalStartDate = null;
                            $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalEndDate = null;
                        } else {
                            $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = false;
                            $scope.charityFinancialInfo.IsShortFiscalYear = false;
                            $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = false;
                            $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalStartDate = null;
                            $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalEndDate = null;
                        }
                    }


                }

                $scope.CheckEndDate(); // CheckEndDate method is available in this file only.
            };

            $scope.CheckEndDate = function () {

                if ($scope.charityFinancialInfo.AccountingyearBeginningDate != null && $scope.charityFinancialInfo.AccountingyearBeginningDate != "") {
                    var value = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultDate = lastDayWithSlashes;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                    }
                }
                else {
                    $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                }

                if ($scope.charityFinancialInfo.AccountingyearEndingDate != null && $scope.charityFinancialInfo.AccountingyearBeginningDate != null) {
                    if (new Date($scope.charityFinancialInfo.AccountingyearEndingDate) < new Date($scope.charityFinancialInfo.AccountingyearBeginningDate)) {
                        $scope.ValidateFinancialEndDateMessage = true;
                    }
                    else
                        $scope.ValidateFinancialEndDateMessage = false;
                }
                $scope.validateFinancialDates(); // validateFinancialDates method is available in this file only.
            };

            $scope.CheckHistoryEndDate = function () {
                if (new Date($scope.currentFinancialObj.AccountingyearEndingDate) < new Date($scope.currentFinancialObj.AccountingyearBeginningDate)) {
                    $scope.ValidateHistoryFinancialEndDateMessage = true;
                }
                else
                    $scope.ValidateHistoryFinancialEndDateMessage = false;
            };

            $scope.setEndDate = function () {
                $scope.charityFinancialInfo.AccountingyearEndingDate = resultDate;
            }

            $scope.resetHighPay = function () {
                $scope.OfficershighPayData = angular.copy($scope.OfficershighPayScopeData);
                $scope.addbuttonName = "Add";
            }

            $scope.addOfficerHighPay = function (officerHighPay) {

                $scope.ValidateErrorMessage = true;
                $scope.hasValues = officerHighPay.FirstName != null && officerHighPay.FirstName != "" && officerHighPay.FirstName != undefined && officerHighPay.LastName != null && officerHighPay.LastName != "" && officerHighPay.LastName != undefined ? true : false;
                //$scope.hasValues = officerHighPay.FirstName != null && officerHighPay.FirstName != "" || officerHighPay.Lastname != null && officerHighPay.Lastname!="";
                $scope.officerHighPayFirstName = officerHighPay.FirstName != null && officerHighPay.FirstName != "" && officerHighPay.FirstName != " " ? false : true;
                $scope.officerHighPayLastName = officerHighPay.LastName != null && officerHighPay.LastName != "" && officerHighPay.LastName != " " ? false : true;
                if (!$scope.hasValues) {
                    return false;
                }
                else {
                    $scope.ValidateErrorMessage = false;
                    if ($scope.OfficershighPayData.SequenceNo != null && $scope.OfficershighPayData.SequenceNo != '' && $scope.OfficershighPayData.SequenceNo != 0) {
                        angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (highpayItem) {
                            if (highpayItem.SequenceNo == $scope.OfficershighPayData.SequenceNo) {
                                //$scope.cftOfficer.OfficerAddress.FullAddress = wacorpService.cftFullAddressService($scope.cftOfficer.OfficerAddress);
                                angular.copy($scope.OfficershighPayData, highpayItem);
                                $scope.isEdit = false;
                                $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only.

                                //if ($scope.charityFinancialInfo.OfficersHighPayList.length >= 3)
                                //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                                //else
                                //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (highpayItem) {
                            if (maxId == constant.ZERO || highpayItem.SequenceNo > maxId)
                                maxId = highpayItem.SequenceNo;
                        });
                        $scope.OfficershighPayData.SequenceNo = ++maxId;
                        $scope.OfficershighPayData.Status = principalStatus.INSERT;
                        $scope.charityFinancialInfo.OfficersHighPayList.push($scope.OfficershighPayData);
                        $scope.isEdit = false;
                        $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only.
                        //if ($scope.charityFinancialInfo.OfficersHighPayList.length >= 3)
                        //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                        //else
                        //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                        //$scope.ShowHighPayList = true;
                    }
                    $scope.resetHighPay(); // resetHighPay method is available in this file only.
                }
            };

            $scope.checkOfficersValidData = function (firstName,lastName) {
                if (firstName)
                    $scope.officerHighPayFirstName = firstName!=undefined && firstName != null && firstName != "" && firstName != " " ? false : true;
                if (lastName)
                    $scope.officerHighPayLastName = lastName !=undefined&& lastName != null && lastName != "" && lastName != " " ? false : true;
            }

            $scope.editOfficerHighPay = function (highPayActionData) {
                $scope.OfficershighPayData = angular.copy(highPayActionData);
                $scope.OfficershighPayData.Status = principalStatus.UPDATE;
                $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                $scope.addbuttonName = "Update";
                $scope.isEdit = true;
            };

            $scope.deleteOfficerHighPay = function (highPayActionData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (highPayActionData.ID <= 0) {
                        var index = $scope.charityFinancialInfo.OfficersHighPayList.indexOf(highPayActionData);
                        $scope.charityFinancialInfo.OfficersHighPayList.splice(index, 1);
                    }
                    else
                        highPayActionData.Status = principalStatus.DELETE;

                    $scope.isEdit = false;
                    $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only.
                    $scope.resetHighPay();
                    //$scope.Count = 0;
                    //angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (highpayItem) {

                    //    if (highpayItem.Status != "D")
                    //    {
                    //        $scope.Count++;
                    //        if ($scope.Count >=3)
                    //        {
                    //            $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                    //        }
                    //        else {
                    //            $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                    //        }
                    //    }
                    //});
                    if ($scope.charityFinancialInfo.OfficersHighPayList.length == 0)
                        //$scope.ShowHighPayList = true;
                        //if ($scope.charityFinancialInfo.OfficersHighPayList.length >= 3)
                        //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                        //else
                        //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                        $scope.resetHighPay(); // resetHighPay method is available in this file only.
                });
            };


            $scope.checkHighpayCount = function () {
                if (!$scope.isEdit) {
                    var count = 0;
                    angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (highpayItem) {
                        if (highpayItem.Status != "D") {
                            count++;
                        }
                    });

                    if (count >= 3) {
                        $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                    }
                    else {
                        $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                    }
                    return count <= 0;
                }
            };

            $scope.clearFields = function (flag, type) {
                $scope.accDate = false;
                if (!flag) {
                    $scope.charityFinancialInfo.isUpdated = false;
                    if (type == "CHARITABLE ORGANIZATION RENEWAL") {
                        $scope.charityFinancialInfo.AccountingyearBeginningDate = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = $scope.charityFinancialInfo.AccountingyearEndingDate;
                        $scope.charityFinancialInfo.FirstAccountingyearEndDate = $scope.charityFinancialInfo.FirstAccountingyearEndDate;
                        $scope.charityFinancialInfo.BeginingGrossAssets = null;
                        $scope.charityFinancialInfo.RevenueGDfromSolicitations = null;
                        $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources = null;
                        $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = null;
                        $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices = null;
                        $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures = null;
                        $scope.charityFinancialInfo.EndingGrossAssets = null;
                        $scope.charityFinancialInfo.PercentToProgramServices = null;
                        $scope.charityFinancialInfo.Comments = null;
                    }
                    else if (type == "CHARITABLE ORGANIZATION OPTIONAL AMENDMENT" || type == "CHARITABLE ORGANIZATION AMENDMENT") {
                        $scope.resetFinancialInfo();
                        $scope.charityFinancialInfo.AccountingyearBeginningDate = null;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                        $scope.charityFinancialInfo.BeginingGrossAssets = null;
                        $scope.charityFinancialInfo.RevenueGDfromSolicitations = null;
                        $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources = null;
                        $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = null;
                        $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices = null;
                        $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures = null;
                        $scope.charityFinancialInfo.EndingGrossAssets = null;
                        $scope.charityFinancialInfo.PercentToProgramServices = null;
                        $scope.charityFinancialInfo.Comments = null;
                        calculateFAYEDRenewalDate();   // calculateFAYEDRenewalDate method is available in this file only.
                    }
                    else {
                        $scope.charityFinancialInfo.AccountingyearBeginningDate = null;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                        $scope.charityFinancialInfo.BeginingGrossAssets = null;
                        $scope.charityFinancialInfo.RevenueGDfromSolicitations = null;
                        $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources = null;
                        $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = null;
                        $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices = null;
                        $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures = null;
                        $scope.charityFinancialInfo.EndingGrossAssets = null;
                        $scope.charityFinancialInfo.PercentToProgramServices = null;
                        $scope.charityFinancialInfo.Comments = null;
                        calculateFAYEDRenewalDate(); // calculateFAYEDRenewalDate method is available in this file only.
                    }
                }
                else {
                    $scope.charityFinancialInfo.isUpdated = true;
                    if (type == "CHARITABLE ORGANIZATION RENEWAL") {
                        $scope.charityFinancialInfo.BeginingGrossAssets = null;
                        $scope.charityFinancialInfo.AccountingyearBeginningDate = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = $scope.charityFinancialInfo.AccountingyearEndingDate;
                        $scope.charityFinancialInfo.FirstAccountingyearEndDate = $scope.charityFinancialInfo.FirstAccountingyearEndDate;
                    }
                    else {
                        //if (type != "CHARITABLE ORGANIZATION OPTIONAL AMENDMENT" && type != "CHARITABLE ORGANIZATION AMENDMENT") {
                        //    $scope.charityFinancialInfo.FirstAccountingyearEndDate = null;
                        //    $scope.newRenewalDate = "";
                        //}
                        $scope.charityFinancialInfo.IsShortFiscalYear = false;
                    }

                }
            };

            $scope.resetHighPayOfficer = function () {
                $scope.charityFinancialInfo.OfficersHighPayList = [];
                $scope.OfficershighPayData.FirstName = '';
                $scope.OfficershighPayData.LastName = '';
                $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
            };

            $scope.resetSelection = function () {
                if ($scope.charityFinancialInfo.OfficersHighPayList.length > 0) {
                    // Folder Name: app Folder
                    // Alert Name: deleteallRecords method is available in alertMessages.js 
                    wacorpService.confirmDialog($scope.messages.UploadFiles.deleteallRecords, function () {
                        angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (value, data) {
                            if (value.ID > 0) {
                                value.Status = principalStatus.DELETE;
                            }
                            else {
                                var index = $scope.charityFinancialInfo.OfficersHighPayList.indexOf(value);
                                $scope.charityFinancialInfo.OfficersHighPayList.splice(index);
                            }
                        });

                        $scope.OfficershighPayData.FirstName = '';
                        $scope.OfficershighPayData.LastName = '';
                        //$scope.ShowHighPayList = false;
                        $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only.
                        $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;

                    },
                 function () {
                     $scope.charityFinancialInfo.OfficersHighPay.IsPayOfficers = true;
                 });
                }
                //angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (value, data) {
                //    if (value.ID > 0)
                //    {
                //        value.Status = principalStatus.DELETE;

                //    }
                //    else {
                //        var index = $scope.charityFinancialInfo.OfficersHighPayList.indexOf(value);
                //        $scope.charityFinancialInfo.OfficersHighPayList.splice(index);
                //    }
                //})

            };

            //reset contributions
            $scope.resetContributions = function () {
                $scope.charityFinancialInfo.ContributionServicesTypeId = [];
            };

            //reset fundraiser outside of wa
            $scope.resetFundOutsideWA = function () {
                $scope.charityFinancialInfo.FinancialInfoStateId = [];
            };

            //CFT Financial History Methods


            $rootScope.$watch('isGlobalEdited', function (val) {
                $scope.isEdited = val;
                //if ($scope.isEdited) {
                //    $scope.charityFinancialInfo.IsShortFiscalYear = false;
                //}
            });

            //Add Financial History data
            //$scope.AddFinancialInfo = function (cftFinancialForm) {
            //    $scope.showErrorMessage = true;
            //    var isExpensesValid = ($scope.charityFinancialInfo.IsFIFullAccountingYear ? ($scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures < $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices ? false : true) : true);
            //    if ($scope[cftFinancialForm].$valid && isExpensesValid) {
            //        $scope.showErrorMessage = false;
            //        $scope.FinancialInfoButtonName = "Add Financial Information";
            //        var maxId = constant.ZERO;
            //        angular.forEach($scope.charityFinancialInfo.CFTFinancialHistoryList, function (finInfo) {
            //            if (maxId == constant.ZERO || finInfo.SequenceNo > maxId)
            //                maxId = finInfo.SequenceNo;
            //        });
            //        var financialInfoObj = {};
            //        financialInfoObj.SequenceNo = ++maxId;
            //        financialInfoObj.AccountingyearBeginningDate = $scope.charityFinancialInfo.AccountingyearBeginningDate;
            //        financialInfoObj.AccountingyearEndingDate = $scope.charityFinancialInfo.AccountingyearEndingDate;
            //        financialInfoObj.BeginingGrossAssets = $scope.charityFinancialInfo.BeginingGrossAssets;
            //        financialInfoObj.RevenueGDfromSolicitations = $scope.charityFinancialInfo.RevenueGDfromSolicitations;
            //        financialInfoObj.RevenueGDRevenueAllOtherSources = $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources;
            //        financialInfoObj.TotalDollarValueofGrossReceipts = $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts;
            //        financialInfoObj.TotalRevenue = $scope.charityFinancialInfo.RevenueGDfromSolicitations + $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources;
            //        financialInfoObj.ExpensesGDExpendituresProgramServices = $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices;
            //        financialInfoObj.ExpensesGDValueofAllExpenditures = $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures;
            //        financialInfoObj.TotalExpenses = $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices + $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures;
            //        financialInfoObj.EndingGrossAssets = $scope.charityFinancialInfo.EndingGrossAssets;
            //        financialInfoObj.PercentToProgramServices = $scope.charityFinancialInfo.PercentToProgramServices;
            //        $scope.charityFinancialInfo.CFTFinancialHistoryList.push(financialInfoObj);
            //        //resetFinancialInfo();
            //    }
            //};

            $scope.UpdateFinancialInfo = function () {

                var endDate = $scope.currentFinancialObj.AccountingyearEndingDate;
                if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                    if (isEndDateMore) {
                        // Folder Name: app Folder
                        // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js 
                        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                        return false;
                    }
                }

                $scope.showErrorMessageForHistory = true;
                var isExpensesValid = ($scope.currentFinancialObj.IsFIFullAccountingYear ? ($scope.currentFinancialObj.ExpensesGDValueofAllExpenditures < $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices ? false : true) : true);
                var isDatesValid = ($scope.currentFinancialObj.IsFIFullAccountingYear ? ((new Date($scope.currentFinancialObj.AccountingyearEndingDate) > new Date($scope.currentFinancialObj.AccountingyearBeginningDate)) ? true : false) : true);
                if ($scope.CharityFinancialInfoForm.divFinHistory.$valid && isExpensesValid && isDatesValid) {
                    $scope.showErrorMessageForHistory = false;
                    angular.forEach($scope.charityFinancialInfo.CFTFinancialHistoryList, function (financialInfoItem) {
                        if (financialInfoItem.FinancialId == $scope.currentFinancialObj.FinancialId) {
                            financialInfoItem.FinancialId = $scope.currentFinancialObj.FinancialId;
                            financialInfoItem.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingyearBeginningDate;
                            financialInfoItem.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingyearEndingDate;
                            financialInfoItem.BeginingGrossAssets = $scope.currentFinancialObj.BeginingGrossAssets;
                            financialInfoItem.RevenueGDfromSolicitations = $scope.currentFinancialObj.RevenueGDfromSolicitations;
                            financialInfoItem.RevenueGDRevenueAllOtherSources = $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources;
                            financialInfoItem.TotalDollarValueofGrossReceipts = $scope.currentFinancialObj.TotalDollarValueofGrossReceipts;
                            financialInfoItem.TotalRevenue = $scope.currentFinancialObj.RevenueGDfromSolicitations + $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources;
                            financialInfoItem.ExpensesGDExpendituresProgramServices = $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices;
                            financialInfoItem.ExpensesGDValueofAllExpenditures = $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures;
                            financialInfoItem.TotalExpenses = $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices + $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures;
                            financialInfoItem.EndingGrossAssets = $scope.currentFinancialObj.EndingGrossAssets;
                            financialInfoItem.PercentToProgramServices = $scope.currentFinancialObj.PercentToProgramServices;
                            financialInfoItem.Status = principalStatus.UPDATE;
                        }
                    });
                    $rootScope.isGlobalEdited = false;
                    $scope.charityFinancialInfo.isUpdated = true;
                }
            };

            // Clear all controls data
            $scope.clearFinancialInfo = function () {
                $scope.currentFinancialObj.AccountingyearBeginningDate = null;
                $scope.currentFinancialObj.AccountingyearEndingDate = null;
                $scope.currentFinancialObj.BeginingGrossAssets = null;
                $scope.currentFinancialObj.RevenueGDfromSolicitations = null;
                $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources = null;
                $scope.currentFinancialObj.TotalDollarValueofGrossReceipts = null;
                $scope.currentFinancialObj.EndingGrossAssets = null;
                $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices = null;
                $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures = null;
                $scope.currentFinancialObj.PercentToProgramServices = null;
                $rootScope.isGlobalEdited = false;
            };

            $scope.resetFinancialInfo = function () {
                //$scope.charityFinancialInfo.shortFiscalYearEntity.FiscalStartDate = null,
                //$scope.charityFinancialInfo.shortFiscalYearEntity.FiscalEndDate = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.BeginingGrossAssetsForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.EndingGrossAssetsForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.PercentToProgramServicesForShortFY = null
                //$scope.charityFinancialInfo.IsShortFiscalYear = false
            };

            //check Accounting year endat date is greater than current date
            $scope.validateFinancialDates = function () {

                if ($scope.charityFinancialInfo.BusinessFiling!=null && $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == "CLOSE CHARITABLE ORGANIZATION") {
                    var currentDate = new Date();
                    var newDate = new Date($scope.charityFinancialInfo.AccountingyearEndingDate);
                    if ($scope.charityFinancialInfo.IsFIFullAccountingYear) {
                        if (newDate > currentDate) {
                            $scope.charityFinancialInfo.IsDateEditable = true;
                            $scope.charityFinancialInfo.BeginingGrossAssets = null;
                            $scope.charityFinancialInfo.EndingGrossAssets = null;
                            $scope.charityFinancialInfo.RevenueGDfromSolicitations = null;
                            $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices = null;
                            $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources = null;
                            $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures = null;
                            $scope.charityFinancialInfo.AccountingyearBeginningDate = null;
                            $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                        }
                    }
                    else {
                        var newDate = new Date($scope.charityFinancialInfo.FirstAccountingyearEndDate);
                        if (newDate > currentDate) {
                            $scope.charityFinancialInfo.IsDateEditable = true;
                            $scope.charityFinancialInfo.FirstAccountingyearEndDate = null;
                        }
                    }
                }

            };

            $scope.$watch("charityFinancialInfo.AccountingyearEndingDate", function () {
                if (typeof ($scope.charityFinancialInfo.BusinessFiling) != typeof (undefined) && $scope.charityFinancialInfo.BusinessFiling != null && $scope.charityFinancialInfo.IsFIFullAccountingYear && ($scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION REGISTRATION'
                            || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION OPTIONAL REGISTRATION'
                             || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION AMENDMENT' || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION OPTIONAL AMENDMENT')) {
                    if (typeof ($scope.charityFinancialInfo.AccountingyearEndingDate) != typeof (undefined) && $scope.charityFinancialInfo.AccountingyearEndingDate != null && $scope.charityFinancialInfo.AccountingyearEndingDate != "") {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.accDate = wacorpService.checkAccYearEndDateForReg($scope.charityFinancialInfo.AccountingyearEndingDate, true);
                    }
                }
            });

            $scope.$watch("charityFinancialInfo.FirstAccountingyearEndDate", function () {
                if (!$scope.charityFinancialInfo.IsFIFullAccountingYear && typeof ($scope.charityFinancialInfo.BusinessFiling) != typeof (undefined) && $scope.charityFinancialInfo.BusinessFiling != null && ($scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION REGISTRATION' || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION OPTIONAL REGISTRATION'
                    || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION AMENDMENT' || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION OPTIONAL AMENDMENT')) {
                    if (typeof ($scope.charityFinancialInfo.FirstAccountingyearEndDate) != typeof (undefined) && $scope.charityFinancialInfo.FirstAccountingyearEndDate != null && $scope.charityFinancialInfo.FirstAccountingyearEndDate != "") {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.accDate = wacorpService.checkAccYearEndDateForReg($scope.charityFinancialInfo.FirstAccountingyearEndDate, false);
                        if (typeof ($scope.charityFinancialInfo.BusinessFiling) != typeof (undefined) && $scope.charityFinancialInfo.BusinessFiling != null && ($scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION REGISTRATION'
                            || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION OPTIONAL REGISTRATION' ||
                            $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION AMENDMENT' || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION OPTIONAL AMENDMENT')) {
                            if (!$scope.accDate)
                                calculateFAYEDRenewalDate(); // calculateFAYEDRenewalDate method is available in this file only.
                            else
                                $scope.newRenewalDate = "";
                        }
                    }
                    else
                        $scope.newRenewalDate = "";
                }
                $scope.validateFinancialDates(); // validateFinancialDates method is available in this file only.
            });


            $scope.$watch('charityFinancialInfo.AccountingyearEndingDate', function () {
                if ($scope.charityFinancialInfo.AccountingyearEndingDate != null && typeof ($scope.charityFinancialInfo.AccountingyearEndingDate) != typeof (undefined) && ($scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION AMENDMENT' || $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION OPTIONAL AMENDMENT')) {
                    //var isFinSectionMandetory = wacorpService.isFinancialMandetory($scope.charityFinancialInfo.AccountingyearEndingDate);
                    var isFinSectionMandetory = false;
                    if (isFinSectionMandetory) {
                        $scope.isMandetory = true;
                    }
                    else {
                        $scope.isMandetory = false;
                    }
                }
            });

            function calculateFAYEDRenewalDate() {
                var value = $scope.charityFinancialInfo.FirstAccountingyearEndDate;
                if (value != null && value != undefined && value != "") {
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultDate = lastDayWithSlashes;
                        $scope.newRenewalDate = "Your Renewal Date is: " + resultDate;

                    }
                }
                else {
                    $scope.newRenewalDate = "";
                }
            }
            //$scope.showEndDateErrorMessage = function () {
            //    var _flag = false;
            //    _flag = $scope.charityFinancialInfo.IsFIFullAccountingYear
            //                && $scope.charityFinancialInfo.AccountingyearEndingDate != null && $scope.charityFinancialInfo.AccountingyearEndingDate != undefined
            //                && (new Date($scope.charityFinancialInfo.AccountingyearEndingDate) < new Date($scope.endCurrentDate));
            //    return _flag;
            //};
        },
    };
});
wacorpApp.directive('commercialFundraisers', function () {

    return {
        templateUrl: 'ng-app/directives/CFT/CommercialFundraisers/_CommercialFundraisers.html',
        restrict: 'A',
        scope: {
            commercialFundraisers: '=?commercialFundraisers',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            isAmendfsc: '=?isAmendfsc'
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.showFundraiserSearchValidation = false;
            $scope.showFRAddValidation = false;
            $scope.isReview = $scope.isReview || false;
            $scope.isAmendfsc = $scope.isAmendfsc || false;
            $scope.messages = messages;
            $scope.addHideFundraiser = "Add New Fundraiser";
            $scope.showNewFundraiserSection = false;
            $scope.search = getFundraiserList;
            $scope.isButtonSerach = false;
            var criteria = null;
            //$scope.commercialFundraisers.FundraisersList = $scope.commercialFundraisers.FundraisersList || [];

            //$scope.commercialFundraisers.IsCommercialFundraisersContributionsInWA = $scope.commercialFundraisers.IsCommercialFundraisersContributionsInWA||false;

            $scope.fundRaiser = {
                CFTId: constant.ZERO, FundRaiserID: constant.ZERO, FEINNumber: "", UBINumber: "", EntityName: "", IsNewCFTFundraiser: false, Status: '', CFTStatus: '', StatusId: '',
                EntityMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }
            }

            var fundRaiserScopeData = {
                CFTId: constant.ZERO, FundRaiserID: constant.ZERO, FEINNumber: "", UBINumber: "", EntityName: "", IsNewCFTFundraiser: false, Status: '',
                EntityMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }
            }

            var fundRaiserResetScope = {
                CFTId: constant.ZERO, FundRaiserID: constant.ZERO, FEINNumber: "", UBINumber: "", EntityName: "", IsNewCFTFundraiser: false, Status: '',
                EntityMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }
            }
            $scope.fundraiserSearchCriteria = { FundraiserName: "", FundraiserID: "", FEINNo: "", UBINumber: "", RegistrationNumber: "", Type: "", PageID: constant.ONE, PageCount: constant.TEN, ID: "" };
            $scope.fundraiserSearchCriteria.Type = "FundOrgName";
            $scope.AddFundraiser = function () {
                $scope.IsAddNewFundraiser = true;
                $("#divFundraisersList").modal('toggle');
                if ($scope.commercialFundraisers.BusinessFiling.FilingTypeName == 'FUNDRAISING SERVICE CONTRACT REGISTRATION') {
                    $scope.addHideFundraiser = "Add New Subcontractor";
                }
                else {
                    $scope.addHideFundraiser = "Add New Fundraiser";
                }

            }

            //Search Fundraiser -- start
            $scope.searchFundraiser = function (searchform) {
                $scope.showFundraiserSearchValidation = true;
                if ($scope.fundraisersForm.searchform.$valid) {
                    $scope.showFundraiserSearchValidation = false;
                    $scope.selectedFundraiser = undefined;
                    $scope.isButtonSerach = false;
                    getFundraiserList(constant.ZERO); // getFundraiserList method is available in this file only.
                    $("#divFundraisersList").modal('toggle');
                }
            };

            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.fundraiserSearchCriteria.UBINumber = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.fundraiserSearchCriteria.UBINumber = pastedText;
                    });
                }
            };

            $scope.$watch('fundraiserInfo', function () {
                if ($scope.fundraiserInfo == undefined)
                    return;
                if ($scope.fundraiserInfo.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);

            function getFundraiserList(page) {
                page = page || constant.ZERO;
                $scope.setCriteria($scope.fundraiserSearchCriteria.Type);

                $scope.fundraiserSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                var data = angular.copy($scope.fundraiserSearchCriteria);
                $scope.isButtonSerach = page == 0;
                data.ID = angular.copy($scope.isButtonSerach ? ($scope.fundraiserSearchCriteria.RegistrationNumber || $scope.fundraiserSearchCriteria.FEINNo
                                                                || $scope.fundraiserSearchCriteria.UBINumber || $scope.fundraiserSearchCriteria.FundraiserName) : $scope.searchval);
                if (criteria == null) {
                    criteria = {};
                    criteria.SearchCriteria = $scope.fundraiserSearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.fundraiserSearchCriteria.PageID;
                    criteria.PageCount = 10;
                }
                else {
                    criteria.SearchCriteria = $scope.fundraiserSearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.fundraiserSearchCriteria.PageID;
                    criteria.PageCount = 10;
                }

                if (criteria.SearchCriteria == "FundRegNumber") {
                    criteria.RegistrationNumber = criteria.SearchValue;
                    criteria.FEINNo = null;
                    criteria.UBINumber = null;
                    criteria.EntityName = null;
                }
                else if (criteria.SearchCriteria == "FundFEINNo") {
                    criteria.FEINNo = criteria.SearchValue;
                    criteria.UBINumber = null;
                    criteria.RegistrationNumber = null;
                    criteria.EntityName = null;
                }
                else if (criteria.SearchCriteria == "FundUBINo") {
                    criteria.UBINumber = criteria.SearchValue;
                    criteria.FEINNo = null;
                    criteria.RegistrationNumber = null;
                    criteria.EntityName = null;
                } else {
                    criteria.EntityName = criteria.SearchValue;
                    criteria.FEINNo = null;
                    criteria.UBINumber = null;
                    criteria.RegistrationNumber = null;
                }

                //var criteria = {
                //    SearchCriteria: $scope.fundraiserSearchCriteria.Type,
                //    RegistrationNumber: $scope.fundraiserSearchCriteria.RegistrationNumber,
                //    FEINNo: $scope.fundraiserSearchCriteria.FEINNo,
                //    UBINumber: $scope.fundraiserSearchCriteria.UBINumber,
                //    EntityName: $scope.fundraiserSearchCriteria.FundraiserName,
                //    PageID: page == constant.ZERO ? constant.ONE : page + constant.ONE, PageCount: constant.TEN
                //};
                // FundraiserSearchForCharities method is available in constants.js
                wacorpService.post(webservices.CFT.FundraiserSearchForCharities, criteria,
                    function (response) {
                        if (response.data != null) {
                            $scope.fundraiserInfo = angular.copy(response.data);
                            //$scope.clearSearch();
                            if ($scope.isButtonSerach && response.data.length > 0) {
                                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                                $scope.pagesCount = response.data.length < $scope.fundraiserSearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                                $scope.totalCount = totalcount;
                                $scope.searchval = criteria.SearchValue;
                                $scope.SearchCriteria = criteria.SearchCriteria;
                                criteria = response.data[constant.ZERO].Criteria;
                            }
                            $scope.page = page;
                        }
                        else
                            // Folder Name: app Folder
                            // Alert Name: noDataFound method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.noDataFound);
                        //$scope.clearSearch();
                    },
                    function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    }
                );
            }

            $scope.setCriteria = function (value) {
                switch (value)
                {
                    case "FundOrgName":
                        $scope.fundraiserSearchCriteria.RegistrationNumber = null;
                        $scope.fundraiserSearchCriteria.FEINNo = null;
                        $scope.fundraiserSearchCriteria.UBINumber = null;
                        break;
                    case "FundFEINNo":
                        $scope.fundraiserSearchCriteria.UBINumber = null;
                        $scope.fundraiserSearchCriteria.RegistrationNumber = null;
                        $scope.fundraiserSearchCriteria.FundraiserName = null;
                        break;
                    case "FundUBINo":
                        $scope.fundraiserSearchCriteria.RegistrationNumber = null;
                        $scope.fundraiserSearchCriteria.FEINNo = null;
                        $scope.fundraiserSearchCriteria.FundraiserName = null;
                        break;
                    case "FundRegNumber":
                        $scope.fundraiserSearchCriteria.UBINumber = null;
                        $scope.fundraiserSearchCriteria.FEINNo = null;
                        $scope.fundraiserSearchCriteria.FundraiserName = null;
                        break;

                }
            };

            $scope.clearSearch = function () {
                $scope.fundraiserSearchCriteria.FundraiserName = "";
                $scope.fundraiserSearchCriteria.FEINNo = "";
                $scope.fundraiserSearchCriteria.UBINumber = "";
                $scope.fundraiserSearchCriteria.RegistrationNumber = "";
            }
            //On select fundraiser from fundraisers list
            $scope.onSelectFundraiser = function (selectFundraiser) {
                $scope.selectedFundraiser = undefined;
                $scope.selectedFundraiser = selectFundraiser;
            };

            //Add Search Fundraiser
            $scope.addSearchFundraiser = function () {
                if ($scope.selectedFundraiser && $scope.selectedFundraiser.FundraiserID != constant.ZERO) {
                    $scope.fundRaiser.FundRaiserID = $scope.selectedFundraiser.FundRaiserID;
                    $scope.fundRaiser.FEINNumber = $scope.selectedFundraiser.FEINNumber;
                    $scope.fundRaiser.UBINumber = $scope.selectedFundraiser.UBINumber;
                    $scope.fundRaiser.EntityName = $scope.selectedFundraiser.EntityName;
                    $scope.fundRaiser.EntityMailingAddress = $scope.selectedFundraiser.EntityMailingAddress;
                    $scope.fundRaiser.Status = principalStatus.INSERT;
                    $scope.fundRaiser.CFTStatus = $scope.selectedFundraiser.Status;
                    $scope.fundRaiser.StatusId = $scope.selectedFundraiser.StatusId;
                    $scope.fundRaiser.IsNewCFTFundraiser = false;
                    $scope.commercialFundraisers.FundraisersList.push($scope.fundRaiser);
                    $scope.showNewFundraiserSection = false;
                    $scope.resetFundraiser(); // resetFundraiser method is available in this file only
                    $("#divFundraisersList").modal('toggle');
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: selectFundraiser method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.FundraiserSearch.selectFundraiser);
                }
            };

            //Search Fundraiser -- End

            ///Add/Edit/Delete New Fundraiser - Start
            //Reset the fundraiser charitable organization
            $scope.resetFundraiser = function () {
                $scope.fundRaiser = angular.copy(fundRaiserScopeData);
                $scope.showErrorMessage = false;
                if ($scope.commercialFundraisers.BusinessFiling.FilingTypeName == 'FUNDRAISING SERVICE CONTRACT REGISTRATION') {
                    $scope.addHideFundraiser = "Add New Subcontractor";
                }
                else {
                    $scope.addHideFundraiser = "Add New Fundraiser";
                }
            };

            $scope.ShowHideAddNewFundraiser = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsAddNewFundraiser = $scope.IsAddNewFundraiser ? false : true;
                if ($scope.commercialFundraisers.BusinessFiling.FilingTypeName == 'FUNDRAISING SERVICE CONTRACT REGISTRATION') {
                    $scope.addHideFundraiser = $scope.IsAddNewFundraiser ? "Add New Subcontractor" : "Cancel Subcontractor";
                }
                else {
                    $scope.addHideFundraiser = $scope.IsAddNewFundraiser ? "Add New Fundraiser" : "Cancel Fundraiser";
                }
            }
            $scope.AddNewFundraiser = function (fundraiserForm) {
                $scope.showFRAddValidation = true;

                $scope.fundRaiser.EntityMailingAddress.StreetAddress1 = (($scope.fundRaiser.EntityMailingAddress.StreetAddress1 != null && $scope.fundRaiser.EntityMailingAddress.StreetAddress1.trim() == "" || $scope.fundRaiser.EntityMailingAddress.StreetAddress1 == undefined) ? $scope.fundRaiser.EntityMailingAddress.StreetAddress1 = null : $scope.fundRaiser.EntityMailingAddress.StreetAddress1.trim());
                if (!$scope.fundRaiser.EntityMailingAddress.StreetAddress1) {
                    $scope.fundraisersForm.fundraiserForm.CFTAddress.StreetAddress1.$setValidity("text", false);
                }
                else {
                    $scope.fundraisersForm.fundraiserForm.CFTAddress.StreetAddress1.$setValidity("text", true);
                }

                if ($scope.fundraisersForm[fundraiserForm].$valid) {
                    $scope.showFRAddValidation = false;
                    if ($scope.fundRaiser.CFTId != 0) {
                        angular.forEach($scope.commercialFundraisers.FundraisersList, function (fundraiser) {
                            if (fundraiser.CFTId == $scope.fundRaiser.CFTId) {
                                $scope.fundRaiser.EntityMailingAddress.FullAddress = wacorpService.fullAddressService($scope.fundRaiser.EntityMailingAddress);
                                angular.copy($scope.fundRaiser, fundraiser);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.commercialFundraisers.FundraisersList, function (fundraiser) {
                            if (maxId == constant.ZERO || fundraiser.FundRaiserID > maxId)
                                maxId = fundraiser.FundRaiserID;
                        });
                        $scope.fundRaiser.FundRaiserID = ++maxId;
                        $scope.fundRaiser.IsNewCFTFundraiser = true;
                        $scope.fundRaiser.EntityMailingAddress.FullAddress = wacorpService.fullAddressService($scope.fundRaiser.EntityMailingAddress);
                        $scope.fundRaiser.Status = principalStatus.INSERT;
                        $scope.commercialFundraisers.FundraisersList.push($scope.fundRaiser);
                    }
                    $scope.resetFundraiser(); // resetFundraiser method is available in this file only.
                    $scope.IsAddNewFundraiser = false;
                }
                $scope.showNewFundraiserSection = false;
            }

            //Edit fundraiser charitable organization data
            $scope.editCFTFundRaiser = function (fundraiserData) {
                $scope.IsAddNewFundraiser = true;
                fundraiserData.EntityMailingAddress.Country = fundraiserData.EntityMailingAddress.Country || codes.USA;
                fundraiserData.EntityMailingAddress.State = fundraiserData.EntityMailingAddress.State || codes.USA;
                if (fundraiserData.Status != principalStatus.INSERT)
                    fundraiserData.Status = principalStatus.UPDATE;
                $scope.fundRaiser = angular.copy(fundraiserData);
                if ($scope.commercialFundraisers.BusinessFiling.FilingTypeName == 'FUNDRAISING SERVICE CONTRACT REGISTRATION') {
                    $scope.addHideFundraiser = "Update Subcontractor";
                }
                else {
                    $scope.addHideFundraiser = "Update Fundraiser";
                }
                $scope.showNewFundraiserSection = true;
            };

            //Delete fundraiser charitable organization data
            $scope.deleteCFTFundRaiser = function (fundraiserData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (fundraiserData.CFTId <= 0) {
                        var index = $scope.commercialFundraisers.FundraisersList.indexOf(fundraiserData);
                        $scope.commercialFundraisers.FundraisersList.splice(index, 1);
                    }
                    else
                        fundraiserData.Status = principalStatus.DELETE;
                    $scope.FundCount = 0;
                    angular.forEach($scope.commercialFundraisers.FundraisersList, function (fundraiser) {
                        if (fundraiser.Status != "D") {
                            $scope.FundCount++;
                        }
                    });
                    $scope.resetFundraiser();
                    $scope.showNewFundraiserSection = true;
                    $scope.IsAddNewFundraiser = false;
                });
            };

            //Clear new the Fundraiser Information
            $scope.clearFRDetails = function () {
                $scope.fundRaiser = angular.copy(fundRaiserResetScope);
                $scope.selectedFundraiser = angular.copy(fundRaiserResetScope);
                $scope.IsAddNewFundraiser = false;
            };

            //selection of fundraiser
            $scope.resetFundSelection = function (flag, count) {
                if (!flag && count.length > 0) {
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.commercialFundraisers.FundraisersList.filesDeleteConfirm, function () {
                        angular.forEach($scope.commercialFundraisers.FundraisersList, function (value, data) {
                            if (value.CFTId > 0) {
                                value.Status = principalStatus.DELETE;
                            }
                            else {
                                var index = $scope.commercialFundraisers.FundraisersList.indexOf(value);
                                $scope.commercialFundraisers.FundraisersList.splice(index, 1);
                            }
                        });
                        $scope.commercialFundraisers.IsCommercialFundraisersContributionsInWA = false;
                        //$scope.IsAddNewFundraiser = false;
                        //$scope.commercialFundraisers.FundraisersList = [];
                    },
                      function () {
                          $scope.commercialFundraisers.IsCommercialFundraisersContributionsInWA = true;
                      }
                                   );

                }
            };

            $scope.closeFundInfo = function () {
                $('#divFundraisersList').modal('toggle');
            };

            //copypaste Fein Number
            $scope.setPastedFeinNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.fundraiserSearchCriteria.FEINNo = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.fundraiserSearchCriteria.FEINNo = pastedText;
                    });
                }
            };

        },
    };
});
wacorpApp.directive('enrollToCfd', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/EnrollToCFD/_EnrollToCFD.html',
        restrict: 'A',
        scope: {
            enrollToCfdInfo: '=?enrollToCfdInfo',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isReview = $scope.isReview || false;
            $scope.messages = messages;
            $scope.enrollToCfdInfo.AKANamesList = $scope.enrollToCfdInfo.AKANamesList || [];
            $scope.enrollToCfdInfo.CharityAkaInfoEntityList = $scope.enrollToCfdInfo.CharityAkaInfoEntityList || [];
            $scope.enrollToCfdInfo.CharityAkaInfoEntity = $scope.enrollToCfdInfo.CharityAkaInfoEntity || {};

            $scope.isNeedValidation = function () {
                return $scope.showErrorMessage || false;
            };

            $scope.showAKADetails = function () {
                $scope.$broadcast('editChangeData', $scope.enrollToCfdInfo.AKASolicitNameId);
            }

            // multi dropdown settings
            $scope.dropdownsettings = {
                scrollableHeight: '200px',
                key: "Value",
                value: "Key",
                scrollable: true,
                isKeyList: false,
                selectall: false               
            };

        },

    };
});
wacorpApp.directive('enrolltoCfdDetails', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/EnrollToCFD/_EnrollToCFDDetails.html',
        restrict: 'A',
        scope: {
            charitiesAkaInfoList: '=?charitiesAkaInfoList',
            entityDetailInfo: '=?entityDetailInfo',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, lookupService, $rootScope) {
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.showEnrollToCfdDetails = false;
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add";
            $scope.messages = messages;
            $scope.countyOptions = [];
            $scope.serviceOptions = [];
            var settingScope = { scrollableHeight: '300px', scrollable: true, key: "Key", value: "Value", isKeyList: false, width: 'multiselect-parent col-md-10' };
            $scope.settings = $scope.settings ? angular.extend(settingScope, $scope.settings) : angular.copy(settingScope);

            // multi dropdown settings
            $scope.dropdownsettings = {
                scrollableHeight: '300px',
                key: "Value",
                value: "Key",
                scrollable: true,
                isKeyList: false,
                selectall: false,
                width: 'multiselect-parent col-md-10'
            };

            $scope.charitiesAkaInfoList = $scope.charitiesAkaInfoList || [];

            $scope.charityAkaInfo = {
                ID: constant.ZERO, SequenceNo: constant.ZERO, AKASolicitNameId: constant.ZERO, AkaName: '', IsDevelopmentInfo: false, IsSameasCharity: false, IsAKA: false,
                DevInfoFirstName: "", DevInfoLastName: "", DevInfoEmailAddress: "", DevInfoConfirmEmailAddress: "", DevInfoPhoneNumber: "",
                FinancialInfoFirstName: "", FinancialInfoLastName: "", FinancialInfoEmailAddress: "", FinancialConfirmEmailAddress: "", FinancialInfoPhoneNumber: "",
                WebSite: "", ProgramDescription: "", CharityVendorId: null, CountiesServedId: [], CategoryOfServiceId: [], Status:""
            };

            var charityAKAInfoScope = {
                ID: constant.ZERO, SequenceNo: constant.ZERO, AKASolicitNameId: constant.ZERO, AkaName: '', IsDevelopmentInfo: false, IsSameasCharity: false, IsAKA: false,
                DevInfoFirstName: "", DevInfoLastName: "", DevInfoEmailAddress: "", DevInfoConfirmEmailAddress: "", DevInfoPhoneNumber: "",
                FinancialInfoFirstName: "", FinancialInfoLastName: "", FinancialInfoEmailAddress: "", FinancialConfirmEmailAddress: "", FinancialInfoPhoneNumber: "",
                WebSite: "", ProgramDescription: "", CharityVendorId: null, CountiesServedId: [], CategoryOfServiceId: [], Status: ""
            };
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            lookupService.countiesList(function (response) { $scope.countyOptions = response.data; });
            lookupService.trustPurposeList(function (response) { $scope.serviceOptions = response.data; });

            //Reset the charity aka information
            $scope.resetCharityAKAInfo = function () {
                $scope.charityAkaInfo = angular.copy(charityAKAInfoScope);
                $scope.showEnrollToCfdDetails = false;
                $scope.addbuttonName = "Add";
                $scope.charityAkaInfo.AKASolicitNameId = '';
            };

            //Add charity aka information
            $scope.AddAKAInformation = function (enrollToCFDDetails) {
                $scope.showEnrollToCfdDetails = true;
                if ($scope['enrollToCFDDetails'].$valid &&  $scope.charityAkaInfo.CountiesServedId.length > 0
                        && $scope.charityAkaInfo.CategoryOfServiceId.length > 0 && $scope.charityAkaInfo.CategoryOfServiceId.length <= 3) {
                    $scope.showEnrollToCfdDetails = false;
                    if ($scope.charityAkaInfo.SequenceNo != "") {
                        angular.forEach($scope.charitiesAkaInfoList, function (akaInfo) {
                            if (akaInfo.SequenceNo == $scope.charityAkaInfo.SequenceNo) {
                                angular.copy($scope.charityAkaInfo, akaInfo);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.charitiesAkaInfoList, function (officer) {
                            if (maxId == constant.ZERO || officer.SequenceNo > maxId)
                                maxId = officer.SequenceNo;
                        });
                        $scope.charityAkaInfo.SequenceNo = ++maxId;
                        $scope.charityAkaInfo.AKASolicitNameId = $scope.entityDetailInfo.AKASolicitNameId;                      
                        $scope.charityAkaInfo.Status = principalStatus.INSERT;
                        angular.forEach($scope.entityDetailInfo.AKANamesList, function (akaname) {
                            if (akaname.SequenceNo == $scope.charityAkaInfo.AKASolicitNameId) {
                                $scope.charityAkaInfo.AkaName = akaname.AKAName;
                            }
                        });
                        $scope.charitiesAkaInfoList.push($scope.charityAkaInfo);
                    }
                    $scope.entityDetailInfo.AKASolicitNameId = '';
                    $scope.resetCharityAKAInfo(); // resetCharityAKAInfo method is available in this file only.
                }

            };

            ////Edit fundraiser charitable organization data
            $scope.editCharityAKAInformation = function (charityAKAInfoData) {
                $scope.charityAkaInfo = angular.copy(charityAKAInfoData);
                $scope.charityAkaInfo.AKASolicitNameId = $scope.charityAkaInfo.AKASolicitNameId.toString();
                $scope.entityDetailInfo.AKASolicitNameId = $scope.charityAkaInfo.AKASolicitNameId;
                if ($scope.charityAkaInfo.Status != principalStatus.INSERT) {
                    $scope.charityAkaInfo.Status = principalStatus.UPDATE;
                }
                $scope.addbuttonName = "Update";
            };

            //Delete fundraiser charitable organization data
            $scope.deleteCharityAKAInfo = function (charityAKAInfoData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (charityAKAInfoData.Status = principalStatus.INSERT) {
                        var index = $scope.charitiesAkaInfoList.indexOf(charityAKAInfoData);
                        $scope.charitiesAkaInfoList.splice(index, 1);
                    }
                    else {
                        charityAKAInfoData.Status = principalStatus.DELETE;
                        $scope.resetCharityAKAInfo(); // resetCharityAKAInfo method is available in this file only.
                    }
                });
            };

            // Clear all controls data
            $scope.clearCharityAKAInfo = function () {
                $scope.resetCharityAKAInfo(); // resetCharityAKAInfo method is available in this file only.
            };

            //Copy Charity Contact Information
            $scope.CopyFromCharityInfo = function () {
                if ($scope.charityAkaInfo.IsSameasCharity) {
                   // $scope.charityAkaInfo.DevInfoFirstName = angular.copy($scope.entityDetailInfo.EntityName);
                    //$scope.charityAkaInfo.DevInfoLastName = angular.copy($scope.entityDetailInfo.DevInfoLastName);
                    $scope.charityAkaInfo.DevInfoEmailAddress = angular.copy($scope.entityDetailInfo.EntityEmailAddress);
                    $scope.charityAkaInfo.DevInfoConfirmEmailAddress = angular.copy($scope.entityDetailInfo.EntityConfirmEmailAddress);
                    $scope.charityAkaInfo.DevInfoPhoneNumber = angular.copy($scope.entityDetailInfo.EntityPhoneNumber);
                }
                else {
                    $scope.charityAkaInfo.DevInfoFirstName = angular.copy(charityAKAInfoScope.DevInfoFirstName);
                    $scope.charityAkaInfo.DevInfoLastName = angular.copy(charityAKAInfoScope.DevInfoLastName);
                    $scope.charityAkaInfo.DevInfoEmailAddress = angular.copy(charityAKAInfoScope.DevInfoEmailAddress);
                    $scope.charityAkaInfo.DevInfoConfirmEmailAddress = angular.copy(charityAKAInfoScope.DevInfoConfirmEmailAddress);
                    $scope.charityAkaInfo.DevInfoPhoneNumber = angular.copy(charityAKAInfoScope.DevInfoPhoneNumber);
                }
            };

            //Copy Development Contact Information
            $scope.CopyFromDevelopmentInfo = function () {
                if ($scope.charityAkaInfo.IsSameasDevelopment) {
                    $scope.charityAkaInfo.FinancialInfoFirstName = angular.copy($scope.charityAkaInfo.DevInfoFirstName);
                    $scope.charityAkaInfo.FinancialInfoLastName = angular.copy($scope.charityAkaInfo.DevInfoLastName);
                    $scope.charityAkaInfo.FinancialInfoEmailAddress = angular.copy($scope.charityAkaInfo.DevInfoEmailAddress);
                    $scope.charityAkaInfo.FinancialConfirmEmailAddress = angular.copy($scope.charityAkaInfo.DevInfoConfirmEmailAddress);
                    $scope.charityAkaInfo.FinancialInfoPhoneNumber = angular.copy($scope.charityAkaInfo.DevInfoPhoneNumber);
                }
                else {
                    $scope.charityAkaInfo.FinancialInfoFirstName = angular.copy(charityAKAInfoScope.FinancialInfoFirstName);
                    $scope.charityAkaInfo.FinancialInfoLastName = angular.copy(charityAKAInfoScope.FinancialInfoLastName);
                    $scope.charityAkaInfo.FinancialInfoEmailAddress = angular.copy(charityAKAInfoScope.FinancialInfoEmailAddress);
                    $scope.charityAkaInfo.FinancialConfirmEmailAddress = angular.copy(charityAKAInfoScope.FinancialConfirmEmailAddress);
                    $scope.charityAkaInfo.FinancialInfoPhoneNumber = angular.copy(charityAKAInfoScope.FinancialInfoPhoneNumber);
                }
            };

            $scope.$on('editChangeData', function (event, akaSolicitId) {
                var charityAKAInfoData = null;
                angular.forEach($scope.charitiesAkaInfoList, function (charityAka) {
                    if (charityAka.AKASolicitNameId == akaSolicitId) {
                        charityAKAInfoData = charityAka;
                    }
                });
                if (charityAKAInfoData != null) {
                    $scope.editCharityAKAInformation(charityAKAInfoData); // editCharityAKAInformation method is available in this file only
                }
            });
           
        },
    };
});
wacorpApp.directive('organizationSolicitServiceTypes', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/OrganizationSolicitServiceTypes/_OrganizationSolicitServiceTypes.html',
        restrict: 'A',
        scope: {
            solicitOptions: '=?solicitOptions',
            solicitModel: '=?solicitModel',
            dropdownsettings: '=?dropdownsettings',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, $rootScope, lookupService) {
            $scope.messages = messages;
            $scope.solicitOptions = $scope.solicitOptions || [];
            $scope.solicitModel = $scope.solicitModel || {};
            var settingScope = { scrollableHeight: '200px', scrollable: true, key: "Value", value: "Key", isKeyList: false, selectall: true };
            $scope.dropdownsettings = $scope.dropdownsettings ? angular.extend(settingScope, $scope.dropdownsettings) : angular.copy(settingScope);
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;

            $scope.Init = function () {
                $scope.selectedItems = [];
                var selectedItemsValue = [];
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.SolicitServiceTypes(function (response) {
                    $scope.solicitOptions = response.data;
                    if ($scope.solicitModel.ContributionServicesTypeId != null || $scope.solicitModel.ContributionServicesTypeId != undefined) {

                        $scope.solicitModel.ContributionServicesTypeId = Array.isArray($scope.solicitModel.ContributionServicesTypeId) ?
                        $scope.solicitModel.ContributionServicesTypeId : $scope.solicitModel.ContributionServicesTypeId.split(",");


                        $scope.solicitModel.ContributionServicesTypeId.filter(function (serviceType) {
                            for (var i = 0; i < response.data.length; i++) {
                                if (serviceType == response.data[i].Key) {
                                    $scope.selectedItems.push(response.data[i]);
                                    selectedItemsValue.push(response.data[i].Value);
                                    break;
                                }
                            }
                        });
                        $scope.solicitModel.ContributionServicesOtherComments = "";
                        $scope.solicitModel.ContributionServicesOtherComments = selectedItemsValue.join(',');
                        $scope.solicitModel.ContributionServicesTypes = "";
                        $scope.solicitModel.ContributionServicesTypes = $scope.solicitModel.ContributionServicesOtherComments;
                    }
                    
                });              
            };
        },
    };
});
wacorpApp.directive('financialInfoStates', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FinancialInfoStates/_FinancialInfoStates.html',
        restrict: 'A',
        scope: {
            statesOptions: '=?statesOptions',
            statesModel: '=?statesModel',
            dropdownsettings: '=?dropdownsettings',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, $rootScope, lookupService) {
            $scope.statesOptions = $scope.statesOptions || [];
            $scope.statesModel = $scope.statesModel || {};
            var settingScope = { scrollableHeight: '200px', scrollable: true, key: "Value", value: "Key", isKeyList: false, selectall: true };
            $scope.dropdownsettings = $scope.dropdownsettings ? angular.extend(settingScope, $scope.dropdownsettings) : angular.copy(settingScope);
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;

            $scope.Init = function () {
                $scope.messages = messages;
                $scope.selectedItems = [];
                var selectedStatesValue = [];
                var lookupStatesParams = { params: { name: 'JurisdictionStates' } };
                wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
                    $scope.statesOptions = response.data;

                    if ($scope.statesModel.FinancialInfoStateId != null || $scope.statesModel.FinancialInfoStateId != undefined) {
                        $scope.statesModel.FinancialInfoStateId = Array.isArray($scope.statesModel.FinancialInfoStateId) ?
                            $scope.statesModel.FinancialInfoStateId : $scope.statesModel.FinancialInfoStateId.split(",");
                        $scope.statesModel.FinancialInfoStateId.filter(function (state) {
                            for (var i = 0; i < response.data.length; i++) {
                                if (state == response.data[i].Key) {
                                    $scope.selectedItems.push(response.data[i]);
                                    selectedStatesValue.push(response.data[i].Value);
                                    break;
                                }
                            }
                        });
                        $scope.statesModel.FinancialInfoStateDesc = "";
                        $scope.statesModel.FinancialInfoStateDesc = selectedStatesValue.join(',');
                    };
                });
            };
        },
    };
});
wacorpApp.directive('fundraiserFinancialInfo', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FinancialInfo/_FundraiserFinancialInfo.html',
        restrict: 'A',
        scope: {
            financialInfoData: '=?financialInfoData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
            showFinancialHistory: '=?showFinancialHistory',
            financialBtn: '=?financialBtn',
            accDate: '=?accDate'
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope) {
            $scope.isFNameValid = true;
            $scope.isLNameValid = true;
            $scope.checkStartDate = false;
            $scope.messages = messages;
            $scope.Countries = [];
            $scope.States = [];
            $scope.ValidateFinancialEndDateMessage = false;
            $scope.addbuttonName = "Add";
            $scope.currentFinancialObj = {};
            $scope.isMandetory = true;
            $rootScope.isGlobalEdited = false

            //$scope.financialInfoData.AccStartDateMoreThanOneYear = true;



            var financialInfoScope = {
                HasOrganizationCompletedFullAccountingYear: false, AccountingYearBeginningDate: "", AccountingYearEndingDate: "", FirstAccountingYearEndDate: "",
                SolicitationComments: "", IsOrganizationCollectedContributionsInWA: false, ContributionServicesTypes: "", ContributionServicesTypeId: "",
                ContributionServicesOtherComments: "", IsRegisteredOutSideOfWashington: false, FinancialInfoStateId: "", FinancialInfoStateDesc: "",
                IsResponsibleForFundraisingInWA: "", BeginningGrossAssets: "", IsContributionServicesOther: false, CFTOfficersList: [],
                //BeginingGrossAssets: null, TotalDollarValueofGrossReceipts: null, EndingGrossAssets: null, ExpensesGDValueofAllExpenditures: null, PercentToProgramServices: null,
                AllContributionsReceived: null, AveragePercentToCharity: null, AmountOfFunds: null, OfficersHighPayList: [], AccStartDateMoreThanOneYear: false,
                OfficersHighPay: {
                    IsPayOfficers: true
                }, CFTFinancialHistoryList: [], BusinessFiling: { FilingTypeName: "" }, AccEndDateLessThanCurrentYear: false,
                shortFiscalYearEntity: {
                    FiscalStartDate: "", FiscalEndDate: "", AllContributionsReceivedForShortFY: null, AveragePercentToCharityForShortFY: null, AmountOfFundsForShortFY: null
                }
            };

            angular.copy($scope.currentFinancialObj, financialInfoScope);

            //if ($scope.financialInfoData != null && $scope.financialInfoData != undefined && $scope.financialInfoData.BusinessFiling != null && $scope.financialInfoData.BusinessFiling != undefined && $scope.financialInfoData.BusinessFiling.FilingTypeName != 'COMMERCIAL FUNDRAISER AMENDMENT') {
            //    $scope.isMandetory = true;
            //}
            //else {
            //    $scope.isMandetory = false;
            //}

            $scope.OfficershighPayData = { ID: '', FirstName: '', LastName: '', SequenceNo: null, Status: '', IsPayOfficers: false, CreatedBy: null };

            $scope.OfficershighPayScopeData = { ID: '', FirstName: '', LastName: '', SequenceNo: null, Status: '', IsPayOfficers: false, CreatedBy: null };

            $scope.financialInfoData = $scope.financialInfoData ? angular.extend(financialInfoScope, $scope.financialInfoData) : angular.copy(financialInfoScope);

            //For Current Financial Info
            $scope.$watchGroup(['financialInfoData.AllContributionsReceived', 'financialInfoData.AmountOfFunds'], function () {

                var value1 = parseFloat($scope.financialInfoData.AmountOfFunds == null || $scope.financialInfoData.AmountOfFunds == '') ? 0 : $scope.financialInfoData.AmountOfFunds;
                var value2 = parseFloat($scope.financialInfoData.AllContributionsReceived == null || $scope.financialInfoData.AllContributionsReceived == '') ? 0 : $scope.financialInfoData.AllContributionsReceived;

                var percentage = null;
                if (value1 && value2)
                    percentage = ((value1 / value2) * 100).toFixed(2);
                else
                    percentage = null;

                if (isNaN(percentage) || percentage === 0)
                    $scope.financialInfoData.AveragePercentToCharity = null;
                else {
                    if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                        $scope.financialInfoData.AveragePercentToCharity = "-" + Math.round(percentage);
                    }
                    else {
                        $scope.financialInfoData.AveragePercentToCharity = Math.round(percentage);
                    }
                }
            }, true);

            //For History Financial Info
            $scope.$watchGroup(['currentFinancialObj.AllContributionsReceived', 'currentFinancialObj.AmountOfFunds'], function () {
                var value1 = parseFloat($scope.currentFinancialObj.AmountOfFunds == null || $scope.currentFinancialObj.AmountOfFunds == '') ? 0 : $scope.currentFinancialObj.AmountOfFunds;
                var value2 = parseFloat($scope.currentFinancialObj.AllContributionsReceived == null || $scope.currentFinancialObj.AllContributionsReceived == '') ? 0 : $scope.currentFinancialObj.AllContributionsReceived;
                var percentage = null;
                if (value1 && value2)
                    percentage = ((value1 / value2) * 100).toFixed(2);
                else
                    percentage = null;

                if (isNaN(percentage) || percentage === 0)
                    $scope.currentFinancialObj.AveragePercentToCharity = null;
                else {
                    if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                        $scope.currentFinancialObj.AveragePercentToCharity = "-" + Math.round(percentage);
                    } else {
                        $scope.currentFinancialObj.AveragePercentToCharity = Math.round(percentage);
                    }
                }
            }, true);

            //For Short Fiscal Financial Info
            $scope.$watchGroup(['financialInfoData.shortFiscalYearEntity.AllContributionsReceivedForShortFY', 'financialInfoData.shortFiscalYearEntity.AmountOfFundsForShortFY'], function () {
                if ($scope.financialInfoData.shortFiscalYearEntity != undefined && $scope.financialInfoData.shortFiscalYearEntity != null) {
                    var value1 = parseFloat($scope.financialInfoData.shortFiscalYearEntity.AmountOfFundsForShortFY == null || $scope.financialInfoData.shortFiscalYearEntity.AmountOfFundsForShortFY == '') ? 0 : $scope.financialInfoData.shortFiscalYearEntity.AmountOfFundsForShortFY;
                    var value2 = parseFloat($scope.financialInfoData.shortFiscalYearEntity.AllContributionsReceivedForShortFY == null || $scope.financialInfoData.shortFiscalYearEntity.AllContributionsReceivedForShortFY == '') ? 0 : $scope.financialInfoData.shortFiscalYearEntity.AllContributionsReceivedForShortFY;
                    var percentage = null;
                    if (value1 && value2)
                        percentage = ((value1 / value2) * 100).toFixed(2);
                    else
                        percentage = null;

                    if (isNaN(percentage) || percentage === 0)
                        $scope.financialInfoData.shortFiscalYearEntity.AveragePercentToCharityForShortFY = null;
                    else {
                        if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                            $scope.financialInfoData.shortFiscalYearEntity.AveragePercentToCharityForShortFY = "-" + Math.round(percentage);
                        } else {
                            $scope.financialInfoData.shortFiscalYearEntity.AveragePercentToCharityForShortFY = Math.round(percentage);
                        }
                    }
                }
            }, true);


            $scope.$watch('financialInfoData', function () {
                if ($scope.financialInfoData.SolicitationComments)
                {
                    if ($scope.financialInfoData.SolicitationComments.length > 500)
                    {
                        $scope.financialInfoData.SolicitationComments = $scope.financialInfoData.SolicitationComments.replace(/(\r\n|\n|\r)/gm, "");
                        $scope.financialInfoData.SolicitationComments = $scope.financialInfoData.SolicitationComments.substring(0, 500);
                    }
                }
            });

            //Get Countries List
            $scope.getCountries = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.countriesList(function (response) { $scope.Countries = response.data; });
            };


            //Get States List
            $scope.getStates = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.statesList(function (response) { $scope.States = response.data; });
            };

            $scope.getCountries(); // getCountries method is available in this file only
            $scope.getStates(); // getStates method is available in this file only

            var resultDate = "";
            $scope.CalculateEndDate = function () {
                if ($scope.financialInfoData.AccountingYearBeginningDate != null && $scope.financialInfoData.AccountingYearBeginningDate != "") {
                    var value = $scope.financialInfoData.AccountingYearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultDate = lastDayWithSlashes;
                        $scope.financialInfoData.AccountingYearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.financialInfoData.AccountingYearEndingDate = null;
                    }
                }

                if (typeof ($scope.financialInfoData.AccountingYearBeginningDate) != typeof (undefined)
                   && $scope.financialInfoData.AccountingYearBeginningDate != null
                   && typeof ($scope.financialInfoData.BusinessFiling) != typeof (undefined)
                   && $scope.financialInfoData.BusinessFiling != null && $scope.financialInfoData.CFTFinancialHistoryList.length > 0
                   && $scope.financialInfoData.BusinessFiling.FilingTypeName == 'COMMERCIAL FUNDRAISER AMENDMENT') {

                    if ($scope.financialInfoData.AccountingYearBeginningDate && $scope.financialInfoData.CurrentStartDateForAmendment) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        var val = wacorpService.checkDateValidity($scope.financialInfoData.CurrentEndDateForAmendment, $scope.financialInfoData.AccountingYearBeginningDate, $scope.financialInfoData.IsShortFiscalYear);
                        if (val == 'SFY') {
                            $scope.financialInfoData.IsShortFiscalYear = true;
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            var startDate = wacorpService.getShortYearStartDate($scope.financialInfoData.CurrentEndDateForAmendment);
                            $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate = wacorpService.dateFormatService(startDate);
                            var endDate = wacorpService.getShortYearEndDate($scope.financialInfoData.AccountingYearBeginningDate);

                            $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate = wacorpService.dateFormatService(endDate);
                            $scope.financialInfoData.AccStartDateMoreThanOneYear = false;
                            $scope.financialInfoData.AccEndDateLessThanCurrentYear = false;
                        } else if (val == 'SDgPnD') {
                            $scope.financialInfoData.AccEndDateLessThanCurrentYear = true;
                            $scope.financialInfoData.AccStartDateMoreThanOneYear = false;
                            $scope.financialInfoData.IsShortFiscalYear = false;
                            $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate = null;
                            $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate = null;
                        } else if (val == 'Y1Plus') {
                            $scope.financialInfoData.AccStartDateMoreThanOneYear = true;
                            $scope.financialInfoData.IsShortFiscalYear = false;
                            $scope.financialInfoData.AccEndDateLessThanCurrentYear = false;
                            $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate = null;
                            $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate = null;
                        } else {
                            $scope.financialInfoData.AccStartDateMoreThanOneYear = false;
                            $scope.financialInfoData.IsShortFiscalYear = false;
                            $scope.financialInfoData.AccEndDateLessThanCurrentYear = false;
                            $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate = null;
                            $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate = null;
                        }

                    }
                }

                $scope.CheckEndDate(); // CheckEndDate method is available in this file only
            };

            $scope.CheckEndDate = function () {
                if ($scope.financialInfoData.AccountingYearEndingDate != null && $scope.financialInfoData.AccountingYearBeginningDate != null) {
                    if (new Date($scope.financialInfoData.AccountingYearEndingDate) < new Date($scope.financialInfoData.AccountingYearBeginningDate)) {
                        $scope.ValidateFinancialEndDateMessage = true;
                    }
                    else
                        $scope.ValidateFinancialEndDateMessage = false;
                }
            };

            var resultHistoryDate = "";
            $scope.CalculateHistoryEndDate = function () {
                if ($scope.currentFinancialObj.AccountingYearBeginningDate != null && $scope.currentFinancialObj.AccountingYearBeginningDate != "") {
                    var value = $scope.currentFinancialObj.AccountingYearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultHistoryDate = lastDayWithSlashes;
                        $scope.currentFinancialObj.AccountingYearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idHisEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.currentFinancialObj.AccountingYearEndingDate = null;
                    }
                }
                //$scope.checkStartDate = wacorpService.checkDateValidity($scope.currentFinancialObj.AccountingYearBeginningDate, $scope.financialInfoData.CurrentEndDateForAmendment);
                $scope.CheckHistoryEndDate(); // CheckHistoryEndDate method is available in this file only
            };

            $scope.CheckHistoryEndDate = function () {
                if (new Date($scope.currentFinancialObj.AccountingYearEndingDate) < new Date($scope.currentFinancialObj.AccountingYearBeginningDate)) {
                    $scope.ValidateHistoryFinancialEndDateMessage = true;
                }
                else
                    $scope.ValidateHistoryFinancialEndDateMessage = false;
            };

            $scope.ValidateEndDate = function () {
                if (new Date($scope.financialInfoData.AccountingYearEndingDate) < new Date($scope.financialInfoData.AccountingYearBeginningDate)) {
                    $scope.ValidateFinancialEndDateMessage = true;
                }
                else
                    $scope.ValidateFinancialEndDateMessage = false;
            };


            $scope.clearFields = function (flag) {
                $scope.accDate = false;
                if (!flag) {
                    $scope.financialInfoData.isUpdated = false;
                    $scope.financialInfoData.AccountingYearBeginningDate = null;
                    $scope.financialInfoData.AccountingYearEndingDate = null;
                    $scope.financialInfoData.AllContributionsReceived = null;
                    $scope.financialInfoData.AveragePercentToCharity = null;
                    $scope.financialInfoData.AmountOfFunds = null;
                    $scope.financialInfoData.SolicitationComments = null;
                    calculateFAYEDRenewalDate(); // calculateFAYEDRenewalDate method is available in this file only
                }
                else {
                    $scope.financialInfoData.isUpdated = true;
                    //if ($scope.financialInfoData.BusinessFiling.FilingTypeName != 'COMMERCIAL FUNDRAISER AMENDMENT') {
                    //    $scope.financialInfoData.FirstAccountingYearEndDate = null;
                    //    $scope.newRenewalDate = "";
                    //}
                    $scope.financialInfoData.IsShortFiscalYear = false;
                }

            };

            $scope.addOfficerHighPay = function (officerHighPay) {
                $scope.isFNameValid = officerHighPay.FirstName != null && officerHighPay.FirstName != "" && officerHighPay.FirstName != undefined;
                $scope.isLNameValid = officerHighPay.LastName != null && officerHighPay.LastName != "" && officerHighPay.LastName != undefined;
                $scope.hasValues = officerHighPay.FirstName != null && officerHighPay.FirstName != "" && officerHighPay.FirstName != undefined && officerHighPay.LastName != null && officerHighPay.LastName != "" && officerHighPay.LastName != undefined ? true : false;
                if (!$scope.hasValues) {
                    return false;
                }
                else {
                    $scope.ValidateErrorMessage = false;
                    if ($scope.OfficershighPayData.SequenceNo != null && $scope.OfficershighPayData.SequenceNo != '' && $scope.OfficershighPayData.SequenceNo != 0) {
                        angular.forEach($scope.financialInfoData.OfficersHighPayList, function (highpayItem) {
                            if (highpayItem.SequenceNo == $scope.OfficershighPayData.SequenceNo) {
                                angular.copy($scope.OfficershighPayData, highpayItem);
                                $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.financialInfoData.OfficersHighPayList, function (highpayItem) {
                            if (maxId == constant.ZERO || highpayItem.SequenceNo > maxId)
                                maxId = highpayItem.SequenceNo;
                        });
                        $scope.OfficershighPayData.SequenceNo = ++maxId;
                        $scope.OfficershighPayData.Status = principalStatus.INSERT;
                        $scope.financialInfoData.OfficersHighPayList.push($scope.OfficershighPayData);
                        $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only
                    }
                    $scope.resetHighPay(); // resetHighPay method is available in this file only
                }
            };

            $scope.checkOfficersValidData = function (firstName, lastName) {
                 
                if (firstName)
                    $scope.isFNameValid = firstName != undefined && firstName != null && firstName != "" && firstName != " ";
                if (lastName)
                    $scope.isLNameValid = lastName != undefined && lastName != null && lastName != "" && lastName != " ";
            }

            $scope.resetHighPay = function () {
                $scope.OfficershighPayData = angular.copy($scope.OfficershighPayScopeData);
                $scope.addbuttonName = "Add";
            }

            $scope.checkHighpayCount = function () {
                $scope.Count = 0;
                angular.forEach($scope.financialInfoData.OfficersHighPayList, function (highpayItem) {

                    if (highpayItem.Status != "D") {
                        $scope.Count++;
                        if ($scope.Count >= 3) {
                            $scope.financialInfoData.OfficersHighPay.IsCountMax = true;
                        }
                        else {
                            $scope.financialInfoData.OfficersHighPay.IsCountMax = false;
                        }
                    }
                });
            };

            $scope.editOfficerHighPay = function (highPayActionData) {
                $scope.OfficershighPayData = angular.copy(highPayActionData);
                $scope.OfficershighPayData.Status = principalStatus.UPDATE;
                $scope.financialInfoData.OfficersHighPay.IsCountMax = false;
                //$scope.IsCountMax = false;
                $scope.addbuttonName = "Update";
            };

            $scope.deleteOfficerHighPay = function (highPayActionData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (highPayActionData.ID <= 0) {
                        var index = $scope.financialInfoData.OfficersHighPayList.indexOf(highPayActionData);
                        $scope.financialInfoData.OfficersHighPayList.splice(index, 1);
                    }
                    else
                        highPayActionData.Status = principalStatus.DELETE;

                    $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only
                    //if ($scope.financialInfoData.OfficersHighPayList.length == 0)
                    $scope.resetHighPay(); // resetHighPay method is available in this file only
                });
            };

            //$scope.resetSelection = function () {
            //    if ($scope.financialInfoData.OfficersHighPayList.length > 0) {
            //        wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
            //            angular.forEach($scope.financialInfoData.OfficersHighPayList, function (value, data) {
            //                if (value.ID > 0) {
            //                    value.Status = principalStatus.DELETE;

            //                }
            //                else {
            //                    var index = $scope.financialInfoData.OfficersHighPayList.indexOf(value);
            //                    $scope.financialInfoData.OfficersHighPayList.splice(index);
            //                }
            //            })
            //            $scope.OfficershighPayData.FirstName = '';
            //            $scope.OfficershighPayData.LastName = '';
            //            //$scope.ShowHighPayList = false;
            //            $scope.financialInfoData.OfficersHighPay.IsCountMax = false;
            //        }, function () {
            //            $scope.financialInfoData.IsRegisteredOutSideOfWashington = false;
            //        });
            //    }
            //};


            //CFT Financial History Methods

            $rootScope.$watch('isGlobalEdited', function (val) {
                $scope.isEdited = val;
                //if ($scope.isEdited) {
                //    $scope.financialInfoData.IsShortFiscalYear = false;
                //}
            });

            //$scope.$watch('financialInfoData.IsShortFiscalYear', function (val) {
            //    $scope.isEdited = val;
            //});

            //Add Financial History data

            //$scope.AddFinancialInfo = function (cftFinancialForm) {
            //    $scope.showErrorMessage = true;
            //    var isExpensesValid = ($scope.currentFinancialObj.AllContributionsReceived < $scope.currentFinancialObj.AmountOfFunds ? false : true);
            //    if ($scope[cftFinancialForm].$valid && isExpensesValid) {
            //        $scope.showErrorMessage = false;
            //        var maxId = constant.ZERO;
            //        angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (finInfo) {
            //            maxId += 1;
            //            //if (maxId == constant.ZERO || finInfo.SequenceNo > maxId)
            //            //    maxId = finInfo.SequenceNo;
            //        });
            //        var financialInfoObj = { };
            //        financialInfoObj.SequenceNo = ++maxId;
            //        financialInfoObj.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingYearBeginningDate;
            //        financialInfoObj.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingYearEndingDate;
            //        //financialInfoObj.BeginingGrossAssets = $scope.financialInfoData.BeginingGrossAssets;
            //        financialInfoObj.AllContributionsReceived = $scope.currentFinancialObj.AllContributionsReceived;
            //        financialInfoObj.AveragePercentToCharity = $scope.currentFinancialObj.AveragePercentToCharity;
            //        //financialInfoObj.TotalDollarValueofGrossReceipts = $scope.financialInfoData.TotalDollarValueofGrossReceipts;
            //        //financialInfoObj.TotalRevenue = $scope.currentFinancialObj.AllContributionsReceived +$scope.currentFinancialObj.AveragePercentToCharity;
            //        financialInfoObj.AmountOfFunds = $scope.currentFinancialObj.AmountOfFunds;
            //        //financialInfoObj.ExpensesGDValueofAllExpenditures = $scope.financialInfoData.ExpensesGDValueofAllExpenditures;
            //        //financialInfoObj.TotalExpenses = $scope.financialInfoData.AmountOfFunds + $scope.financialInfoData.ExpensesGDValueofAllExpenditures;
            //        //financialInfoObj.EndingGrossAssets = $scope.financialInfoData.EndingGrossAssets;
            //        //financialInfoObj.PercentToProgramServices = $scope.financialInfoData.PercentToProgramServices;
            //        $scope.financialInfoData.CFTFinancialHistoryList.unshift(financialInfoObj);
            //        $rootScope.isGlobalEdited = false;
            //        $scope.financialInfoData.IsShortFiscalYear = false
            //        //resetFinancialInfo();
            //    }
            //};

            $scope.UpdateFinancialInfo = function () {

                var endDate = $scope.currentFinancialObj.AccountingYearEndingDate;
                if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                    if (isEndDateMore) {
                        // Folder Name: app Folder
                        // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js 
                        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                        return false;
                    }
                }

                $scope.showForHistoryErrorMessage = true;
                var isExpensesValid = ($scope.currentFinancialObj.HasOrganizationCompletedFullAccountingYear ? ($scope.currentFinancialObj.AllContributionsReceived < $scope.currentFinancialObj.AmountOfFunds ? false : true) : true);
                var isDatesValid = ($scope.currentFinancialObj.HasOrganizationCompletedFullAccountingYear ? ((new Date($scope.currentFinancialObj.AccountingYearEndingDate) > new Date($scope.currentFinancialObj.AccountingYearBeginningDate)) ? true : false) : true);
                if ($scope.fundraiserFinancialInfo.divFinHistory.$valid && isExpensesValid && isDatesValid) {
                    $scope.showForHistoryErrorMessage = false;
                    angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (financialInfoItem) {
                        if (financialInfoItem.SequenceNo == $scope.currentFinancialObj.FinancialSeqNo) {
                            financialInfoItem.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingYearBeginningDate;
                            financialInfoItem.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingYearEndingDate;
                            financialInfoItem.AllContributionsReceived = $scope.currentFinancialObj.AllContributionsReceived;
                            financialInfoItem.AveragePercentToCharity = $scope.currentFinancialObj.AveragePercentToCharity;
                            financialInfoItem.TotalRevenue = $scope.currentFinancialObj.AllContributionsReceived;
                            financialInfoItem.AmountOfFunds = $scope.currentFinancialObj.AmountOfFunds;
                            financialInfoItem.TotalExpenses = $scope.currentFinancialObj.AmountOfFunds;
                            financialInfoItem.Status = principalStatus.UPDATE;
                            //$scope.financialInfoData.isFinInfoChanged =true;
                        }
                    });
                    $rootScope.isGlobalEdited = false;
                    $scope.financialInfoData.isUpdated = true;
                }
            };

            // Clear all controls data
            $scope.clearFinancialInfo = function () {
                $scope.currentFinancialObj.AccountingYearBeginningDate = null,
                $scope.currentFinancialObj.AccountingYearEndingDate = null,
                $scope.currentFinancialObj.AllContributionsReceived = null,
                $scope.currentFinancialObj.AveragePercentToCharity = null,
                $scope.currentFinancialObj.AmountOfFunds = null,
                //$scope.resetFinancialInfo();
                $rootScope.isGlobalEdited = false
            };

            $scope.resetFinancialInfo = function () {
                //$scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate = null,
                //$scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate = null,
                $scope.financialInfoData.shortFiscalYearEntity.AllContributionsReceivedForShortFY = null,
                $scope.financialInfoData.shortFiscalYearEntity.AveragePercentToCharityForShortFY = null,
                $scope.financialInfoData.shortFiscalYearEntity.AmountOfFundsForShortFY = null
                //$scope.financialInfoData.IsShortFiscalYear =false
            };

            $scope.$watch("financialInfoData.AccountingYearEndingDate", function () {
                if ($scope.financialInfoData.HasOrganizationCompletedFullAccountingYear && typeof ($scope.financialInfoData.BusinessFiling) != typeof (undefined) && $scope.financialInfoData.BusinessFiling != null
                    && ($scope.financialInfoData.BusinessFiling.FilingTypeName == 'COMMERCIAL FUNDRAISER REGISTRATION' || $scope.financialInfoData.BusinessFiling.FilingTypeName == 'COMMERCIAL FUNDRAISER AMENDMENT')) {
                    if (typeof ($scope.financialInfoData.AccountingYearEndingDate) != typeof (undefined) && $scope.financialInfoData.AccountingYearEndingDate != null && $scope.financialInfoData.AccountingYearEndingDate != "") {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.accDate = wacorpService.checkAccYearEndDateForReg($scope.financialInfoData.AccountingYearEndingDate, true);
                    }
                }
            });

            $scope.$watch("financialInfoData.FirstAccountingYearEndDate", function () {
                if (!$scope.financialInfoData.HasOrganizationCompletedFullAccountingYear && typeof ($scope.financialInfoData.BusinessFiling) != typeof (undefined) && $scope.financialInfoData.BusinessFiling != null
                    && ($scope.financialInfoData.BusinessFiling.FilingTypeName == 'COMMERCIAL FUNDRAISER REGISTRATION' || $scope.financialInfoData.BusinessFiling.FilingTypeName == 'COMMERCIAL FUNDRAISER AMENDMENT')) {
                    if (typeof ($scope.financialInfoData.FirstAccountingYearEndDate) != typeof (undefined) && $scope.financialInfoData.FirstAccountingYearEndDate != null && $scope.financialInfoData.FirstAccountingYearEndDate != "") {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.accDate = wacorpService.checkAccYearEndDateForReg($scope.financialInfoData.FirstAccountingYearEndDate, false);
                        if (typeof ($scope.financialInfoData.FirstAccountingYearEndDate) != typeof (undefined) && $scope.financialInfoData.FirstAccountingYearEndDate != null && $scope.financialInfoData.FirstAccountingYearEndDate != "") {
                            if (!$scope.accDate)
                                calculateFAYEDRenewalDate(); // calculateFAYEDRenewalDate method is available in this file only
                            else
                                $scope.newRenewalDate = "";
                        }
                    }
                    else
                        $scope.newRenewalDate = "";
                }
            });



            $scope.getShortYearStartDate = function () {
                if ($scope.financialInfoData.CurrentEndDateForAmendment != null && typeof ($scope.financialInfoData.CurrentEndDateForAmendment) != typeof (undefined)) {
                    $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate = "";
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var startDate = wacorpService.getShortYearStartDate($scope.financialInfoData.CurrentEndDateForAmendment);
                    $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate = wacorpService.dateFormatService(startDate);
                    return $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate;
                }
            };

            $scope.getShortYearEndDate = function () {
                if ($scope.financialInfoData.AccountingYearBeginningDate != null && typeof ($scope.financialInfoData.AccountingYearBeginningDate) != typeof (undefined)) {
                    $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate = "";
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var endDate = wacorpService.getShortYearEndDate($scope.financialInfoData.AccountingYearBeginningDate);
                    $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate = wacorpService.dateFormatService(endDate);
                    return $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate;
                }
            };


            function calculateFAYEDRenewalDate() {
                var value = $scope.financialInfoData.FirstAccountingYearEndDate;
                if (value != null && value != undefined && value != "") {
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultDate = lastDayWithSlashes;
                        $scope.newRenewalDate = "Your Renewal Date is: " + resultDate;
                    }
                }
                else {
                    $scope.newRenewalDate = "";
                }
            }

            //$scope.$watch('financialInfoData.IsShortFiscalYear', function (val) {
            //    if(val) {
            //        if (($scope.financialInfoData.AccountingYearBeginningDate != null && typeof ($scope.financialInfoData.AccountingYearBeginningDate) != typeof (undefined)) && ($scope.financialInfoData.CurrentEndDateForAmendment != null && typeof ($scope.financialInfoData.CurrentEndDateForAmendment) != typeof (undefined))) {
            //            $scope.getShortYearStartDate();
            //            $scope.getShortYearEndDate();
            //        }
            //    }
            //});

            $scope.$watch('financialInfoData.AccountingYearEndingDate', function () {
                if ($scope.financialInfoData.AccountingYearEndingDate != null && typeof ($scope.financialInfoData.AccountingYearEndingDate) != typeof (undefined) && $scope.financialInfoData.BusinessFiling.FilingTypeName == 'COMMERCIAL FUNDRAISER AMENDMENT') {
                    //var isFinSectionMandetory = wacorpService.isFinancialMandetory($scope.financialInfoData.AccountingYearEndingDate);
                    //if ($scope.financialInfoData.BusinessFiling.FilingTypeName != 'COMMERCIAL FUNDRAISER AMENDMENT') {
                    //    $scope.isMandetory = true;
                    //}
                    //else {
                    //    $scope.isMandetory = false;
                    //}
                    var isFinSectionMandetory = false;

                    if (isFinSectionMandetory) {
                        $scope.isMandetory = true;
                    }
                    else {
                        $scope.isMandetory = false;
                    }
                }
            });

        },
    };
});

wacorpApp.directive('signature', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/Signature/_Signature.html',
        restrict: 'A',
        scope: {
            signatureAttestation: '=?signatureAttestation',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, $rootScope) {
           
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isReview = $scope.isReview || false;
            $scope.messages = messages;
            //var signatureAttestationScope = {
            //    AttestationFirstName: null,
            //    AttestationLastName: null,
            //    AttestationDate: new Date(wacorpService.dateFormatService(new Date())),
            //    AttestationPhoneNumber: null,
            //    IsAttestationInformationProvided: false,             
            //};

            //$scope.signatureAttestation = $scope.signatureAttestation || {};
            
           // $scope.signatureAttestation = angular.extend(signatureAttestationScope, $scope.signatureAttestation);
            $scope.isNeedValidation = function () {
                return $scope.showErrorMessage || false;
            };
           },
    };
});
wacorpApp.directive('multiselectCounties', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/MultiSelectCounties/_MultiSelectCounties.html',
        restrict: 'A',
        scope: {
            countyOptions: '=?countyOptions',
            countyModel: '=?countyModel',
            dropdownsettings: '=?dropdownsettings',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, $rootScope, lookupService) {
            $scope.countyOptions = $scope.countyOptions || [];
            $scope.countyModel = $scope.countyModel || [];
            var settingScope = { scrollableHeight: '200px', scrollable: true, key: "Value", value: "Key", isKeyList: false, selectall: false };
            $scope.dropdownsettings = $scope.dropdownsettings ? angular.extend(settingScope, $scope.dropdownsettings) : angular.copy(settingScope);
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;

            $scope.Init = function () {
                $scope.selectedItems = [];      
            };

            //Get Countries List
            $scope.getCountries = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.countriesList(function (response) { $scope.countyOptions = response.data; });

                $scope.countyOptions.filter(function (state) {
                    for (var i = 0; i < response.data.length; i++) {
                        if (state == response.data[i].Key) {
                            $scope.selectedItems.push(response.data[i]);
                            break;
                        }
                    }
                });
            };
            $scope.getCountries(); // getCountries method is available in this file only


        },
    };
});
wacorpApp.directive('greenCrossCfd', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/EnrollToCFD/_GreenCrossCFD.html',
        restrict: 'A',
        scope: {                        
            charityGcAkaInfo: '=?charityGcAkaInfo',
            isReview: '=?isReview',
            entityDetailInfo: '=?entityDetailInfo',
            showErrorMessage: '=?showErrorMessage'  
        },
        controller: function ($scope, wacorpService, lookupService, $rootScope) {
            $scope.messages = messages;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isReview = $scope.isReview || false;
            $scope.charityGcAkaInfo = $scope.charityGcAkaInfo || {};
            $scope.countyOptions = [];
            $scope.countySelectedOptions = [];
            $scope.serviceOptions = [];
            $scope.serviceSelectedOptions = [];
            var settingScope = { scrollableHeight: '300px', scrollable: true, key: "Key", value: "Value", isKeyList: false, width: 'multiselect-parent col-md-10'};
            $scope.settings = $scope.settings ? angular.extend(settingScope, $scope.settings) : angular.copy(settingScope);
            
            // multi dropdown settings
            $scope.dropdownsettings = {
                scrollableHeight: '300px',
                key: "Value",
                value: "Key",
                scrollable: true,
                isKeyList: false,
                selectall: false,
                width: 'multiselect-parent col-md-10'
            };

            var charityGcAKAInfoScope = {
                ID: constant.ZERO, SequenceNo: constant.ZERO, AKASolicitNameId: constant.ZERO, IsDevelopmentInfo: false, IsSameasCharity: false, IsAKA: false,
                DevInfoFirstName: "", DevInfoLastName: "", DevInfoEmailAddress: "", DevInfoConfirmEmailAddress: "", DevInfoPhoneNumber: "",
                FinancialInfoFirstName: "", FinancialInfoLastName: "", FinancialInfoEmailAddress: "", FinancialConfirmEmailAddress: "", FinancialInfoPhoneNumber: "",
                WebSite: "", ProgramDescription: "", CharityVendorId: null, CountiesServedId: [], CategoryOfServiceId: []
            };

            //Copy Charity Contact Information
            $scope.CopyFromCharityInfo = function () {
                if ($scope.charityGcAkaInfo.IsSameasCharity) {
                    //$scope.charityGcAkaInfo.DevInfoFirstName = angular.copy($scope.entityDetailInfo.EntityName);
                    //$scope.charityGcAkaInfo.DevInfoLastName = angular.copy($scope.entityDetailInfo.DevInfoLastName);
                    $scope.charityGcAkaInfo.DevInfoEmailAddress = angular.copy($scope.entityDetailInfo.EntityEmailAddress);
                    $scope.charityGcAkaInfo.DevInfoConfirmEmailAddress = angular.copy($scope.entityDetailInfo.EntityConfirmEmailAddress);
                    $scope.charityGcAkaInfo.DevInfoPhoneNumber = angular.copy($scope.entityDetailInfo.EntityPhoneNumber);
                }
                else {
                    $scope.charityGcAkaInfo.DevInfoFirstName = angular.copy($scope.charityGcAKAInfoScope.DevInfoFirstName);
                    $scope.charityGcAkaInfo.DevInfoLastName = angular.copy($scope.charityGcAKAInfoScope.DevInfoLastName);
                    $scope.charityGcAkaInfo.DevInfoEmailAddress = angular.copy($scope.charityGcAKAInfoScope.DevInfoEmailAddress);
                    $scope.charityGcAkaInfo.DevInfoConfirmEmailAddress = angular.copy($scope.charityGcAKAInfoScope.DevInfoConfirmEmailAddress);
                    $scope.charityGcAkaInfo.DevInfoPhoneNumber = angular.copy($scope.charityGcAKAInfoScope.DevInfoPhoneNumber);
                }
            };

            //Copy Development Contact Information
            $scope.CopyFromDevelopmentInfo = function () {
                if ($scope.charityGcAkaInfo.IsSameasDevelopment) {
                    $scope.charityGcAkaInfo.FinancialInfoFirstName = angular.copy($scope.charityGcAkaInfo.DevInfoFirstName);
                    $scope.charityGcAkaInfo.FinancialInfoLastName = angular.copy($scope.charityGcAkaInfo.DevInfoLastName);
                    $scope.charityGcAkaInfo.FinancialInfoEmailAddress = angular.copy($scope.charityGcAkaInfo.DevInfoEmailAddress);
                    $scope.charityGcAkaInfo.FinancialConfirmEmailAddress = angular.copy($scope.charityGcAkaInfo.DevInfoConfirmEmailAddress);
                    $scope.charityGcAkaInfo.FinancialInfoPhoneNumber = angular.copy($scope.charityGcAkaInfo.DevInfoPhoneNumber);
                }
                else {
                    $scope.charityGcAkaInfo.FinancialInfoFirstName = angular.copy($scope.charityGcAKAInfoScope.FinancialInfoFirstName);
                    $scope.charityGcAkaInfo.FinancialInfoLastName = angular.copy($scope.charityGcAKAInfoScope.FinancialInfoLastName);
                    $scope.charityGcAkaInfo.FinancialInfoEmailAddress = angular.copy($scope.charityGcAKAInfoScope.FinancialInfoEmailAddress);
                    $scope.charityGcAkaInfo.FinancialConfirmEmailAddress = angular.copy($scope.charityGcAKAInfoScope.FinancialConfirmEmailAddress);
                    $scope.charityGcAkaInfo.FinancialInfoPhoneNumber = angular.copy($scope.charityGcAKAInfoScope.FinancialInfoPhoneNumber);
                }
            };          
            if (!$scope.isReview) {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.countiesList(function (response) { $scope.countyOptions = response.data; });
                lookupService.trustPurposeList(function (response) { $scope.serviceOptions = response.data; });
            }
            if ($scope.isReview) {
                getCountySelected(); // getCountySelected method is available in this file only.
                getServicesSelected(); // getServicesSelected method is available in this file only.
            }

            // get selected Counties Codes
            function getCountySelected() {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.countiesList(function (response) {
                    $scope.charityGcAkaInfo.CountiesServedId.filter(function (countyCode) {
                        for (var i = 0; i < response.data.length; i++) {
                            if (countyCode == response.data[i].Key) {
                                $scope.countySelectedOptions.push(response.data[i]);
                                break;
                            }
                        }
                    });
                });
            }           
            
            // get selected Services Codes
            function getServicesSelected() {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.trustPurposeList(function (response) {
                    $scope.charityGcAkaInfo.CategoryOfServiceId.filter(function (service) {
                        for (var i = 0; i < response.data.length; i++) {
                            if (service == response.data[i].Key) {
                                $scope.serviceSelectedOptions.push(response.data[i]);
                                break;
                            }
                        }
                    });
                });
            }

            //$scope.focusMultiSelectBox = function (ddBox) {
            //    if (ddBox == 1) {
            //        //$($(".multiselect-parent")[0]).find("div[class^=form-control]").triggerHandler('click');
            //        $($(".multiselect-parent")[0]).find("div[class^=form-control]").focus();
            //    }
            //    else if (ddBox == 1) {
            //        $($(".multiselect-parent")[1]).find("div[class^=form-control]").focus();
            //    }
            //}
        },
    };
});
wacorpApp.directive('cftCorrespondenceAddress', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CorrespondenceAddress/_CorrespondenceAddress.html',
        restrict: 'A',
        scope: {
            cftCorrespondenceAddressEntity: '=?cftCorrespondenceAddressEntity',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            isCorrespAddress: '=?isCorrespAddress',
            isShowReturnAddress:'=?isShowReturnAddress'
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope, $location) {
            $scope.messages = messages;
            //Email validation
            $scope.ValidateConfirmEmailAddress = function () {
                
                if (($scope.cftCorrespondenceAddressEntity.CorrespondenceEmailAddress).toUpperCase() != ($scope.cftCorrespondenceAddressEntity.CorrespondenceConfrimEmailAddress).toUpperCase()) {
                    // Folder Name: app Folder
                    // Alert Name: emailMatch method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.PrincipalOffice.emailMatch);
                    $('#txtCorrespondenceemailFocus').focus();
                }
            };
        }
    };
});
wacorpApp.directive('fundraiserEntitySearch', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserEntitySearch/_fundraiserEntitySearch.html',
        restrict: 'A',
        scope: {
            searchType: '=?searchType',
            selectedBusiness: '=?selectedBusiness',
            submitFunc: '&?submitFunc',
        },
        controller: function ($scope, wacorpService, focus, $rootScope, $cookieStore, $timeout, $routeParams, $location, $window, $compile, $element) {
            // declare scope variables
            $scope.page = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.messages = messages;
            $scope.searchType = $scope.searchType || "";
            $scope.businessSearchCriteria = { Type: searchTypes.RegistrationNumber, ID: "", CFTId: "", Businesstype: "", BusinessFilingType: "", OrgName: "", isCftOrganizationSearchBack: false, isCftFeinOrganizationSearchBack: false, IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, SearchType: $scope.searchType, isSearchClick: false, isFundraiserEntitySearch: false, isFeinFundraiserEntitySearch: false, SortBy: null, SortType: null, };
            $scope.selectedBusiness = null;
            $scope.search = loadbusinessList;
            $scope.searchval = '';
            $scope.isButtonSerach = false;
            focus("searchField");
            var url = $location.path();
            if (typeof (url) != typeof (undefined) && url != "" && url != null) {
                $rootScope.businessFilingType = url.split('/')[2];
            }
            

            $scope.cftFeinSearchcriteria = {
                CFTId: "", ID: "", EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false, EntityWebsite: null, SortBy: null, SortType: null,
                RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, Businesstype: "",BusinessFilingType: "",  Type: "", SearchValue: "", SearchCriteria: "", isSearchClick: false,
            };
            var criteria = null;

            $scope.submitBusiness = function () {
                angular.forEach(CFTStatus, function (value, data) {
                    if ($scope.Status != value.closed && $scope.Status != value.involuntaryClosure) {
                        if ($scope.submitFunc) {
                            $scope.submitFunc();
                        }
                    }
                    else {
                        // Folder Name: app Folder
                        // Alert Name: alert method is available in alertMessages.js 
                        wacorpService.alertDialog(messages.CFTPublicSearch.alert);
                    }

                });
            };

            if ($rootScope.data != null) {
                $scope.businessSearchCriteria = $rootScope.data;
                $scope.isButtonSerach = true

                $scope.cftFeinSearchcriteria.SearchValue = $rootScope.data.ID;
                $scope.cftFeinSearchcriteria.Type = $rootScope.data.Type;
                $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);
                $rootScope.data = null;
                loadbusinessList(constant.ZERO); // loadbusinessList method is available in this file only

            }

            // search business list
            $scope.searchBusiness = function (searchform) {
                $scope.isShowErrorFlag = true;
                if ($scope[searchform].$valid) {
                    $scope.businessSearchCriteria.isSearchClick = true;
                    $scope.isShowErrorFlag = false;
                    $scope.isButtonSerach = true;
                    loadbusinessList(constant.ZERO); // loadbusinessList method is available in this file only
                }
            };
            //clear text on selecting radiobutton
            $scope.cleartext = function () {
                $scope.businessSearchCriteria.ID = null;
                $scope.businessSearchCriteria.SortBy = null;
                $scope.businessSearchCriteria.SortType = null;
            };

            // clear fields
            $scope.clearFun = function () {
                $scope.businessSearchCriteria.ID = "";
                $scope.businessSearchCriteria.OrgName = "";
                $scope.businessSearchCriteria.isSearchClick = false;
                $scope.businessSearchCriteria.isSearchClick = false;
                $scope.businessSearchCriteria.Type = searchTypes.RegistrationNumber;
                $scope.businessSearchCriteria.SortBy = null;
                $scope.businessSearchCriteria.SortType = null;
                $scope.isShowErrorFlag = false;
            };

            // get selected business information
            $scope.getSelectedBusiness = function (business) {
                $scope.selectedBusiness = business;
                $scope.selectedFundRaiserID = business.FundRaiserID;
                $scope.Status = business.Status;
            };


            // get business list data from server
            function loadbusinessList(page, sortBy) {
                //Ticket -- 3167
                $rootScope.isCFTBackButtonPressed = false;
                page = page || constant.ZERO;
                $scope.businessSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                $scope.selectedBusiness = null;
                if (sortBy != undefined) {
                    if ($scope.businessSearchCriteria.SortBy == sortBy) {
                        if ($scope.businessSearchCriteria.SortType == 'ASC') {
                            $scope.businessSearchCriteria.SortType = 'DESC';
                        }
                        else {
                            $scope.businessSearchCriteria.SortType = 'ASC';
                        }
                    }
                    else {
                        $scope.businessSearchCriteria.SortBy = sortBy;
                        $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                }
                else {
                    if ($scope.businessSearchCriteria.Type == "RegistrationNumber") {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "Registration#";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.businessSearchCriteria.Type == "FEINNo") {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "FEIN#";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.businessSearchCriteria.Type == "UBINumber") {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "UBI#";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.businessSearchCriteria.Type == "OrganizationName") {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "OrganizationName";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                }
                var data = angular.copy($scope.businessSearchCriteria);
                $scope.isButtonSerach = page == 0;
                $rootScope.isFundraiserEntitySearch = false;
                if ($scope.isButtonSerach)
                    data.ID = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID || $scope.businessSearchCriteria.OrgName : $scope.searchval);
                else {
                    if ($scope.businessSearchCriteria.Type == "OrganizationName" && $scope.businessSearchCriteria.OrgName)
                        data.ID = $scope.businessSearchCriteria.OrgName;
                }
                if (criteria == null) {
                    criteria = {};
                    criteria.Type = $scope.businessSearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.SearchCriteria = "contains";
                    //criteria.ID = constant.ONE;
                    criteria.PageCount = 10;
                    //criteria.TotalRowCount = $scope.totalCount;
                    criteria.PageID = $scope.businessSearchCriteria.PageID;
                    criteria.SortBy = $scope.businessSearchCriteria.SortBy 
                    criteria.SortType = $scope.businessSearchCriteria.SortType
                }
                else {
                    criteria.Type = $scope.businessSearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.businessSearchCriteria.PageID;
                    criteria.SortBy = $scope.businessSearchCriteria.SortBy
                    criteria.SortType = $scope.businessSearchCriteria.SortType
                    //criteria.BusinessFilingType = ;
                }
                // getFundraiserSearchDetails method is available in constants.js
                wacorpService.post(webservices.CFT.getFundraiserSearchDetails, criteria, function (response) {
                    $scope.selectedBusiness = null;
                    $scope.BusinessList = response.data;
                    $scope.selectedFundRaiserID = null;
                    if ($scope.isButtonSerach && response.data.length > 0) {
                        var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                        $scope.pagesCount = response.data.length < $scope.businessSearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                        $scope.totalCount = totalcount;
                        $scope.searchval = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID : $scope.searchval);
                    }
                    $scope.page = page;
                    $scope.BusinessListProgressBar = false;
                    focus("tblBusinessSearch");
                }, function (response) {
                    $scope.selectedBusiness = null;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                });
            }

            // select search type
            $scope.selectSearchType = function () {
                $scope.businessSearchCriteria.ID = "";
            }

            //copypaste Reg Number
            $scope.setPastedRegNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                    $scope.businessSearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                        $scope.businessSearchCriteria.ID = pastedText;
                    });
                }
            };


            //copypaste Fein Number
            $scope.setPastedFeinNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.businessSearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.businessSearchCriteria.ID = pastedText;
                    });
                }
            };

            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.businessSearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.businessSearchCriteria.ID = pastedText;
                    });
                }
            };

            $scope.setUBILength = function (e) {
                //if (e.currentTarget.value.length >= 9) {
                //    e.preventDefault();
                //}
                if (e.currentTarget.value != undefined && e.currentTarget.value != null && e.currentTarget.value != "" && e.currentTarget.value.length >= 9)
                {
                    if (e.which != 97)
                    {
                        // Allow: backspace, delete, tab, escape, enter and .
                        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                            // Allow: Ctrl+A, Command+A
                            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                            // Allow: home, end, left, right, down, up
                            (e.keyCode >= 35 && e.keyCode <= 40)) {
                            // let it happen, don't do anything
                            return;
                        }
                        // Ensure that it is a number and stop the keypress
                        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                            e.preventDefault();
                        }
                        e.preventDefault();
                    }
                }
            };

            // Search FEIN Information
            $scope.searchFeinData = function (type, value) {
                $scope.cftFeinSearchcriteria.Type = type;
                $scope.cftFeinSearchcriteria.SearchValue = value;
                loadCFeinList(constant.ZERO); // loadCFeinList method is available in this file only
                $('#divFundraiserSearchResult').modal('toggle');
            };

            // search fein details associated to charity
            $scope.searchFein = function (searchform) {
                $scope.cftFeinSearchcriteria.IsSearch = true;
                $scope.isButtonSerach = true;
                loadCFeinList(searchform); // loadCFeinList method is available in this file only
            };

            //to get data for FEIN link
            function loadCFeinList(page) {
                //Ticket -- 3167
                $rootScope.isCFTBackButtonPressed = false;
                if ($rootScope.isCftFeinOrganizationSearchBack == true) {
                    page = page || constant.ZERO;
                    $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                    $scope.cftFeinSearchcriteria = $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);
                }
                else {
                    page = page || constant.ZERO;
                    $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                    //$scope.cftFeinSearchcriteria.Type = $scope.criteria.Type;
                    //$scope.cftFeinSearchcriteria.SearchValue = $scope.criteria.SearchValue;
                    $scope.cftFeinSearchcriteria.SearchCriteria = "";
                }
                var data = angular.copy($scope.cftFeinSearchcriteria);
                $scope.isButtonSerach = page == 0;
                // getFundraiserSearchDetails method is available in constants.js
                wacorpService.post(webservices.CFT.getFundraiserSearchDetails, data, function (response) {
                    $scope.feinDataDetails = response.data;
                    if ($scope.cftFeinSearchcriteria.PageID == 1)
                        //$('#divFundraiserSearchResult').modal('toggle');
                        $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);

                    if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                        var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                        $scope.pagesCount1 = response.data.length < $scope.cftFeinSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount1 : pagecount;
                        $scope.totalCount = totalcount;
                    }
                    $scope.page1 = page;
                    $scope.BusinessListProgressBar = false;
                }, function (response) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                });
            }

            $scope.cancel = function () {
                $("#divFundraiserSearchResult").modal('toggle');
            }

            //navigate to business information
            $scope.showBusineInfo = function (id, businessType, flag) {
                //Ticket -- 3167
                $rootScope.isCFTBackButtonPressed = false;
                if (!flag) {
                    $scope.businessSearchCriteria.CFTId = id;
                    $scope.businessSearchCriteria.Businesstype = businessType;
                    //$scope.businessSearchCriteria.isFundraiserEntitySearch = true;
                    $rootScope.isAdvanceSearch = null;
                    $rootScope.data = $scope.businessSearchCriteria;
                    $rootScope.isFundraiserEntitySearch = true;
                    $cookieStore.put('cftBusinessSearchListcriteriaId', id);
                    $cookieStore.put('cftBusinessSearchListcriteriaType', businessType);
                    //$location.path("/organization");
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityFoundationOrganization();
                }
                else {
                    $scope.businessSearchCriteria.CFTId = id;
                    $scope.businessSearchCriteria.Businesstype = businessType;
                    //$scope.businessSearchCriteria.isFeinCharityEntitySearch = true;
                    $rootScope.data = $scope.businessSearchCriteria;
                    $rootScope.isFundraiserEntitySearch = true;
                    $scope.navigate($rootScope.data); // navigate method is available in this file only
                }

            };

            $scope.navigate = function (data) {
                $window.sessionStorage.removeItem('orgData');
                var obj = {
                    org: data,
                    viewMode: true,
                    flag: true,

                }
                $window.sessionStorage.setItem('orgData', JSON.stringify(obj));
                $window.open('#/organization', "_blank");
                $window.sessionStorage.removeItem('orgData');
            }

            $scope.navCharityFoundationOrganization = function () { $rootScope.modal = null; $rootScope.searchCriteria = null; $location.path("/organization"); };

            $scope.$watch('BusinessList', function () {
                if ($scope.BusinessList == undefined)
                    return;
                if ($scope.BusinessList.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);

            //Ticket -- 3167
            $scope.initCFTSearch = function () {
                if ($rootScope.isSearchNavClicked) {
                    $scope.clearFun();
                }
            };

        },
    }
});


wacorpApp.directive('charityEntitySearch', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CharityEntitySearch/_CharityEntitySearch.html',
        restrict: 'A',
        scope: {
            searchType: '=?searchType',
            selectedEntity: '=?selectedEntity',
            submitFunc: '&?submitFunc',
        },
        controller: function ($scope, wacorpService, focus, $rootScope, $cookieStore, $timeout, $routeParams, $location, $window, $compile, $element) {
            // declare scope variables
            $scope.page = constant.ZERO;
            $scope.page1 = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.pagesCount1 = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.messages = messages;
            $scope.feinDataDetails = [];
            $scope.searchType = $scope.searchType || "";
            //var isOptional = localStorage.getItem('isOptional');
            var isOptionalRenewal = $rootScope.isRenewal != null && $rootScope.isRenewal != undefined && $rootScope.isRenewal ? true : false;
            var isOptionalAmendmet = $rootScope.isOptionalAmendment != null && $rootScope.isOptionalAmendment != undefined && $rootScope.isOptionalAmendment ? true : false;
            $scope.charitySearchCriteria = { Type: searchTypes.RegistrationNumber, ID: "", CFTId: "", Businesstype: "", isCftOrganizationSearchBack: false, isCftFeinOrganizationSearchBack: false, IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, IsOnline: true, SearchType: $scope.searchType, isSearchClick: false, isCharityEntitySearch: false, isFeinCharityEntitySearch: false, SortBy: null, SortType: null, };
            //$scope.cftFeinSearchcriteria = {
            //    CFTId: "", EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, isCftOrganizationSearchBack:false, IsSearch: false, EntityWebsite: null,
            //    RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, Businesstype: "", Type: "", SearchValue: "", SearchCriteria: "",
            //};
            $scope.cftFeinSearchcriteria = {
                CFTId: "", ID: "", EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false, EntityWebsite: null, SortBy: null, SortType: null,
                RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, Businesstype: "", Type: "", SearchValue: "", SearchCriteria: "", isSearchClick: false,
            };

            $scope.selectedEntity = null;
            var criteria = null;
            $scope.search = loadCharityList;
            $scope.searchval = '';
            $scope.isButtonSerach = false;
            focus("entityNameSearchField");

            $scope.submitCharityEntity = function () {
                if (isOptionalRenewal == true || isOptionalAmendmet == true) {
                    angular.forEach(CFTStatus, function (value, data) {
                        if ($scope.Status != value.closed && $scope.Status != value.involuntaryClosure) {
                            $rootScope.OptionalData = null;
                            $rootScope.CharityID = $scope.selectedEntityID;
                            $location.path("/charitiesOptionalQualifier");
                        }
                        else {
                            // Folder Name: app Folder
                            // Alert Name: alert method is available in alertMessages.js
                            wacorpService.alertDialog(messages.CFTPublicSearch.alert);
                        }
                    });
                }
                else {
                    angular.forEach(CFTStatus, function (value, data) {
                        if ($scope.Status != value.closed && $scope.Status != value.involuntaryClosure) {
                            if ($scope.submitFunc) {
                                $scope.submitFunc();
                            }
                        }
                        else {
                            // Folder Name: app Folder
                            // Alert Name: alert method is available in alertMessages.js
                            wacorpService.alertDialog(messages.CFTPublicSearch.alert);
                        }

                    });
                }
              //if (isOptional == "true") {
              //    $rootScope.CharityID = $scope.selectedEntityID;
              //      $location.path("/charitiesOptionalQualifier");
              //  }
              //  else {
              //      angular.forEach(CFTStatus, function (value, data) {
              //          if ($scope.Status != value.closed && $scope.Status != value.involuntaryClosure) {
              //              if ($scope.submitFunc) {
              //                  $scope.submitFunc();
              //              }
              //          }
              //          else {
              //              wacorpService.alertDialog(messages.CFTPublicSearch.alert);
              //          }

              //      });
              //  }
            };

            var url = $location.path();
            if (typeof (url) != typeof (undefined) && url != "" && url != null) {
                $rootScope.businessFilingType = url.split('/')[2];
            }

            if ($rootScope.data != null) {
                $scope.charitySearchCriteria = $rootScope.data;
                $scope.isButtonSerach = true

                $scope.cftFeinSearchcriteria.SearchValue = $rootScope.data.ID;
                $scope.cftFeinSearchcriteria.Type = $rootScope.data.Type;
                $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);
                $rootScope.data = null;
                loadCharityList(constant.ZERO); // loadCharityList method is available in this file only.

            }
            // search cft list
            $scope.searchEntity = function (searchform) {
                $scope.isShowErrorFlag = true;
                if ($scope[searchform].$valid) {
                    $scope.charitySearchCriteria.isSearchClick = true;
                    $scope.isShowErrorFlag = false;
                    $scope.isButtonSerach = true
                    $scope.selectedEntityID = constant.ZERO;
                    loadCharityList(constant.ZERO); // loadCharityList method is available in this file only.
                }
            };
            //clear text on selecting radio button
            $scope.cleartext = function () {
                $scope.charitySearchCriteria.ID = null;
                $scope.charitySearchCriteria.OrgName = null;
                $scope.charitySearchCriteria.SortBy = null;
                $scope.charitySearchCriteria.SortType = null;
            };

            // clear fields
            $scope.clearFun = function () {
                $scope.charitySearchCriteria.ID = "";
                $scope.charitySearchCriteria.OrgName = "";
                $scope.charitySearchCriteria.isSearchClick = false;
                $scope.charitySearchCriteria.Type = searchTypes.RegistrationNumber;
                $scope.charitySearchCriteria.SortBy = null;
                $scope.charitySearchCriteria.SortType = null;
                $scope.isShowErrorFlag = false;
            };

            // get selected entity information
            $scope.getSelectedEntity = function (cftentity) {
                $scope.selectedEntity = cftentity;
                $scope.selectedEntityID = cftentity.CFTId;
                $scope.Status = cftentity.Status;
            };

            // get charity list data from server
            function loadCharityList(page, sortBy) {
                //Ticket -- 3167
                $rootScope.isCFTBackButtonPressed = false;
                page = page || constant.ZERO;
                $scope.charitySearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;

                var isOptional = localStorage.getItem("isOptional");

                $scope.selectedEntity = null;
                if (sortBy != undefined) {
                    if ($scope.charitySearchCriteria.SortBy == sortBy) {
                        if ($scope.charitySearchCriteria.SortType == 'ASC') {
                            $scope.charitySearchCriteria.SortType = 'DESC';
                        }
                        else {
                            $scope.charitySearchCriteria.SortType = 'ASC';
                        }
                    }
                    else {
                        $scope.charitySearchCriteria.SortBy = sortBy;
                        $scope.charitySearchCriteria.SortType = 'ASC';
                    }
                }
                else {
                    if ($scope.charitySearchCriteria.Type == "RegistrationNumber") {
                        if ($scope.charitySearchCriteria.SortBy == null || $scope.charitySearchCriteria.SortBy == "" || $scope.charitySearchCriteria.SortBy == undefined)
                            $scope.charitySearchCriteria.SortBy = "Registration#";
                        if ($scope.charitySearchCriteria.SortType == null || $scope.charitySearchCriteria.SortType == "" || $scope.charitySearchCriteria.SortType == undefined)
                            $scope.charitySearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.charitySearchCriteria.Type == "FEINNo") {
                        if ($scope.charitySearchCriteria.SortBy == null || $scope.charitySearchCriteria.SortBy == "" || $scope.charitySearchCriteria.SortBy == undefined)
                            $scope.charitySearchCriteria.SortBy = "FEIN#";
                        if ($scope.charitySearchCriteria.SortType == null || $scope.charitySearchCriteria.SortType == "" || $scope.charitySearchCriteria.SortType == undefined)
                            $scope.charitySearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.charitySearchCriteria.Type == "UBINumber") {
                        if ($scope.charitySearchCriteria.SortBy == null || $scope.charitySearchCriteria.SortBy == "" || $scope.charitySearchCriteria.SortBy == undefined)
                            $scope.charitySearchCriteria.SortBy = "UBI#";
                        if ($scope.charitySearchCriteria.SortType == null || $scope.charitySearchCriteria.SortType == "" || $scope.charitySearchCriteria.SortType == undefined)
                            $scope.charitySearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.charitySearchCriteria.Type == "OrganizationName") {
                        if ($scope.charitySearchCriteria.SortBy == null || $scope.charitySearchCriteria.SortBy == "" || $scope.charitySearchCriteria.SortBy == undefined)
                            $scope.charitySearchCriteria.SortBy = "OrganizationName";
                        if ($scope.charitySearchCriteria.SortType == null || $scope.charitySearchCriteria.SortType == "" || $scope.charitySearchCriteria.SortType == undefined)
                            $scope.charitySearchCriteria.SortType = 'ASC';
                    }
                }
                var data = angular.copy($scope.charitySearchCriteria);
                $scope.isButtonSerach = page == 0;
                $rootScope.isCharityEntitySearch = false;
                data.ID = angular.copy($scope.isButtonSerach ? $scope.charitySearchCriteria.ID || $scope.charitySearchCriteria.OrgName : $scope.searchval);
                if (criteria == null) {
                    criteria = {};
                    criteria.Type = $scope.charitySearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.SearchCriteria = "contains";
                    //criteria.ID = constant.ONE;
                    criteria.PageCount = 10;
                    //criteria.TotalRowCount = $scope.totalCount;
                    criteria.PageID = $scope.charitySearchCriteria.PageID;
                    criteria.SortBy = $scope.charitySearchCriteria.SortBy 
                    criteria.SortType = $scope.charitySearchCriteria.SortType
                }
                else {
                    criteria.Type = $scope.charitySearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.charitySearchCriteria.PageID;
                    criteria.SortBy = $scope.charitySearchCriteria.SortBy
                    criteria.SortType = $scope.charitySearchCriteria.SortType
                }

                criteria.isOptionalRegistration = isOptional;
                //wacorpService.post(webservices.CFT.getCharitySearchDetails, data, function (response) {ddddd
                // getCharityAmendRenewalDetails method is available in constants.js
                wacorpService.post(webservices.CFT.getCharityAmendRenewalDetails, criteria, function (response) {
                    $scope.selectedEntity = null;
                    $scope.CharityList = response.data;
                    $scope.selectedEntityID = null;
                    if ($scope.isButtonSerach && response.data.length > 0) {
                        var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                        $scope.pagesCount = response.data.length < $scope.charitySearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                        $scope.totalCount = totalcount;
                        //$scope.searchval = angular.copy($scope.isButtonSerach ? $scope.charitySearchCriteria.ID : $scope.searchval);
                        $scope.searchval = criteria.SearchValue;
                        criteria = response.data[constant.ZERO].Criteria;
                        criteria.SearchCriteria = "contains";
                    }
                    $scope.page = page;
                    $scope.BusinessListProgressBar = false;
                    focus("tblCharitySearch");
                }, function (response) {
                    $scope.selectedEntity = null;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                });
            }

            // select search type
            $scope.selectSearchType = function () {
                $scope.charitySearchCriteria.ID = "";
            }

            $scope.searchFeinData = function (type, value) {
                $scope.cftFeinSearchcriteria.Type = type;
                $scope.cftFeinSearchcriteria.SearchValue = value;
                loadCFeinList(constant.ZERO); // loadCFeinList method is available in this file only
                $('#divCharitiesSearchResult').modal('toggle');
            };

            // search fein details associated to charity
            $scope.searchFein = function (searchform) {
                $scope.cftFeinSearchcriteria.IsSearch = true;
                $scope.isButtonSerach = true;
                loadCFeinList(searchform); // loadCFeinList method is available in this file only
            };

            //to get data for FEIN link
            function loadCFeinList(page) {
                //Ticket -- 3167
                $rootScope.isCFTBackButtonPressed = false;
                if ($rootScope.isCftFeinOrganizationSearchBack == true) {
                    page = page || constant.ZERO;
                    $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                    $scope.cftFeinSearchcriteria = $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);
                }
                else {
                    page = page || constant.ZERO;
                    $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                    //$scope.cftFeinSearchcriteria.Type = $scope.criteria.Type;
                    //$scope.cftFeinSearchcriteria.SearchValue = $scope.criteria.SearchValue;
                    $scope.cftFeinSearchcriteria.SearchCriteria = "";
                }
                var data = angular.copy($scope.cftFeinSearchcriteria);
                $scope.isButtonSerach = page == 0;
                // getCharityAmendRenewalDetails method is available in constants.js
                wacorpService.post(webservices.CFT.getCharityAmendRenewalDetails, data, function (response) {
                    $scope.feinDataDetails = response.data;
                    if ($scope.cftFeinSearchcriteria.PageID == 1)
                        //$('#divCharitiesSearchResult').modal('toggle');
                        $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);

                    if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                        var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                        $scope.pagesCount1 = response.data.length < $scope.cftFeinSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount1 : pagecount;
                        $scope.totalCount = totalcount;
                    }
                    $scope.page1 = page;
                    $scope.BusinessListProgressBar = false;
                }, function (response) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                });
            }

            $scope.cancel = function () {
                $("#divCharitiesSearchResult").modal('toggle');
            }



            //copypaste Reg Number
            $scope.setPastedRegNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                    $scope.charitySearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                        $scope.charitySearchCriteria.ID = pastedText;
                    });
                }
            };


            //copypaste Fein Number
            $scope.setPastedFeinNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.charitySearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.charitySearchCriteria.ID = pastedText;
                    });
                }
            };


            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.charitySearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.charitySearchCriteria.ID = pastedText;
                    });
                }
            };

            $scope.setUBILength = function (e) {
                if (e.currentTarget.value != undefined && e.currentTarget.value != null && e.currentTarget.value != "" && e.currentTarget.value.length >= 9)
                {
                    if (e.which != 97)
                    {
                        // Allow: backspace, delete, tab, escape, enter and .
                        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                            // Allow: Ctrl+A, Command+A
                            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                            // Allow: home, end, left, right, down, up
                            (e.keyCode >= 35 && e.keyCode <= 40)) {
                            // let it happen, don't do anything
                            return;
                        }
                        // Ensure that it is a number and stop the keypress
                        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                            e.preventDefault();
                        }
                        e.preventDefault();
                    }
                }
            };

            //navigate to business information
            $scope.showBusineInfo = function (id, businessType, flag) {
                //Ticket -- 3167
                $rootScope.isCFTBackButtonPressed = false;
                if (!flag) {
                    $scope.charitySearchCriteria.CFTId = id;
                    $scope.charitySearchCriteria.Businesstype = businessType;
                    //$scope.charitySearchCriteria.isCharityEntitySearch = true;
                    $rootScope.data = $scope.charitySearchCriteria;
                    $rootScope.isCharityEntitySearch = true;
                    $cookieStore.put('cftBusinessSearchListcriteriaId', id);
                    $cookieStore.put('cftBusinessSearchListcriteriaType', businessType);
                    //$location.path("/organization");
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityFoundationOrganization();
                }
                else {
                    $scope.charitySearchCriteria.CFTId = id;
                    $scope.charitySearchCriteria.Businesstype = businessType;
                    //$scope.charitySearchCriteria.isFeinCharityEntitySearch = true;
                    $rootScope.data = $scope.charitySearchCriteria;
                    $rootScope.isCharityEntitySearch = true;
                    $scope.navigate($rootScope.data); // navigate method is available in this file only
                }

            }

            //$scope.showFeinBusineInfo = function (id, businessType) {
            //    $scope.cftFeinSearchcriteria.CFTId = id;
            //    $scope.cftFeinSearchcriteria.Businesstype = businessType;
            //    $scope.cftFeinSearchcriteria.isCharityEntitySearch = true;
            //    $rootScope.data = $scope.cftFeinSearchcriteria;
            //    $cookieStore.put('cftFeinBusinessSearchListcriteriaId', id);
            //    $cookieStore.put('cftFeinBusinessSearchListcriteriaType', businessType);
            //    //$rootScope.isCharityEntitySearch = true;
            //   // $window.open('#/organization', $rootScope.data, "_blank");
            //    $scope.navigate($rootScope.data);


            //    //$location.path("/organization");
            //    //$scope.window = $window.open('', '_blank');
            //    //angular
            //    //    .element($scope.window.document.body)
            //    //    .append($compile($element.contents())($scope));

            //    //$scope.navCharityFoundationOrganization();
            //}

            $scope.navigate = function (data) {
                $window.sessionStorage.removeItem('orgData');
                var obj = {
                    org: data,
                    viewMode: true,
                    flag: true,

                }
                $window.sessionStorage.setItem('orgData', JSON.stringify(obj));
                $window.open('#/organization', "_blank");
                $window.sessionStorage.removeItem('orgData');
            }

            $scope.navCharityFoundationOrganization = function () { $rootScope.modal = null; $rootScope.searchCriteria = null; $location.path("/organization"); };

            $scope.$watch('CharityList', function () {
                if ($scope.CharityList == undefined)
                    return;
                if ($scope.CharityList.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);

            //Ticket -- 3167
            $scope.initCFTSearch = function () {
                if ($rootScope.isSearchNavClicked) {
                    $scope.clearFun();
                }
            };

        },
    }
});


wacorpApp.directive('charityOptionalEntitySearch', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CharitiesOptionalSearch/_CharityOptionalEntitySearch.html',
        restrict: 'A',
        scope: {
            searchType: '=?searchType',
            selectedEntity: '=?selectedEntity',
            submitFunc: '&?submitFunc',
        },
        controller: function ($scope, wacorpService, focus, $rootScope, $cookieStore, $timeout, $routeParams, $location, $window, $compile, $element) {
            // declare scope variables
            $scope.page = constant.ZERO;
            $scope.page1 = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.pagesCount1 = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.messages = messages;
            $scope.feinDataDetails = [];
            $scope.searchType = $scope.searchType || "";
            
            $scope.charitySearchCriteria = { Type: searchTypes.RegistrationNumber, ID: "", CFTId: "", Businesstype: "", isCftOrganizationSearchBack: false, isCftFeinOrganizationSearchBack: false, IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, IsOnline: true, SearchType: $scope.searchType, isSearchClick: false, isCharityEntitySearch: false, isFeinCharityEntitySearch: false, SortBy: null, SortType: null, };
            //$scope.cftFeinSearchcriteria = {
            //    CFTId: "", EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, isCftOrganizationSearchBack:false, IsSearch: false, EntityWebsite: null,
            //    RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, Businesstype: "", Type: "", SearchValue: "", SearchCriteria: "",
            //};
            $scope.cftFeinSearchcriteria = {
                CFTId: "",ID:"", EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN,  IsSearch: false, EntityWebsite: null,
                RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, Businesstype: "", Type: "", SearchValue: "", SearchCriteria: "",  isSearchClick: false,
            };
            
            $scope.selectedEntity = null;
            var criteria = null;
            $scope.search = loadCharityList;
            $scope.searchval = '';
            $scope.isButtonSerach = false;
            focus("entityNameSearchField");

            $scope.submitCharityEntity = function () {

                angular.forEach(CFTStatus, function (value, data) {
                    if ($scope.Status != value.closed && $scope.Status != value.involuntaryClosure) {
                        if ($scope.submitFunc) {
                            $scope.submitFunc();
                        }
                    }
                    else {
                        // Folder Name: app Folder
                        // Alert Name: alert method is available in alertMessages.js
                        wacorpService.alertDialog(messages.CFTPublicSearch.alert);
                    }

                });
            };

            var url = $location.path();
            if (typeof (url) != typeof (undefined) && url != "" && url != null) {
                $rootScope.businessFilingType = url.split('/')[2];
            }

            if ($rootScope.data != null) {
                $scope.charitySearchCriteria = $rootScope.data;
                $scope.isButtonSerach = true

                $scope.cftFeinSearchcriteria.SearchValue = $rootScope.data.CFTId;
                $scope.cftFeinSearchcriteria.Type = $rootScope.data.Type;
                $cookieStore.put('cftOptionalFeinSearchcriteria', $scope.cftFeinSearchcriteria);
                $rootScope.data=null;
                loadCharityList(constant.ZERO); // loadCharityList method is available in this file only.
               
            }
            // search cft list
            $scope.searchEntity = function (searchform) {
                $scope.isShowErrorFlag = true;
                if ($scope[searchform].$valid) {
                    $scope.charitySearchCriteria.isSearchClick = true;
                    $scope.isShowErrorFlag = false;
                    $scope.isButtonSerach = true
                    loadCharityList(constant.ZERO); // loadCharityList method is available in this file only.
                }
            };
            //clear text on selecting radio button
            $scope.cleartext = function () {
                $scope.charitySearchCriteria.ID = null;
                $scope.charitySearchCriteria.OrgName = null;
            };

            // clear fields
            $scope.clearFun = function () {
                $scope.charitySearchCriteria.ID = "";
                $scope.charitySearchCriteria.OrgName = "";
                $scope.charitySearchCriteria.isSearchClick = false;
                $scope.charitySearchCriteria.Type = searchTypes.RegistrationNumber;
                $scope.isShowErrorFlag = false;
            };

            // get selected entity information
            $scope.getSelectedEntity = function (charityEntity) {
                $scope.selectedEntity = charityEntity;
                $scope.selectedEntityID = charityEntity.CFTId || $scope.charitySearchCriteria.OrgName;
                $scope.Status = charityEntity.Status;
            };

            // get charity list data from server
            function loadCharityList(page, sortBy) {
                 
                page = page || constant.ZERO;
                $scope.charitySearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                $scope.selectedEntity = null;
                if (sortBy != undefined) {
                    if ($scope.charitySearchCriteria.SortBy == sortBy) {
                        if ($scope.charitySearchCriteria.SortType == 'ASC') {
                            $scope.charitySearchCriteria.SortType = 'DESC';
                        }
                        else {
                            $scope.charitySearchCriteria.SortType = 'ASC';
                        }
                    }
                    else {
                        $scope.charitySearchCriteria.SortBy = sortBy;
                        $scope.charitySearchCriteria.SortType = 'ASC';
                    }
                }
                var data = angular.copy($scope.charitySearchCriteria);
                $scope.isButtonSerach = page == 0;
                $rootScope.isCharityEntitySearch = false;
                data.ID = angular.copy($scope.isButtonSerach ? $scope.charitySearchCriteria.ID || $scope.charitySearchCriteria.OrgName : $scope.searchval);
                if (criteria == null) {
                    criteria = {};
                    criteria.Type = $scope.charitySearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.SearchCriteria = "contains";
                    //criteria.ID = constant.ONE;
                    criteria.PageCount = 10;
                    //criteria.TotalRowCount = $scope.totalCount;
                    criteria.PageID = $scope.charitySearchCriteria.PageID;
                    criteria.SortBy = $scope.charitySearchCriteria.SortBy
                    criteria.SortType = $scope.charitySearchCriteria.SortType
                }
                else {
                    criteria.Type = $scope.charitySearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.charitySearchCriteria.PageID;
                    criteria.SortBy = $scope.charitySearchCriteria.SortBy
                    criteria.SortType = $scope.charitySearchCriteria.SortType
                }
                
                wacorpService.post(webservices.CFT.getCharityOptionalSearchResult, criteria, function (response) {
                    $scope.selectedEntity = null;
                    $scope.CharityList = response.data;
                    $scope.selectedEntityID = null;
                    if ($scope.isButtonSerach && response.data.length > 0) {
                        var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                        $scope.pagesCount = response.data.length < $scope.charitySearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                        $scope.totalCount = totalcount;
                        //$scope.searchval = angular.copy($scope.isButtonSerach ? $scope.charitySearchCriteria.ID : $scope.searchval);
                        $scope.searchval = criteria.SearchValue;
                        criteria = response.data[constant.ZERO].Criteria;
                        criteria.SearchCriteria = "contains";
                    }
                    $scope.page = page;
                    $scope.BusinessListProgressBar = false;
                    focus("tblCharitySearch");
                }, function (response) {
                    $scope.selectedEntity = null;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                });
            }

            // select search type
            $scope.selectSearchType = function () {
                $scope.charitySearchCriteria.ID = "";
            }

            $scope.searchFeinData = function (type, value) {
                $scope.cftFeinSearchcriteria.Type = type;
                $scope.cftFeinSearchcriteria.SearchValue = value;
                loadCFeinList(constant.ZERO); // loadCFeinList method is available in this file only.
                $('#divCharitiesSearchResult').modal('toggle');
            };

            // search fein details associated to charity
            $scope.searchFein = function (searchform) {
                $scope.cftFeinSearchcriteria.IsSearch = true;
                $scope.isButtonSerach = true;
                loadCFeinList(searchform); // loadCFeinList method is available in this file only.
            };

            //to get data for FEIN link
            function loadCFeinList(page) {
                 
                //if ($rootScope.isCftFeinOrganizationSearchBack == true) {
                if ($rootScope.isOptionalCftFeinOrganizationSearchBack == true){
                    page = page || constant.ZERO;
                    $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                    //$scope.cftFeinSearchcriteria = $cookieStore.get('cftOptionalFeinSearchcriteria',$scope.cftFeinSearchcriteria);
                }
                else {
                    page = page || constant.ZERO;
                    $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                    //$scope.cftFeinSearchcriteria.Type = $scope.criteria.Type;
                    //$scope.cftFeinSearchcriteria.SearchValue = $scope.criteria.SearchValue;
                    $scope.cftFeinSearchcriteria.SearchCriteria = "";
                }
                var data = angular.copy($scope.cftFeinSearchcriteria);
                $scope.isButtonSerach = page == 0;
                // getCharityOptionalSearchResult method is available in constants.js
                wacorpService.post(webservices.CFT.getCharityOptionalSearchResult, data, function (response) {
                    $scope.feinDataDetails = response.data;
                    if ($scope.cftFeinSearchcriteria.PageID==1)
                        //$('#divCharitiesSearchResult').modal('toggle');
                        $cookieStore.put('cftOptionalFeinSearchcriteria', $scope.cftFeinSearchcriteria);

                    if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                        var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                        $scope.pagesCount1 = response.data.length < $scope.cftFeinSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount1 : pagecount;
                        $scope.totalCount = totalcount;
                    }
                    $scope.page1 = page;
                    $scope.BusinessListProgressBar = false;
                }, function (response) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                });
            }

            $scope.cancel = function () {
                $("#divCharitiesSearchResult").modal('toggle');
            }

            //copypaste Reg Number
            $scope.setPastedRegNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                    $scope.charitySearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                        $scope.charitySearchCriteria.ID = pastedText;
                    });
                }
            };


            //copypaste Fein Number
            $scope.setPastedFeinNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.charitySearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.charitySearchCriteria.ID = pastedText;
                    });
                }
            };


            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.charitySearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.charitySearchCriteria.ID = pastedText;
                    });
                }
            };

            $scope.setUBILength = function (e) {
                if (e.currentTarget.value != undefined && e.currentTarget.value.length != null && e.currentTarget.value.length!="" && e.currentTarget.value.length >= 9) {
                    // Allow: backspace, delete, tab, escape, enter and .
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                        // Allow: Ctrl+A, Command+A
                        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                        // Allow: home, end, left, right, down, up
                        (e.keyCode >= 35 && e.keyCode <= 40)) {
                        // let it happen, don't do anything
                        return;
                    }
                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                    }
                    e.preventDefault();
                }
            };

            //navigate to business information
            $scope.showBusineInfo = function (id, businessType, flag) {
                if (!flag)
                {
                    $scope.charitySearchCriteria.CFTId = id;
                    $scope.charitySearchCriteria.Businesstype = businessType;
                    //$scope.charitySearchCriteria.isCharityEntitySearch = true;
                    $rootScope.data = $scope.charitySearchCriteria;
                    //$rootScope.isCharityEntitySearch = true;
                    $rootScope.isOptionalCharityEntitySearch = true;
                    //$cookieStore.put('cftBusinessSearchListcriteriaId', id);
                    //$cookieStore.put('cftBusinessSearchListcriteriaType', businessType);
                    $cookieStore.put('cftOptionalBusinessSearchListcriteriaId', id);
                    $cookieStore.put('cftOptionalBusinessSearchListcriteriaType', businessType);
                    //$location.path("/organization");
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityFoundationOrganization();
                }
                else {
                    $scope.charitySearchCriteria.CFTId = id;
                    $scope.charitySearchCriteria.Businesstype = businessType;
                    //$scope.charitySearchCriteria.isFeinCharityEntitySearch = true;
                    $rootScope.data = $scope.charitySearchCriteria;
                    //$rootScope.isCharityEntitySearch = true;
                    $rootScope.isOptionalCharityEntitySearch = true;
                    $scope.navigate($rootScope.data); // navigate method is available in this file only
                }
                
            }

            //$scope.showFeinBusineInfo = function (id, businessType) {
            //    $scope.cftFeinSearchcriteria.CFTId = id;
            //    $scope.cftFeinSearchcriteria.Businesstype = businessType;
            //    $scope.cftFeinSearchcriteria.isCharityEntitySearch = true;
            //    $rootScope.data = $scope.cftFeinSearchcriteria;
            //    $cookieStore.put('cftFeinBusinessSearchListcriteriaId', id);
            //    $cookieStore.put('cftFeinBusinessSearchListcriteriaType', businessType);
            //    //$rootScope.isCharityEntitySearch = true;
            //   // $window.open('#/organization', $rootScope.data, "_blank");
            //    $scope.navigate($rootScope.data);
               
                
            //    //$location.path("/organization");
            //    //$scope.window = $window.open('', '_blank');
            //    //angular
            //    //    .element($scope.window.document.body)
            //    //    .append($compile($element.contents())($scope));

            //    //$scope.navCharityFoundationOrganization();
            //}
         
            $scope.navigate = function(data) {
                $window.sessionStorage.removeItem('orgData');
                var obj = {
                    org: data,
                    viewMode: true,
                    type:'Optional',

                }
                $window.sessionStorage.setItem('orgData', JSON.stringify(obj));
                $window.open('#/organization', "_blank");
                $window.sessionStorage.removeItem('orgData');
            }

            $scope.navCharityFoundationOrganization = function () { $rootScope.modal = null; $rootScope.searchCriteria = null; $location.path("/organization"); };

            $scope.$watch('CharityList', function () {
                if ($scope.CharityList == undefined)
                    return;
                if ($scope.CharityList.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);
        },
    }
});


wacorpApp.directive('trusteeEntitySearch', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/TrusteeEntitySearch/_trusteeEntitySearch.html',
        restrict: 'A',
        scope: {
            searchType: '=?searchType',
            selectedBusiness: '=?selectedBusiness',
            submitFunc: '&?submitFunc',
        },
        controller: function ($scope, wacorpService, focus, $rootScope, $cookieStore, $timeout, $routeParams, $location, $window, $compile, $element) {
            // declare scope variables
            $scope.page = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.messages = messages;
            $scope.searchType = $scope.searchType || "";
            $scope.businessSearchCriteria = { Type: searchTypes.RegistrationNumber, ID: "", PageID: constant.ONE, PageCount: constant.TEN, SearchType: $scope.searchType, isSearchClick: false, SortBy: null, SortType: null, };
            $scope.selectedBusiness = null;
            $scope.search = loadbusinessList;
            $scope.searchval = '';
            $scope.isButtonSerach = false;
            focus("searchField");
            var url = $location.path();
            if (typeof (url) != typeof (undefined) && url != "" && url != null) {
                $rootScope.businessFilingType = url.split('/')[2];
            }
            $scope.cftFeinSearchcriteria = {
                CFTId: "", ID: "", EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false, EntityWebsite: null, SortBy: null, SortType: null,
                RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, Businesstype: "", BusinessFilingType: "", Type: "", SearchValue: "", SearchCriteria: "", isSearchClick: false,
            };
            var criteria = null;

            $scope.submitBusiness = function () {

                angular.forEach(CFTStatus, function (value, data) {
                    if ($scope.Status != value.closed && $scope.Status != value.involuntaryClosure) {
                        if ($scope.submitFunc) {
                            $scope.submitFunc();
                        }
                    }
                    else {
                        // Folder Name: app Folder
                        // Alert Name: alert method is available in alertMessages.js 
                        wacorpService.alertDialog(messages.CFTPublicSearch.alert);
                    }
                });
                
            };

            if ($rootScope.data != null) {
                $scope.businessSearchCriteria = $rootScope.data;
                $scope.isButtonSerach = true

                $scope.cftFeinSearchcriteria.SearchValue = $rootScope.data.ID;
                $scope.cftFeinSearchcriteria.Type = $rootScope.data.Type;
                $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);
                $rootScope.data = null;
                loadbusinessList(constant.ZERO); // loadbusinessList method is available in this file only

            }

            // search business list
            $scope.searchBusiness = function (searchform) {
                $scope.isShowErrorFlag = true;
                if ($scope[searchform].$valid) {
                    $scope.businessSearchCriteria.isSearchClick = true;
                    $scope.isShowErrorFlag = false;
                    $scope.isButtonSerach = true;
                    loadbusinessList(constant.ZERO); // loadbusinessList method is available in this file only
                }
            };
            //clear text on selecting radiobutton
            $scope.cleartext = function () {
                $scope.businessSearchCriteria.ID = null;
                $scope.businessSearchCriteria.SortBy = null;
                $scope.businessSearchCriteria.SortType = null;

            };

            // clear fields
            $scope.clearFun = function () {
                $scope.businessSearchCriteria.ID = "";
                $scope.businessSearchCriteria.OrgName = "";
                $scope.businessSearchCriteria.isSearchClick = false;
                $scope.businessSearchCriteria.Type = searchTypes.RegistrationNumber;
                $scope.businessSearchCriteria.SortBy = null;
                $scope.businessSearchCriteria.SortType = null;
                $scope.isShowErrorFlag = false;
            };

            // get selected business information
            $scope.getSelectedBusiness = function (business) {
                $scope.selectedBusiness = business;
                $scope.selectedTrustID = business.TrustID;
                $scope.Status = business.Status;
            };


            // get business list data from server
            function loadbusinessList(page, sortBy) {
                //Ticket -- 3167
                $rootScope.isCFTBackButtonPressed = false;
                page = page || constant.ZERO;
                $scope.businessSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                $scope.selectedBusiness = null;
                if (sortBy != undefined) {
                    if ($scope.businessSearchCriteria.SortBy == sortBy) {
                        if ($scope.businessSearchCriteria.SortType == 'ASC') {
                            $scope.businessSearchCriteria.SortType = 'DESC';
                        }
                        else {
                            $scope.businessSearchCriteria.SortType = 'ASC';
                        }
                    }
                    else {
                        $scope.businessSearchCriteria.SortBy = sortBy;
                        $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                }
                else {
                    if ($scope.businessSearchCriteria.Type == "RegistrationNumber")
                    {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "Registration#";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.businessSearchCriteria.Type == "FEINNo")
                    {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "FEIN#";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.businessSearchCriteria.Type == "UBINumber") {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "UBI#";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                    else if ($scope.businessSearchCriteria.Type == "OrganizationName") {
                        if ($scope.businessSearchCriteria.SortBy == null || $scope.businessSearchCriteria.SortBy == "" || $scope.businessSearchCriteria.SortBy == undefined)
                            $scope.businessSearchCriteria.SortBy = "OrganizationName";
                        if ($scope.businessSearchCriteria.SortType == null || $scope.businessSearchCriteria.SortType == "" || $scope.businessSearchCriteria.SortType == undefined)
                            $scope.businessSearchCriteria.SortType = 'ASC';
                    }
                }
                var data = angular.copy($scope.businessSearchCriteria);
                $scope.isButtonSerach = page == 0;
                if ($scope.isButtonSerach)
                    data.ID = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID || $scope.businessSearchCriteria.OrgName : $scope.searchval);
                else {
                    if ($scope.businessSearchCriteria.Type == "OrganizationName" && $scope.businessSearchCriteria.OrgName)
                        data.ID = $scope.businessSearchCriteria.OrgName
                }
                if (criteria == null) {
                    criteria = {};
                    criteria.Type = $scope.businessSearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.SearchCriteria = "contains";
                    //criteria.ID = constant.ONE;
                    criteria.PageCount = 10;
                    //criteria.TotalRowCount = $scope.totalCount;
                    criteria.PageID = $scope.businessSearchCriteria.PageID;
                }
                else {
                    criteria.Type = $scope.businessSearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.businessSearchCriteria.PageID;
                    //criteria.BusinessFilingType = ;
                }
                // getTrusteeSearchDetails method is available in constants.js
                wacorpService.post(webservices.CFT.getTrusteeSearchDetails, data, function (response) {
                    $scope.selectedBusiness = null;
                    $scope.BusinessList = response.data;
                    $scope.selectedTrustID =null
                    if ($scope.isButtonSerach && response.data.length > 0) {
                        var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                        $scope.pagesCount = response.data.length < $scope.businessSearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                        $scope.totalCount = totalcount;
                        $scope.searchval = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID : $scope.searchval);
                    }
                    $scope.page = page;
                    $scope.BusinessListProgressBar = false;
                    focus("tblBusinessSearch");
                }, function (response) {
                    $scope.selectedBusiness = null;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                });
            }

            // select search type
            $scope.selectSearchType = function () {
                $scope.businessSearchCriteria.ID = "";
            }

            //copypaste Reg Number
            $scope.setPastedRegNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                    $scope.businessSearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                        $scope.businessSearchCriteria.ID = pastedText;
                    });
                }
            };

            //copypaste Fein Number
            $scope.setPastedFeinNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.businessSearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.businessSearchCriteria.ID = pastedText;
                    });
                }
            };

            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.businessSearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.businessSearchCriteria.ID = pastedText;
                    });
                }
            };

            $scope.setUBILength = function (e) {
                //if (e.currentTarget.value.length >= 9) {
                //    e.preventDefault();
                //}
                if (e.currentTarget.value != undefined && e.currentTarget.value != "" && e.currentTarget.value != null && e.currentTarget.value.length >= 9)
                {
                    if (e.which != 97)
                    {
                        // Allow: backspace, delete, tab, escape, enter and .
                        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                            // Allow: Ctrl+A, Command+A
                            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                            // Allow: home, end, left, right, down, up
                            (e.keyCode >= 35 && e.keyCode <= 40)) {
                            // let it happen, don't do anything
                            return;
                        }
                        // Ensure that it is a number and stop the keypress
                        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                            e.preventDefault();
                        }
                        e.preventDefault();
                    }
                }
            };


            // Search FEIN Information
            $scope.searchFeinData = function (type, value) {
                $scope.cftFeinSearchcriteria.Type = type;
                $scope.cftFeinSearchcriteria.SearchValue = value;
                loadCFeinList(constant.ZERO); // loadCFeinList method is available in this file only
                $('#divFundraiserSearchResult').modal('toggle');
            };

            // search fein details associated to charity
            $scope.searchFein = function (searchform) {
                $scope.cftFeinSearchcriteria.IsSearch = true;
                $scope.isButtonSerach = true;
                loadCFeinList(searchform); // loadCFeinList method is available in this file only
            };



            //to get data for FEIN link
            function loadCFeinList(page) {
                //Ticket -- 3167
                $rootScope.isCFTBackButtonPressed = false;
                if ($rootScope.isCftFeinOrganizationSearchBack == true) {
                    page = page || constant.ZERO;
                    $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                    $scope.cftFeinSearchcriteria = $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);
                }
                else {
                    page = page || constant.ZERO;
                    $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                    //$scope.cftFeinSearchcriteria.Type = $scope.criteria.Type;
                    //$scope.cftFeinSearchcriteria.SearchValue = $scope.criteria.SearchValue;
                    $scope.cftFeinSearchcriteria.SearchCriteria = "";
                }
                var data = angular.copy($scope.cftFeinSearchcriteria);
                $scope.isButtonSerach = page == 0;
                // getTrusteeSearchDetails method is available in constants.js
                wacorpService.post(webservices.CFT.getTrusteeSearchDetails, data, function (response) {
                    $scope.feinDataDetails = response.data;
                    if ($scope.cftFeinSearchcriteria.PageID == 1)
                        //$('#divFundraiserSearchResult').modal('toggle');
                        $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);

                    if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                        var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                        $scope.pagesCount1 = response.data.length < $scope.cftFeinSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount1 : pagecount;
                        $scope.totalCount = totalcount;
                    }
                    $scope.page1 = page;
                    $scope.BusinessListProgressBar = false;
                }, function (response) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                });
            }

            $scope.cancel = function () {
                $("#divFundraiserSearchResult").modal('toggle');
            }
            //navigate to business information
            $scope.showBusineInfo = function (id, businessType, flag) {
                //Ticket -- 3167
                $rootScope.isCFTBackButtonPressed = false;
                if (!flag) {
                    $scope.businessSearchCriteria.CFTId = id;
                    $scope.businessSearchCriteria.Businesstype = businessType;
                    //$scope.businessSearchCriteria.isFundraiserEntitySearch = true;
                    $rootScope.data = $scope.businessSearchCriteria;
                    $rootScope.isFundraiserEntitySearch = true;
                    $cookieStore.put('cftBusinessSearchListcriteriaId', id);
                    $cookieStore.put('cftBusinessSearchListcriteriaType', businessType);
                    //$location.path("/organization");
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityFoundationOrganization();
                }
                else {
                    $scope.businessSearchCriteria.CFTId = id;
                    $scope.businessSearchCriteria.Businesstype = businessType;
                    //$scope.businessSearchCriteria.isFeinCharityEntitySearch = true;
                    $rootScope.data = $scope.businessSearchCriteria;
                    $rootScope.isFundraiserEntitySearch = true;
                    $scope.navigate($rootScope.data); // navigate method is available in this file only
                }

            };

            $scope.navigate = function (data) {
                $window.sessionStorage.removeItem('orgData');
                var obj = {
                    org: data,
                    viewMode: true,
                    flag: true,

                }
                $window.sessionStorage.setItem('orgData', JSON.stringify(obj));
                $window.open('#/organization', "_blank");
                $window.sessionStorage.removeItem('orgData');
            }

            $scope.navCharityFoundationOrganization = function () { $rootScope.modal = null; $rootScope.searchCriteria = null; $location.path("/organization"); };


            $scope.$watch('BusinessList', function () {
                if ($scope.BusinessList == undefined)
                    return;
                if ($scope.BusinessList.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);

            //Ticket -- 3167
            $scope.initCFTSearch = function () {
                if ($rootScope.isSearchNavClicked) {
                    $scope.clearFun();
                }
            };

        },
    }
});


wacorpApp.directive('directoryInformation', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/DirectoryInformation/_directoryInformation.html',
        restrict: 'A',
        scope: {
            directoryInformationData: '=?directoryInformationData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.Countries = [];
            $scope.States = [];
           // $scope.ValidateErrorMessage = false;

            var directoryInformationScope = { IsIncludedInWACharitableTrust:false,OrganizationType:"",PurposeId: "", PurposeDesc: "",IsOrgAcceptUnsolicitApplication:"",isOrganization501:false,
                                                    IsOtherOrganization: false, IsIndividuals: false, AverageGrantSize: "", IsGeographicServiceAreaWA: false, IsGeographicServiceAreaPacificNorthwest: false,
                                                    IsGeographicServiceAreaUS: false, IsGSAreaLocal: false, GeographicServiceAreaLocal: "", IsGSAreaOther: false, GeographicServiceAreaOther: false,
                                                    IsInitialApproachLetter: false, IsInitialApproachPacket: false, IsInitialApproachEmail: false, InitialApproachEmail: "", IsInitialApproachTelephoneCall: false,
                                                    IsInitialApproachDoNotCall: false, IsInitialApproachOther: false, GeographicServiceAreaOther:""
                                            };

            //var directoryInformationScopeReset = {
            //    IsIncludedInWACharitableTrust: false, OrganizationType: "", PurposeId: "", PurposeDesc: "", IsOrgAcceptUnsolicitApplication: "", isOrganization501: false,
            //    IsOtherOrganization: false, IsIndividuals: false, AverageGrantSize: "", IsGeographicServiceAreaWA: false, IsGeographicServiceAreaPacificNorthwest: false,
            //    IsGeographicServiceAreaUS: false, IsGSAreaLocal: false, GeographicServiceAreaLocal: "", IsGSAreaOther: false, GeographicServiceAreaOther: false,
            //    IsInitialApproachLetter: false, IsInitialApproachPacket: false, IsInitialApproachEmail: false, InitialApproachEmail: "", IsInitialApproachTelephoneCall: false,
            //    IsInitialApproachDoNotCall: false, IsInitialApproachOther: false, GeographicServiceAreaOther: ""
            //};


            $scope.directoryInformationData = $scope.directoryInformationData ? angular.extend(directoryInformationScope, $scope.directoryInformationData) : angular.copy(directoryInformationScope);
            
            //Dont Wish To Include in WA Charitable Trust Directory
            $scope.notIncludedInfTrustDirectory = function () {
                if (!$scope.directoryInformationData.IsIncludedInWACharitableTrust) {
                    resetdirectoryInformationScope(); // resetdirectoryInformationScope method is available in this file only
                }
            };

            var resetdirectoryInformationScope = function () {
                $scope.directoryInformationData.IsIncludedInWACharitableTrust = false;
                $scope.directoryInformationData.OrganizationType = "";
                $scope.directoryInformationData.PurposeId = "";
                $scope.directoryInformationData.PurposeDesc = "";
                $scope.directoryInformationData.IsOrgAcceptUnsolicitApplication = "";
                $scope.directoryInformationData.isOrganization501 = false;
                $scope.directoryInformationData.IsOtherOrganization = false;
                $scope.directoryInformationData.IsIndividuals = false;
                $scope.directoryInformationData.AverageGrantSize = "";
                $scope.directoryInformationData.IsGeographicServiceAreaWA = false;
                $scope.directoryInformationData.IsGeographicServiceAreaPacificNorthwest = false;
                $scope.directoryInformationData.IsGeographicServiceAreaUS = false;
                $scope.directoryInformationData.IsGSAreaLocal = false;
                $scope.directoryInformationData.GeographicServiceAreaLocal = "";
                $scope.directoryInformationData.IsGSAreaOther = false;
                $scope.directoryInformationData.GeographicServiceAreaOther = false;
                $scope.directoryInformationData.IsInitialApproachLetter = false;
                $scope.directoryInformationData.IsInitialApproachPacket = false;
                $scope.directoryInformationData.IsInitialApproachEmail = false;
                $scope.directoryInformationData.InitialApproachEmail = "";
                $scope.directoryInformationData.IsInitialApproachTelephoneCall = false;
                $scope.directoryInformationData.IsInitialApproachDoNotCall = false;
                $scope.directoryInformationData.IsInitialApproachOther = false;
                $scope.directoryInformationData.GeographicServiceAreaOther = ""
            };

            //$scope.watchCollectionObj = ['directoryInformationData.IsInitialApproachOther', 'directoryInformationData.IsInitialApproachEmail', 'directoryInformationData.IsGSAreaOther', 'directoryInformationData.IsGSAreaLocal'];

            $scope.$watchGroup(['directoryInformationData.IsInitialApproachOther', 'directoryInformationData.IsInitialApproachEmail', 'directoryInformationData.IsGSAreaOther', 'directoryInformationData.IsGSAreaLocal'], function (n, o) {
                if (!$scope.directoryInformationData.IsGSAreaLocal) {
                    $scope.directoryInformationData.GeographicServiceAreaLocal = "";
                }
                if (!$scope.directoryInformationData.IsGSAreaOther) {
                    $scope.directoryInformationData.GeographicServiceAreaOther = "";
                }
                if (!$scope.directoryInformationData.IsInitialApproachEmail) {
                    $scope.directoryInformationData.InitialApproachEmail = "";
                }
                if (!$scope.directoryInformationData.IsInitialApproachOther) {
                    $scope.directoryInformationData.InitialApproachOther = "";
                }
            });

            //Email validation
            $scope.ValidateDirectoryConfirmEmailAddress = function () {
                if ($scope.directoryInformationData.InitialApproachEmail != "" && $scope.directoryInformationData.CompareInitialApproachEmail != "" && (($scope.directoryInformationData.InitialApproachEmail).toUpperCase() != ($scope.directoryInformationData.CompareInitialApproachEmail).toUpperCase())) {
                    setTimeout(function () {
                        // Folder Name: app Folder
                        // Alert Name: emailMatch method is available in alertMessages.js 
                        wacorpService.alertDialog($scope.messages.PrincipalOffice.emailMatch);
                        $('#txtInitialApproachEmail').focus();
                    }, 10);
                }
            };

        },
    };
});

wacorpApp.directive('organizationPurpose', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/OrganizationPurpose/_organizationPurpose.html',
        restrict: 'A',
        scope: {
            purposeOptions: '=?purposeOptions',
            purposeModel: '=?purposeModel',
            dropdownsettings: '=?dropdownsettings',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, $rootScope, lookupService) {
            $scope.purposeOptions = $scope.purposeOptions || [];
            $scope.purposeModel = $scope.purposeModel || [];
            var settingScope = { scrollableHeight: '200px', scrollable: true, key: "Value", value: "Key", isKeyList: false, selectall: false };
            $scope.dropdownsettings = $scope.dropdownsettings ? angular.extend(settingScope, $scope.dropdownsettings) : angular.copy(settingScope);
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;

            $scope.Init = function () {
                $scope.messages = messages;
                $scope.selectedItems = [];
                var lookupPurposeParams = { params: { name: 'TRUSTPURPOSE' } };
                // getOrganizationPurposeTypes method is available in constants.js
                wacorpService.get(webservices.CFT.getOrganizationPurposeTypes, lookupPurposeParams, function (response) {
                    $scope.purposeOptions = response.data;

                    if (angular.isArray($scope.purposeModel.PurposeId) && $scope.purposeModel.PurposeId.length > 0) {
                        $scope.purposeModel.PurposeId.filter(function (purpose) {
                            for (var i = 0; i < response.data.length; i++) {
                                if (purpose == response.data[i].Key) {
                                    $scope.selectedItems.push(response.data[i]);
                                    break;
                                }
                            }
                        });
                    }
                });
            };

        },
    };
});
wacorpApp.directive('trustFinancialInfo', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustFinancialInfo/_trustFinancialInfo.html',
        restrict: 'A',
        scope: {
            financialInfoData: '=?financialInfoData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
            showFinancialHistory: '=?showFinancialHistory',
            financialBtn: '=?financialBtn',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.IRSDocumentTypes = [];
            $scope.ValidateFinancialEndDateMessage = false;
            $scope.UploadTaxReturnList = [];
            var financialInfoScope = {
                IsFIFullAccountingYear: "", AccountingyearBeginningDate: "", AccountingyearEndingDate: "", FirstAccountingyearEndDate: "",
                BeginingGrossAssets: null, TotalRevenue: null, Compensation: null, GrantContributionsProgramService: null, Comments: "", IsFiscalAccountingYearReported: false, FiscalYearReportedType: "",
                TotalExpenses: null, EndingGrossAssets: null, IsDocumentAttached: false, IsFirstAccountingYear: "", FiscalYearOther: "", IRSDocumentId: "", OldIRSDocumentId: "",
                FinancialId: "", UploadTaxReturnList: [], FinancialInfoIRSUploadTypeText: "", CFTFinancialHistoryList: []
            };

            $scope.financialInfoData = $scope.financialInfoData ? angular.extend(financialInfoScope, $scope.financialInfoData) : angular.copy(financialInfoScope);

            $scope.$watch('financialInfoData.IsFIFullAccountingYear', function () {
                if ($scope.financialInfoData.IsFIFullAccountingYear && ($scope.financialInfoData.BusinessFiling.FilingTypeName == 'CHARITABLE TRUST REGISTRATION' || $scope.financialInfoData.BusinessFiling.FilingTypeName == 'CHARITABLE TRUST RENEWAL')) {
                    $scope.isEdited = true;
                }
                else {
                    $scope.isEdited = false;
                }
            });

            var getIRSDocumentList = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.irsDocumentsList(function (response) { $scope.IRSDocumentTypes = response.data; });
            };

            getIRSDocumentList(); // getIRSDocumentList method is available in this file only

            var resultDate = "";
            $scope.CalculateEndDate = function () {
                if ($scope.financialInfoData.AccountingyearBeginningDate != null && $scope.financialInfoData.AccountingyearBeginningDate != "") {
                    var value = $scope.financialInfoData.AccountingyearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultDate = lastDayWithSlashes;
                        $scope.financialInfoData.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idEndDate").datepicker("setDate", lastDayWithSlashes);

                    }
                    else {
                        $scope.financialInfoData.AccountingyearEndingDate = null;
                    }
                }
            };

            $scope.ValidateEndDate = function () {
                if (new Date($scope.financialInfoData.AccountingyearEndingDate) < new Date($scope.financialInfoData.AccountingyearBeginningDate)) {
                    $scope.ValidateFinancialEndDateMessage = true;
                }
                else
                    $scope.ValidateFinancialEndDateMessage = false;
            };

            $scope.deleteAllFiles = function (files) {
                if (files.length > constant.ZERO) {
                    files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        // deleteAllUploadedFiles method is available in constants.js
                        wacorpService.post(webservices.Common.deleteAllUploadedFiles, files,
                            function (response) {
                                $scope.financialInfoData.UploadTaxReturnList = [];
                            },
                            function (response) {
                            }
                        );
                    },
                    function () {
                        $scope.financialInfoData.IsFIFullAccountingYear = true;
                    });
                }
            };

            $scope.IRSChange = function (irsId, docsList, oldIRS) {
                //if (irsId == 0) {
                if ($scope.financialInfoData.FinancialInfoIRSUpload != undefined && $scope.financialInfoData.FinancialInfoIRSUpload.length > 0) {
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        angular.forEach($scope.financialInfoData.FinancialInfoIRSUpload, function (value, data) {
                            if (value.BusinessFilingDocumentId > 0) {
                                value.Status = principalStatus.DELETE;
                            }
                            else {
                                var index = $scope.financialInfoData.FinancialInfoIRSUpload.indexOf(value);
                                $scope.financialInfoData.FinancialInfoIRSUpload.splice(index, 1);
                            }

                        });

                        angular.forEach($scope.IRSDocumentTypes, function (doc) {
                            if (doc.Key == $scope.financialInfoData.IRSDocumentId)
                                $scope.financialInfoData.FinancialInfoIRSUploadTypeText = doc.Value;
                        });

                    }, function () {
                        $scope.financialInfoData.IRSDocumentId = oldIRS;
                        angular.forEach($scope.IRSDocumentTypes, function (doc) {
                            if (doc.Key == $scope.financialInfoData.IRSDocumentId)
                                $scope.financialInfoData.FinancialInfoIRSUploadTypeText = doc.Value;
                        });
                    });
                }
                else {
                    $scope.financialInfoData.FinancialInfoIRSUpload = [];
                }
                //}
            };

        },
    };
});

wacorpApp.directive('trustOrganizationStructure', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustOrganizationStructure/_trustOrganizationStructure.html',
        restrict: 'A',
        scope: {
            organizationalStructureData: '=?organizationalStructureData',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.isReview = $scope.isReview || false;
            $scope.ArticlesofIncorporation = TrustOrganizationalType.ArticlesofIncorporation;
            $scope.TrustAgreement = TrustOrganizationalType.TrustAgreement;
            $scope.LastWilandTestament = TrustOrganizationalType.LastWilandTestament;
            $scope.ProbateOrder = TrustOrganizationalType.ProbateOrder;
             

            var fundraiserOrganizationalStructureScope = {
                OrganizationalStructureID: "", EstablishingTrustTypes: "", EstablishingTrustDocument: "", IsTrustInstrumentAttached: "", IsBeneficiaries: "",
                NameOfCorporation: "", NameOfTrust: "", OrgDateOfIncorporation: "", DateOfTrustEstablishment: "", Summarize: "", EstateOf: "",
                ProbatedCountyDesc: "", ProbatedCounty: "", ProbateDate: "", ProbateNumber: ""
            };

            $scope.organizationalStructureData = $scope.organizationalStructureData ? angular.extend(fundraiserOrganizationalStructureScope, $scope.organizationalStructureData) : angular.copy(fundraiserOrganizationalStructureScope);

            $scope.$watch('organizationalStructureData', function () {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.organizationalStructureData.OrgDateOfIncorporation = $scope.organizationalStructureData.OrgDateOfIncorporation == "0001-01-01T00:00:00" ? wacorpService.dateFormatService(new Date()) : wacorpService.dateFormatService($scope.organizationalStructureData.OrgDateOfIncorporation);
            }, true);

        },
    };
});
wacorpApp.directive('trustBeneficiaries', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustBeneficiaries/_trustBeneficiaries.html',
        restrict: 'A',
        scope: {
            trustBeneficiariesList: '=?trustBeneficiariesList',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.trustBeneficiariesList = $scope.trustBeneficiariesList || [];
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add New";
            $scope.ValidateErrorMessage = false;


            $scope.beneficiaries = {
                FirstName: "", SequenceNo: "",
                LegalInfoAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, LegalInfoStatus: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            var beneficiariesScopeData = {
                FirstName: "", SequenceNo: "",
                LegalInfoAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, LegalInfoStatus: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
            };

            //Reset the trust charitable organization
            $scope.resetBeneficiaries = function () {
                $scope.beneficiaries = angular.copy(beneficiariesScopeData);
                $scope.ValidateErrorMessage = false;
                $scope.addbuttonName = "Add New";
            };

            //Add trust charitable organization data
            $scope.AddBeneficiaries = function (trustBeneficiariesForm) {
                $scope.ValidateErrorMessage = true;
                if ($scope[trustBeneficiariesForm].$valid) {
                    $scope.ValidateErrorMessage = false;
                    if ($scope.beneficiaries.SequenceNo != "") {
                        angular.forEach($scope.trustBeneficiariesList, function (beneficiary) {
                            if (beneficiary.SequenceNo == $scope.beneficiaries.SequenceNo) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                $scope.beneficiaries.LegalInfoAddress.FullAddress = wacorpService.fullAddressService($scope.beneficiaries.LegalInfoAddress);
                                angular.copy($scope.beneficiaries, beneficiary);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.trustBeneficiariesList, function (beneficiary) {
                            if (maxId == constant.ZERO || beneficiary.SequenceNo > maxId)
                                maxId = beneficiary.SequenceNo;
                        });
                        $scope.beneficiaries.SequenceNo = ++maxId;
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.beneficiaries.LegalInfoAddress.FullAddress = wacorpService.fullAddressService($scope.beneficiaries.LegalInfoAddress);
                        $scope.beneficiaries.LegalInfoStatus = principalStatus.INSERT;
                        $scope.trustBeneficiariesList.push($scope.beneficiaries);
                    }
                    $scope.resetBeneficiaries(); // resetBeneficiaries method is available in this file only
                }
            };

            //Edit trust charitable organization data
            $scope.editBeneficiaries = function (beneficiariesData) {
                beneficiariesData.LegalInfoAddress.Country = beneficiariesData.LegalInfoAddress.Country || codes.USA;
                beneficiariesData.LegalInfoAddress.State = beneficiariesData.LegalInfoAddress.State || codes.USA;
                $scope.beneficiaries = angular.copy(beneficiariesData);
                $scope.beneficiaries.LegalInfoStatus = principalStatus.UPDATE;
                $scope.addbuttonName = "Update";
            };

            //Delete trust charitable organization data
            $scope.deleteBeneficiaries = function (beneficiariesData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    //var index = $scope.trustBeneficiariesList.indexOf(beneficiariesData);
                    //$scope.trustBeneficiariesList.splice(index, 1);
                    beneficiariesData.LegalInfoStatus = principalStatus.DELETE;
                    $scope.resetBeneficiaries(); // resetBeneficiaries method is available in this file only
                });
            };

            // Clear all controls data
            $scope.clearBeneficiaries = function () {
                $scope.resetBeneficiaries(); // resetBeneficiaries method is available in this file only
            };

        },
    };
});

wacorpApp.controller('trustClosureController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.ValidateFinancialEndDateMessage = false;
    $scope.IsFirstAcctyear = null;
    $scope.beginningdate = null;
    $scope.endingdate = null;
    //$scope.beginingAssest = null;
    $scope.isReview = false;
    $scope.addedReasons = [];
    $scope.isClosureAttestation = false;
    if ($rootScope.isClosureAttestation != true)
        $rootScope.isClosureAttestation = false;
    var getIRSDocumentList = function () {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.irsDocumentsList(function (response) { $scope.IRSDocumentTypes = response.data; });
    };
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.getTrustDetails(); // getTrustDetails is available in this controller only.
        getIRSDocumentList(); // getIRSDocumentList is available in this controller only.
    }

    $scope.getTrustDetails = function () {
        var data = null;
        data = {
            params: { TrustID: $routeParams.TrustID, TransactionID: $rootScope.transactionID }
        };
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            // TrustClosureCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.TrustClosureCriteria, data, function (response) {
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.BusinessTransaction.DateTimeReceived = wacorpService.dateFormatService(new Date());
                $scope.modal.BusinessTransaction.FilingDate = wacorpService.dateFormatService(new Date());
                $scope.modal.RenewalDate = wacorpService.dateFormatService($scope.modal.RenewalDate);

                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                $scope.modal.TrustClosureReasonList = ['Organization No Longer Exists', 'Organization not needed to register', 'Other'];
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.EffectiveClosureDate = wacorpService.dateFormatService($scope.modal.EffectiveClosureDate);
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
                $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
                $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);

                $scope.beginningdate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
                $scope.endingdate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
                $scope.IsFirstAcctyear = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);
                if (!$scope.modal.IsFIFullAccountingYear) {
                    var currentDate = new Date();
                    var newDate = new Date($scope.modal.FirstAccountingyearEndDate);
                    if (newDate > currentDate) {
                        $scope.modal.IsDateEditable = true;
                        $scope.modal.FirstAccountingyearEndDate = null;
                        $scope.modal.BeginingGrossAssets = null;
                    }
                }
                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }
                //$scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets || null;
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');
                if (!$rootScope.IsShoppingCart || $rootScope.IsShoppingCart == undefined) {
                    $scope.modal.CFTCorrespondenceAddress.Country = codes.USA;
                    $scope.modal.CFTCorrespondenceAddress.State = codes.WA;
                }
                else if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }
                checkForNAN(); // checkForNAN method is available in this controller only.

                $scope.modal.TotalRevenue = $scope.modal.IsTotalRevenueEmpty ? null : $scope.modal.TotalRevenue;
                $scope.modal.GrantContributionsProgramService = $scope.modal.IsGrantContributionsProgramServiceEmpty ? null : $scope.modal.GrantContributionsProgramService;
                $scope.modal.Compensation = $scope.modal.IsCompensationEmtpy ? null : $scope.modal.Compensation;
                $scope.modal.TotalExpenses = $scope.modal.IsTotalExpensesEmpty ? null : $scope.modal.TotalExpenses;
                $scope.modal.EndingGrossAssets = $scope.modal.IsTrustEndingGrossAssetsEmpty ? null : $scope.modal.EndingGrossAssets;

                $scope.modal.isHavingEntityOnUBISearch = angular.isNullorEmpty($scope.modal.UBINumber) ? false : true;

                if ($scope.modal.TrustClosureReason != null && $scope.modal.TrustClosureReason != "" && $scope.modal.TrustClosureReason != undefined)
                    $scope.addedReasons = $scope.modal.TrustClosureReason.split(',');
                else
                    $scope.addedReasons = [];

                $scope.modal.isShowReturnAddress = true;
            }, function (response) {
            });
        }
        else {
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            if ($scope.modal.TrustClosureReason != null && $scope.modal.TrustClosureReason != "" && $scope.modal.TrustClosureReason != undefined)
                $scope.addedReasons = $scope.modal.TrustClosureReason.split(',');
            else
                $scope.addedReasons = [];

            checkForNAN(); // checkForNAN method is available in this controller only.
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.BusinessTransaction.DateTimeReceived = wacorpService.dateFormatService($scope.modal.BusinessTransaction.DateTimeReceived);
            $scope.modal.BusinessTransaction.FilingDate = wacorpService.dateFormatService($scope.modal.BusinessTransaction.FilingDate);
            $scope.modal.RenewalDate = wacorpService.dateFormatService($scope.modal.RenewalDate);
            $scope.beginningdate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
            $scope.endingdate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
            $scope.IsFirstAcctyear = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);

            //Assigning 0's to Empty
            $scope.modal.TotalRevenue = $scope.modal.IsTotalRevenueEmpty ? null : $scope.modal.TotalRevenue;
            $scope.modal.GrantContributionsProgramService = $scope.modal.IsGrantContributionsProgramServiceEmpty ? null : $scope.modal.GrantContributionsProgramService;
            $scope.modal.Compensation = $scope.modal.IsCompensationEmtpy ? null : $scope.modal.Compensation;
            $scope.modal.TotalExpenses = $scope.modal.IsTotalExpensesEmpty ? null : $scope.modal.TotalExpenses;
            $scope.modal.EndingGrossAssets = $scope.modal.IsTrustEndingGrossAssetsEmpty ? null : $scope.modal.EndingGrossAssets;
            $scope.modal.BeginingGrossAssets = $scope.modal.IsTrustBeginingGrossAssetsEmpty ? null : $scope.modal.BeginingGrossAssets;
            $scope.modal.isShowReturnAddress = true;
        }
    };

    var checkForNAN = function () {
        $scope.modal.TotalRevenue = isNaN($scope.modal.TotalRevenue) ? null : $scope.modal.TotalRevenue;
        $scope.modal.GrantContributionsProgramService = isNaN($scope.modal.GrantContributionsProgramService) ? null : $scope.modal.GrantContributionsProgramService;
        $scope.modal.Compensation = isNaN($scope.modal.Compensation) ? null : $scope.modal.Compensation;
        $scope.modal.TotalExpenses = isNaN($scope.modal.TotalExpenses) ? null : $scope.modal.TotalExpenses;
        $scope.modal.EndingGrossAssets = isNaN($scope.modal.EndingGrossAssets) ? null : $scope.modal.EndingGrossAssets;
    };


    $scope.CheckEndDate = function () {


        if ($scope.modal.AccountingyearEndingDate != null && $scope.modal.AccountingyearBeginningDate != null) {
            if (new Date($scope.modal.AccountingyearEndingDate) < new Date($scope.modal.AccountingyearBeginningDate)) {
                $scope.ValidateFinancialEndDateMessage = true;
            }
            else
                $scope.ValidateFinancialEndDateMessage = false;
        }
    };


    $scope.Review = function () {
        //var endDate = $scope.modal.AccountingyearEndingDate;
        //if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
        //    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
        //    if (isEndDateMore) {
        //        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
        //        return false;
        //    }
        //}

        $scope.validateErrorMessage = true;
        //var isTrustFinancialInfo = $scope.modal.IsDateEditable ? true : (($scope.trustClosureForm.trusteeFinancialInfo.$valid));
        var isEffectiveDateExists = ($scope.trustClosureForm.EffectiveDate.$valid);

        //var isFinancialsChanged = $scope.modal.IsDateEditable ? true : ($scope.modal.IsFIFullAccountingYear ? (($scope.modal.EndingGrossAssets != null || $scope.modal.TotalRevenue != null || $scope.modal.GrantContributionsProgramService != null || $scope.modal.TotalExpenses != null ||
        //                                $scope.modal.Compensation != null) ? false : true) : true);

        var isFinancialsChanged = $scope.modal.IsDateEditable ? true : ($scope.modal.IsFIFullAccountingYear ? (($scope.modal.EndingGrossAssets != null || $scope.modal.TotalRevenue != null || $scope.modal.GrantContributionsProgramService != null || $scope.modal.TotalExpenses != null ||
        $scope.modal.Compensation != null) ? false : true) : true);


        //Implemented as per the changes mentioned in Ticket-2171 & 2184
        var isIRSDocumentValid = $scope.modal.IsFIFullAccountingYear ? ($scope.modal.FinancialInfoIRSUpload.length > 0 ? true : false) : true;

        //var isTrustFinancialInfoValid = $scope.trustClosureForm.trusteeFinancialInfo.$valid;

        var isIRSDocumentTypeValid = $scope.modal.IsFIFullAccountingYear ? ($scope.modal.IRSDocumentId != 0 ? true : false) : true;

        //var isCorrespondenceAddressValid = $scope.trustClosureForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.trustClosureForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.trustClosureForm.cftCorrespondenceAddressForm.$valid;

        $scope.modal.TrustClosureReason = $scope.addedReasons.join(',');
        $scope.modal.addedReasons = $scope.addedReasons;
        var isSignatureAttestationValidate = ($scope.trustClosureForm.SignatureForm.$valid);
        var isClosureAttestation = $scope.modal.SignatureOnDocument ? true : false;
        $rootScope.modal = $scope.modal;
        var isFormValidate = isEffectiveDateExists && $scope.addedReasons.length > 0 && isClosureAttestation
                                && isIRSDocumentValid && isIRSDocumentTypeValid && isSignatureAttestationValidate && isCorrespondenceAddressValid;

        //var isFormValidate = isEffectiveDateExists && $scope.addedReasons.length > 0 && isIRSDocumentTypeValid && isIRSDocumentValid && isClosureAttestation && isSignatureAttestationValidate;
        $scope.fillRegData();
        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            $rootScope.modal = $scope.modal;
            $location.path('/trustClosureReview');
        } else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };



    $scope.fillRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.TrustID = $scope.modal.TrustID || null;
        //Organization Information
        $scope.modal.EntityName = $scope.modal.EntityName != null && $scope.modal.EntityName != '' ? $scope.modal.EntityName : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        $scope.modal.TrustClosureReason = $scope.addedReasons.join(',');
        //Financial Information
        $scope.modal.IsFIFullAccountingYear = $scope.modal.IsFIFullAccountingYear;

        $scope.modal.AccountingyearBeginningDate = $scope.modal.AccountingyearBeginningDate;
        $scope.modal.AccountingyearEndingDate = $scope.modal.AccountingyearEndingDate;
        $scope.modal.FirstAccountingyearEndDate = $scope.modal.FirstAccountingyearEndDate;

        $scope.modal.IsTrustBeginingGrossAssetsEmpty = ($scope.modal.BeginingGrossAssets == null) ? true : false;
        $scope.modal.IsGrantContributionsProgramServiceEmpty = ($scope.modal.GrantContributionsProgramService == null) ? true : false;
        $scope.modal.IsTotalRevenueEmpty = ($scope.modal.TotalRevenue == null) ? true : false;
        $scope.modal.IsTrustEndingGrossAssetsEmpty = ($scope.modal.EndingGrossAssets == null) ? true : false;
        $scope.modal.IsCompensationEmtpy = ($scope.modal.Compensation == null) ? true : false;
        $scope.modal.IsTotalExpensesEmpty = ($scope.modal.TotalExpenses == null) ? true : false;

        //$scope.modal.BeginingGrossAssets = ($scope.modal.BeginingGrossAssets == null) ? null : $scope.modal.BeginingGrossAssets;
        //$scope.modal.TotalRevenue = ($scope.modal.TotalRevenue == null) ? null : $scope.modal.TotalRevenue;
        //$scope.modal.GrantContributionsProgramService = ($scope.modal.GrantContributionsProgramService == null) ? null : $scope.modal.GrantContributionsProgramService;
        //$scope.modal.Compensation = ($scope.modal.Compensation == null) ? null : $scope.modal.Compensation;
        //$scope.modal.EndingGrossAssets = ($scope.modal.EndingGrossAssets == null) ? null : $scope.modal.EndingGrossAssets;
        //$scope.modal.TotalExpenses = ($scope.modal.TotalExpenses == null) ? null : $scope.modal.TotalExpenses;
        $scope.modal.IRSDocumentId = $scope.modal.IRSDocumentId

        if ($scope.modal.IRSDocumentId == 0) {
            $scope.modal.IRSDocumentTye = null;
        }
        else {
            angular.forEach($scope.IRSDocumentTypes, function (val) {
                if ($scope.modal.IRSDocumentId == val.Key) {
                    $scope.modal.IRSDocumentTye = val.Value;
                }
            });
        }

        $scope.modal.FinancialInfoIRSUploadTypeText = $scope.modal.IRSDocumentTye;


        $scope.modal.FinancialInfoIRSUpload = angular.isNullorEmpty($scope.modal.FinancialInfoIRSUpload) ? [] : $scope.modal.FinancialInfoIRSUpload;

        $scope.modal.Comments = $scope.modal.Comments;

        $scope.modal.ClosureUploadDocument = angular.isNullorEmpty($scope.modal.ClosureUploadDocument) ? [] : $scope.modal.ClosureUploadDocument;

        $scope.modal.CFTUploadDocumentsList = angular.isNullorEmpty($scope.modal.CFTUploadDocumentsList) ? [] : $scope.modal.CFTUploadDocumentsList;

        ////Filing Correspondence
        //$scope.modal.CFTAttention = $scope.modal.CFTAttention;


        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;

        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        ////Attestation
        //$scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        //$scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;
        //Attestation
        //$scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;
        $rootScope.modal = $scope.modal;
    };

    $scope.IRSChange = function (irsId, docsList, oldIRS) {
        //if (irsId == 0) {
        if ($scope.modal.FinancialInfoIRSUpload != undefined && $scope.modal.FinancialInfoIRSUpload.length > 0) {
            wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                angular.forEach($scope.modal.FinancialInfoIRSUpload, function (value, data) {
                    if (value.BusinessFilingDocumentId > 0) {
                        value.Status = principalStatus.DELETE;
                    }
                    else {
                        var index = $scope.modal.FinancialInfoIRSUpload.indexOf(value);
                        $scope.modal.FinancialInfoIRSUpload.splice(index, 1);
                    }

                });
                angular.forEach($scope.IRSDocumentTypes, function (doc) {
                    if (doc.Key == $scope.modal.IRSDocumentId)
                        $scope.modal.FinancialInfoIRSUploadTypeText = doc.Value;
                });
            }, function () {
                $scope.modal.IRSDocumentId = oldIRS;
                angular.forEach($scope.IRSDocumentTypes, function (doc) {
                    if (doc.Key == $scope.modal.IRSDocumentId)
                        $scope.modal.FinancialInfoIRSUploadTypeText = doc.Value;
                });
            });
        }
        else {
            $scope.modal.FinancialInfoIRSUpload = [];
        }
        //}
    };


    // Toggle selection for a given reason
    $scope.toggleSelection = function toggleSelection(reason) {
        var idx = $scope.addedReasons.indexOf(reason);
        if (idx > -1) {
            $scope.addedReasons.splice(idx, 1);
        }
        else {
            $scope.addedReasons.push(reason);
        }
    };


    var resultDate = "";
    $scope.CalculateEndDate = function () {
        if ($scope.modal.AccountingyearBeginningDate != null && $scope.modal.AccountingyearBeginningDate != "") {
            var value = $scope.modal.AccountingyearBeginningDate;
            var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
            var result = value.match(rxDatePattern);
            if (result != null) {
                var dateValue = new Date(value);
                dateValue.setYear(dateValue.getFullYear() + 1);
                var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                resultDate = lastDayWithSlashes;
                $scope.modal.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                $("#idEndDate").datepicker("setDate", lastDayWithSlashes);
            }
            else {
                $scope.modal.AccountingyearEndingDate = null;
            }
        }
        $scope.validateFinancialDates(); // validateFinancialDates method is available in this controller only.
    };

    //check Accounting year endat date is greater than current date
    $scope.validateFinancialDates = function () {
        var currentDate = new Date();
        if ($scope.modal.IsFIFullAccountingYear) {
            var newDate = new Date($scope.modal.AccountingyearEndingDate);
            if (newDate > currentDate) {
                $scope.modal.IsDateEditable = true;
                $scope.modal.BeginingGrossAssets = null;
                $scope.modal.AccountingyearBeginningDate = null;
                $scope.modal.AccountingyearEndingDate = null;
            }
        }
        else {
            var newDate = new Date($scope.modal.FirstAccountingyearEndDate);
            if (newDate > currentDate) {
                $scope.modal.IsDateEditable = true;
                $scope.modal.FirstAccountingyearEndDate = null;
            }
        }
    };

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.modal.TrustClosureReason = $scope.addedReasons.join(',');
        $scope.modal.addedReasons = $scope.addedReasons;
        $rootScope.modal = $scope.modal;
        $scope.fillRegData();
        $scope.modal.OnlineNavigationUrl = "/trusteeClosure/" + $scope.modal.TrustID;
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // TrustSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.TrustSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

});
wacorpApp.controller('trustClosureReview', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    $scope.Init = function () {
        $scope.modal = $rootScope.modal;
    }


    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/trusteeClosure/' + $scope.modal.TrustID);
    }

    $scope.AddToCart = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.IsOnline = true;

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // TrusteeAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.TrusteeAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
            $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });

    };
});
wacorpApp.directive('trustCftOfficers', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustOfficersDirectors/_TrustCFTOfficers.html',
        restrict: 'A',
        scope: {
            cftOfficersList: '=?cftOfficersList',
            showErrorMessage: '=?showErrorMessage',
            mainModel: '=?mainModel',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope, $location, $timeout) {
            $scope.messages = messages;
            $scope.cftOfficersList = $scope.cftOfficersList || [];
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add New Officer";
            $scope.ValidateErrorMessage = false;
            $scope.IsIamOfficer = false;
            $scope.cftOfficer = {
                OfficerID: "", FirstName: null, LastName: null, Title: null, FullName: null, SequenceNo: "", PhoneNumber: "", EmailAddress: "", TypeID: "", OfficerBaseType: "", IsCFTOfficer: false, Status: null,
                OfficerAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, Status: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO, OfficerStatus: principalStatus.INSERT,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null, IsSameAsAddressContactInfo: false
            };

            var cftOfficersScopeData = {
                OfficerID: "", FirstName: null, LastName: null, Title: null, FullName: null, SequenceNo: "", PhoneNumber: "", EmailAddress: "", TypeID: "", OfficerBaseType: "", IsCFTOfficer: false, Status: null,
                OfficerAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, Status: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO, OfficerStatus: principalStatus.INSERT,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null, IsSameAsAddressContactInfo: false
            };

            $scope.resetCFTOfficer = function () {
                $scope.cftOfficer = angular.copy(cftOfficersScopeData);
                $scope.ValidateErrorMessage = false;
                $scope.addbuttonName = "Add New Officer";
                //$scope.IsIamOfficer = false;
                $("#loginOfficer").prop("checked", false);
            };


            $scope.AddCFTOfficer = function (cftOfficersForm) {
                $scope.ValidateErrorMessage = true;

                $scope.cftOfficer.OfficerAddress.StreetAddress1 = (($scope.cftOfficer.OfficerAddress.StreetAddress1 != null && $scope.cftOfficer.OfficerAddress.StreetAddress1.trim() == "" || $scope.cftOfficer.OfficerAddress.StreetAddress1 == undefined) ? $scope.cftOfficer.OfficerAddress.StreetAddress1 = null : $scope.cftOfficer.OfficerAddress.StreetAddress1.trim());
                if (!$scope.cftOfficer.OfficerAddress.StreetAddress1) {
                    $scope.trusteeCftOfficersForm.CFTAddress.StreetAddress1.$setValidity("text", false);
                }
                else {
                    $scope.trusteeCftOfficersForm.CFTAddress.StreetAddress1.$setValidity("text", true);
                }

                if ($scope[cftOfficersForm].$valid) {
                    $scope.ValidateErrorMessage = false;
                    $scope.addbuttonName = "Add New Officer";
                    if ($scope.cftOfficer.SequenceNo != 0) {
                        angular.forEach($scope.cftOfficersList, function (officer) {
                            if (officer.SequenceNo == $scope.cftOfficer.SequenceNo) {
                                //officer.OfficerStatus = principalStatus.UPDATE;
                                angular.copy($scope.cftOfficer, officer);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.cftOfficersList, function (officer) {
                            if (maxId == constant.ZERO || officer.SequenceNo > maxId)
                                maxId = officer.SequenceNo;
                        });
                        $scope.cftOfficer.SequenceNo = ++maxId;
                        $scope.cftOfficer.OfficerStatus = principalStatus.INSERT;
                        $scope.cftOfficer.IsCFTOfficer = true;
                        $scope.cftOfficersList.push($scope.cftOfficer);
                    }
                    $scope.resetCFTOfficer(); // resetCFTOfficer method is available in this file only
                }
            };


            $scope.editCFTOfficer = function (cftOfficersData) {
                cftOfficersData.OfficerAddress.Country = cftOfficersData.OfficerAddress.Country || codes.USA;
                cftOfficersData.OfficerAddress.State = cftOfficersData.OfficerAddress.State || codes.USA;
                cftOfficersData.IsSameAsAddressContactInfo = false;
                $scope.cftOfficer = angular.copy(cftOfficersData);
                $scope.cftOfficer.OfficerStatus = principalStatus.UPDATE;
                $scope.addbuttonName = "Update Officer";
            };


            $scope.deleteCFTOfficer = function (cftOfficersData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (cftOfficersData.OfficerID <= 0 || cftOfficersData.OfficerID == "") {
                        var index = $scope.cftOfficersList.indexOf(cftOfficersData);
                        $scope.cftOfficersList.splice(index, 1);
                    }
                    else
                        cftOfficersData.OfficerStatus = principalStatus.DELETE;
                    $scope.resetCFTOfficer(); // resetCFTOfficer method is available in this file only
                });
            };

            // Clear all controls data
            $scope.clearCFTOfficer = function () {
                $scope.resetCFTOfficer(); // resetCFTOfficer method is available in this file only
            };

            //Get User Login details during MySelf Select
            $scope.getUserLoginDetails = function (IsIamOfficerVal) {
                if (IsIamOfficerVal) {
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        $scope.cftOfficer.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.cftOfficer.LastName = angular.copy($scope.newUser.LastName);
                        $scope.cftOfficer.Title = angular.copy($scope.newUser.Title);
                        $scope.cftOfficer.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.cftOfficer.ConfirmEmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.cftOfficer.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        var addressId = $scope.cftOfficer.OfficerAddress.ID;
                        $scope.cftOfficer.OfficerAddress = angular.copy($scope.newUser.Address);
                        $scope.cftOfficer.OfficerAddress.ID = addressId;
                        $scope.cftOfficer.IsCFTOfficer = false;
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    var seqNo = $scope.cftOfficer.SequenceNo;
                    var officerId = $scope.cftOfficer.OfficerID;
                    var addressId = $scope.cftOfficer.OfficerAddress.ID;
                    var status = $scope.cftOfficer.OfficerStatus;
                    $scope.cftOfficer = angular.copy(cftOfficersScopeData);
                    $scope.cftOfficer.OfficerAddress.ID = addressId;
                    $scope.cftOfficer.SequenceNo = seqNo;
                    $scope.cftOfficer.OfficerID = officerId;
                    $scope.cftOfficer.OfficerStatus = status;
                }
            };

            $scope.amendmentLink = function () {
                window.open('#/BusinessAmendmentIndex', '_blank');
                //$location.path('/BusinessAmendmentIndex');
            };

            $scope.copyFromContactInformation = function () {
                if ($scope.cftOfficer.IsSameAsAddressContactInfo) {
                    var addressId = $scope.cftOfficer.OfficerAddress.ID;
                    $scope.cftOfficer.OfficerAddress = angular.copy($scope.mainModel.EntityMailingAddress);
                    $scope.cftOfficer.OfficerAddress.ID = addressId;
                    $scope.cftOfficer.PhoneNumber = $scope.mainModel.EntityPhoneNumber;
                }
                else {
                    var addressId = $scope.cftOfficer.OfficerAddress.ID;
                    $scope.cftOfficer.OfficerAddress = angular.copy(cftOfficersScopeData.OfficerAddress);
                    $scope.cftOfficer.OfficerAddress.ID = addressId;
                    $scope.cftOfficer.PhoneNumber = "";
                }
            }

            $scope.changedAddress = function () {
                if ($scope.cftOfficer.IsSameAsAddressContactInfo) {
                    $scope.cftOfficer.IsSameAsAddressContactInfo = false;
                }
            };

            var changedMailingAddress = $scope.$on("onMailingAddressChanged", function () {
                $scope.changedAddress();
            });

            $scope.$on('$destroy', function () {
                changedMailingAddress();
            });

        },
    };
});

wacorpApp.directive('trustFinancialPreparer', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustFinancialPreparer/_TrustFinancialPreparer.html',
        restrict: 'A',
        scope: {
            trustLegalInfoData: '=?trustLegalInfoData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.LegalInfoAttachDocuments = $scope.LegalInfoAttachDocuments || [];
            $scope.addbuttonName = "Add Legal Information";

            var trustLegalInfoScope = {
                LegalInfoEntityName: '', FirstName: '', Title: '', LastName: '', EntityRepresentativeFirstName: '', EntityRepresentativeLastName: '', SequenceNo: "", LegalInfoTypeID: "E", IsAnyLegalActions: false, isUploadDocument: false,
                Court: '', Case: '', TitleofLegalAction: '', LegalActionDate: null,
                LegalInfoAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                LegalInfoAttachDocuments: [], isUploadDocument: false
            };

            $scope.trustLegalInfoData = $scope.trustLegalInfoData ? angular.extend(trustLegalInfoScope, $scope.trustLegalInfoData) : angular.copy(trustLegalInfoScope);

            $scope.$watch('trustLegalInfoData', function () {
                //$scope.trustLegalInfoData.isUploadDocument = angular.isNullorEmpty($scope.trustLegalInfoData.isUploadDocument) ? true : $scope.trustLegalInfoData.isUploadDocument;
                if ($scope.trustLegalInfoData != null && $scope.trustLegalInfoData != undefined) {
                    $scope.trustLegalInfoData.isUploadDocument = $scope.trustLegalInfoData.LegalInfoAttachDocuments.length > 0 ? true : false;
                    $scope.trustLegalInfoData.LegalInfoTypeID = $scope.trustLegalInfoData.LegalInfoTypeID || 'I';

                }
            });

            //Get User Login details during MySelf Select
            $scope.getUserLoginDetails = function (mySelfLegal) {
                var currentTypeID = angular.copy($scope.trustLegalInfoData.LegalInfoTypeID);
                if (mySelfLegal) {
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        $scope.trustLegalInfoData.LegalInfoTypeID = angular.copy($scope.newUser.Agent.AgentType);
                        $scope.trustLegalInfoData.LegalInfoEntityName = angular.copy($scope.newUser.EntityName);
                        $scope.trustLegalInfoData.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.trustLegalInfoData.LastName = angular.copy($scope.newUser.LastName);
                        $scope.trustLegalInfoData.EntityRepresentativeFirstName = angular.copy($scope.newUser.EntityRepresentativeFirstName);
                        $scope.trustLegalInfoData.EntityRepresentativeLastName = angular.copy($scope.newUser.EntityRepresentativeLastName);
                        $scope.trustLegalInfoData.Title = angular.copy($scope.newUser.Title);
                        $scope.trustLegalInfoData.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.trustLegalInfoData.ConfirmEmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.trustLegalInfoData.LegalInfoPhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        $scope.trustLegalInfoData.LegalInfoAddress = angular.copy($scope.newUser.Address);
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    $scope.trustLegalInfoData = angular.copy(trustLegalInfoScope);
                    $scope.trustLegalInfoData.LegalInfoTypeID = currentTypeID;
                }
            };


            $scope.legalInfoSelection = function (value) {
                if (value == "I") {
                    $scope.trustLegalInfoData.FirstName = '';
                    $scope.trustLegalInfoData.LastName = '';
                    $scope.trustLegalInfoData.Title = '';
                }
                else {
                    $scope.trustLegalInfoData.EntityRepresentativeFirstName = '';
                    $scope.trustLegalInfoData.EntityRepresentativeLastName = '';
                    $scope.trustLegalInfoData.Title = '';

                }
                $scope.trustLegalInfoData.LegalInfoEntityName = '';
            };

            $scope.AddLegalAction = function myfunction(fundraiserLegalInfo) {

                //if ($scope.trustLegalInfoScope.SequenceNo!=0) {
                angular.forEach(trustLegalInfoData.LegalInfoList, function (leagl) {

                    if (leagl.SequenceNo == $scope.trustLegalInfoScope.SequenceNo) {
                        //$scope.cftOfficer.OfficerAddress.FullAddress = wacorpService.cftFullAddressService($scope.cftOfficer.OfficerAddress);
                        angular.copy($scope.trustLegalInfoScope, leagl);
                    }
                });
                //}
            };

            //Delete attachments
            $scope.deleteAllFiles = function (files) {
                if (files.length > constant.ZERO) {
                    files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        // deleteAllUploadedFiles method is available in constants.js
                        wacorpService.post(webservices.Common.deleteAllUploadedFiles, files,
                            function (response) {
                                $scope.trustLegalInfoData.LegalInfoAttachDocuments = [];
                            },
                            function (response) {
                            }
                        );
                    },
                    function () {
                        $scope.trustLegalInfoData.isUploadDocument = false;
                    });
                }
            };
        },
    };
});

wacorpApp.directive('trustLegalActions', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustLegalInfo/_TrustLegalActions.html',
        restrict: 'A',
        scope: {
            legalInfoEntity: '=?legalInfoEntity',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope, $location) {
            $scope.messages = messages;
         //   $scope.legalInfoEntityList = $scope.legalInfoEntityList || [];
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add Legal Information";
            $scope.hasValues = false;
            $scope.LegalCount = false;
            $scope.LegalUploadCount = false;
            $scope.legalInfo = {
                IsAnyLegalActions: false, isUploadDocument: false,SequenceNo:null,
                Court: '', Case: '', TitleofLegalAction: '', LegalActionDate: null, LegalActionsUploads: [], LegalInfoEntityList: []
            };
           
            $scope.hasValues = $scope.legalInfo.Court != '' || $scope.legalInfo.Case != '' ||
                               $scope.legalInfo.TitleofLegalAction != '' || $scope.legalInfo.legalActionData != null;

            var legalInfoScopeData = {
                IsAnyLegalActions: false, isUploadDocument: false,
                Court: '', Case: '', TitleofLegalAction: '', LegalActionDate: null, LegalActionsUploads: [], LegalInfoEntityList: []
            };

            $scope.legalInfoEntity = $scope.legalInfoEntity ? angular.extend(legalInfoScopeData, $scope.legalInfoEntity) : angular.copy(legalInfoScopeData);


            $scope.$watch('legalInfo', function () {
                if (typeof ($scope.legalInfo.LegalActionsUploads) != typeof (undefined) && $scope.legalInfo.LegalActionsUploads != null) {
                    $scope.legalInfo.isUploadDocument = $scope.legalInfo.LegalActionsUploads.length > 0 ? true : false;
                }
            });

            //Reset the legal action
            $scope.resetLegalAction = function () {
                $scope.legalInfo = angular.copy(legalInfoScopeData);
               // $scope.ValidateErrorMessage = false;
                $scope.addbuttonName = "Add Legal Information";
            };

            //Add Legal Action data
            $scope.AddLeglAction = function (legalActionsForm) {
                $scope.ValidateErrorMessage = true;
                if ($scope[legalActionsForm].$valid) {
                    $scope.ValidateErrorMessage = false;
                    if ($scope.legalInfo.SequenceNo!=null && $scope.legalInfo.SequenceNo!=''&& $scope.legalInfo.SequenceNo != 0) {
                        angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (legalInfoItem) {
                            if (legalInfoItem.SequenceNo == $scope.legalInfo.SequenceNo) {
                                angular.copy($scope.legalInfo, legalInfoItem);
                                ////////////////Cross check.
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (legalInfoItem) {
                            if (maxId == constant.ZERO || legalInfoItem.SequenceNo > maxId)
                                maxId = legalInfoItem.SequenceNo;
                        });
                        $scope.legalInfo.SequenceNo = ++maxId;
                        $scope.legalInfo.Status = principalStatus.INSERT;
                        $scope.legalInfoEntity.LegalInfoEntityList.push($scope.legalInfo);
                    }
                    $scope.resetLegalAction(); // resetLegalAction method is available in this file only
                }
                 
            };

            //Edit fundraiser charitable organization data
            $scope.editLegalAction = function (legalActionData) {
                $scope.legalInfo = angular.copy(legalActionData);
                $scope.legalInfo.LegalActionDate = $scope.legalInfo.LegalActionDate == "0001-01-01T00:00:00" ? null : wacorpService.dateFormatService($scope.legalInfo.LegalActionDate);
                $scope.legalInfo.Status = principalStatus.UPDATE;
                $scope.addbuttonName = "Update Legal Information";
            };

            //Delete fundraiser charitable organization data
            $scope.deleteLegalAction = function (legalActionData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (legalActionData.LegalInfoId <= 0 || legalActionData.LegalInfoId == "")
                    {
                        var index = $scope.legalInfoEntity.LegalInfoEntityList.indexOf(legalActionData);
                        $scope.legalInfoEntity.LegalInfoEntityList.splice(index, 1);
                    }
                    else
                        legalActionData.Status = principalStatus.DELETE;
                    $scope.resetLegalAction(); // resetLegalAction method is available in this file only
                });
            };
            
            $scope.deleteAllFiles = function (flag, uploadfiles, legalInfo) {
                $scope.resetLegalAction(); // resetLegalAction method is available in this file only
                if (!flag && (uploadfiles.length > constant.ZERO || legalInfo.length > constant.ZERO)) {
                    var confirmMsg = '';
                    if (uploadfiles.length == constant.ZERO) {
                        confirmMsg = "All the records will be deleted. Do you want to continue?";
                    }
                    else {
                        confirmMsg = $scope.messages.UploadFiles.filesDeleteConfirm;
                    }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog(confirmMsg, function () {
                        //Removing Uploaded List
                        if ($scope.legalInfoEntity.LegalActionsUploads.length > 0)
                        {
                            //for(var i=0;i<$scope.legalInfoEntity.LegalActionsUploads.length;i=0){
                            angular.forEach($scope.legalInfoEntity.LegalActionsUploads, function (value, data) {
                                if (value.BusinessFilingDocumentId > 0)
                                {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.legalInfoEntity.LegalActionsUploads.indexOf(value);
                                    $scope.legalInfoEntity.LegalActionsUploads.splice(index, 1);
                                }
                            });
                        }
                        //Removing Legal Info List
                        if ($scope.legalInfoEntity.LegalInfoEntityList.length > 0) {
                            angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (value, data) {
                                if (value.LegalInfoId > 0) {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.legalInfoEntity.LegalInfoEntityList.indexOf(value);
                                    $scope.legalInfoEntity.LegalInfoEntityList.splice(index, 1);
                                }

                            });
                        }
                    },
                    function () {
                        $scope.legalInfoEntity.LegalInfo.IsAnyLegalActions = true;
                    });
                }
            };

            $scope.amendmentLink = function () {
                $location.path('/BusinessAmendmentIndex');
            };

        },
    };
});

wacorpApp.directive('trustFein', function ($filter) {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustFEIN/_TrustFEIN.html',
        restrict: 'A',
        scope: {
            feinData: '=?feinData',
            isNotRenewal:'=?isNotRenewal',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.usaCode = usaCode;
            $scope.washingtonCode = washingtonCode;
            $scope.isOptional = true;
            $scope.isCorporation = true;
            $scope.isOther = true;
            $scope.FederalTaxTypes = [];
            $scope.Countries = [];
            $scope.States = [];
            $scope.ShowIRSLetter = false;
            $scope.OrganizationNames = [];
            $scope.FederalCount = false;
            //$scope.feinData.IsShowFederalTax = false;
            $scope.washingtonIntegerCode = washingtonIntegerCode;
            //$scope.charityOrganization = {};
            //$scope.charityOrganization.AKANamesList = $scope.charityOrganization.AKANamesList || [];
            //$scope.feinData.IsFederalTax = false;
            //$scope.feinData.LastWillAndTestament = false;
            //$scope.feinData.ArticlesOfIncorporationAndBylaws = false;
            //$scope.feinData.TrustAgreement = false;
            //$scope.feinData.ProbateOrder = false;
            var feinScope = {
                FEINNumber: constant.ZERO, UBINumber: constant.ZERO, IsEntityRegisteredInWA: false, IsUBIOrganizationaStructure: true, isShowAka: false,
                JurisdictionCountry: codes.USA, JurisdictionState: codes.WA, UBIOtherDescp: '', JurisdictionCountryDesc: null, JurisdictionStateDesc: null, IsFederalTax: false,
                FederalTaxExemptId: '', FederaltaxUpload: [], ArticlesOfIncorporationAndBylaws: false, TrustAgreement: false, LastWillAndTestament: false, ProbateOrder: false,
                JurisdictionDesc: null, Jurisdiction: null, IsFEINNumberExistsorNot: false, IsUBINumberExistsorNot: false, IsShowFederalTax: false, IsOrgNameExists: false, IsActiveFilingExist: false
            };

            $scope.feinData = $scope.feinData ? angular.extend(feinScope, $scope.feinData) : angular.copy(feinScope);

            $scope.selectedJurisdiction = function (items, selectedVal) {
                var result = "";
                angular.forEach(items, function (item) {
                    if (selectedVal == item.Key) {
                        result = item.Value;
                    }
                });
                return result;
            }

            var ubiCnt = 1;
            $scope.$watch('feinData', function () {
                $scope.feinData.FEINNumber = $scope.feinData.FEINNumber == 0 ? '' : $scope.feinData.FEINNumber;
                $scope.feinData.UBINumber = $scope.feinData.UBINumber == 0 ? '' : $scope.feinData.UBINumber;
                $scope.feinData.IsEntityRegisteredInWA = angular.isNullorEmpty($scope.feinData.IsEntityRegisteredInWA) ? false : $scope.feinData.IsEntityRegisteredInWA;
                $scope.feinData.IsUBIOrganizationaStructure = angular.isNullorEmpty($scope.feinData.IsUBIOrganizationaStructure) ? true : $scope.feinData.IsUBIOrganizationaStructure;
                $scope.feinData.JurisdictionCountry = $scope.feinData.JurisdictionCountry == 0 ? '' : $scope.feinData.JurisdictionCountry;
                $scope.feinData.JurisdictionState = $scope.feinData.JurisdictionState == 0 ? $scope.washingtonCode : $scope.feinData.JurisdictionState;
                $scope.feinData.IsActiveFilingExist = angular.isNullorEmpty($scope.feinData.IsActiveFilingExist) ? false : $scope.feinData.IsActiveFilingExist;
                $scope.feinData.isShowAka = angular.isNullorEmpty($scope.feinData.isShowAka) ? false : $scope.feinData.isShowAka;

                $scope.feinData.ArticlesOfIncorporationAndBylaws = angular.isNullorEmpty($scope.feinData.ArticlesOfIncorporationAndBylaws) ? false : $scope.feinData.ArticlesOfIncorporationAndBylaws;
                $scope.feinData.TrustAgreement = angular.isNullorEmpty($scope.feinData.TrustAgreement) ? false : $scope.feinData.TrustAgreement;
                $scope.feinData.LastWillAndTestament = angular.isNullorEmpty($scope.feinData.LastWillAndTestament) ? false : $scope.feinData.LastWillAndTestament;
                $scope.feinData.ProbateOrder = angular.isNullorEmpty($scope.feinData.ProbateOrder) ? false : $scope.feinData.ProbateOrder;
                $scope.feinData.IsFederalTax = angular.isNullorEmpty($scope.feinData.IsFederalTax) ? false : $scope.feinData.IsFederalTax;
                $scope.feinData.IsShowFederalTax = angular.isNullorEmpty($scope.feinData.IsShowFederalTax) ? false : $scope.feinData.IsShowFederalTax;
                //if ($scope.feinData.JurisdictionCountry != $scope.usaCode) {
                //    $scope.feinData.JurisdictionState = '';
                //}

                if (ubiCnt == 1 && typeof ($scope.feinData.UBINumber) != typeof (undefined) && $scope.feinData.UBINumber != null && $scope.feinData.UBINumber != '') {
                    $scope.getOrganizationNameByUBI($scope.feinData.UBINumber); // getOrganizationNameByUBI method is available in this file only
                    ubiCnt++;
                }

                var cnt = 1;
                if (typeof ($scope.feinData.AKANamesList) != typeof (undefined) && $scope.feinData.AKANamesList != null) {
                    if ($scope.feinData.AKANamesList.length > 0) {
                        angular.forEach($scope.feinData.AKANamesList, function (akaInfo) {
                            if (akaInfo.Status != "D") {
                                cnt = 0;
                            }
                        });
                        if (cnt == 0) {
                            $scope.feinData.isShowAka = true;
                        }
                        else {
                            $scope.feinData.isShowAka = false;
                        }
                    }
                }

                angular.forEach($scope.FederalTaxTypes, function (tax) {
                    if (tax.Key == $scope.feinData.FederalTaxExemptId)
                        $scope.feinData.FederalTaxExemptText = tax.Value;
                    $scope.feinData.IsFTDocumentAttached = true;
                });

                angular.forEach($scope.Countries, function (country) {
                    if (country.Key == $scope.feinData.JurisdictionCountry)
                        $scope.feinData.JurisdictionCountryDesc = country.Value;
                });
                angular.forEach($scope.States, function (state) {
                    if (state.Key == $scope.feinData.JurisdictionState)
                        $scope.feinData.JurisdictionStateDesc = state.Value;
                });

                if ($scope.feinData.FederaltaxUpload != null && $scope.feinData.FederaltaxUpload != undefined) {
                    if ($scope.feinData.FederaltaxUpload.length > 0) {
                        $scope.feinData.IsShowFederalTax = true;
                    }
                }

                //angular.forEach($scope.feinData.FederaltaxUpload, function (value) {
                //    if (value.Status!="D") {
                //        $scope.FederalCount = false;
                //    }
                //    else {
                //        $scope.FederalCount = true;
                //    }
                //});
                //$scope.FederalChange();
            }, true);

            $scope.$watch('feinData.Purpose', function () {
                 
                if ($scope.feinData.Purpose) {
                    if ($scope.feinData.Purpose.length > 500) {
                        $scope.feinData.Purpose = $scope.feinData.Purpose.replace(/(\r\n|\n|\r)/gm, "");
                        $scope.feinData.Purpose = $scope.feinData.Purpose.substring(0, 500);
                    }
                }
            });

            //$scope.CountryChangeDesc = function () {
            //    $scope.feinData.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.Countries, $scope.feinData.JurisdictionCountry);
            //};
            //Get Federal Tax Types List
            $scope.getFederalTaxTypes = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.FederalTaxTypes(function (response) { $scope.FederalTaxTypes = response.data; });
            };
            $scope.getFederalTaxTypes(); // getFederalTaxTypes method is available in this file only

            var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
                $scope.Countries = response.data;
            }, function (response) {
            });

            var lookupStatesParams = { params: { name: 'CFTStates' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
                $scope.States = response.data;
            }, function (response) {
            });


            $scope.organizationStructure = function (value) {
                if (value) {
                    $scope.feinData.IsUBIOrganizationaStructure = true;
                }
                else {
                    $scope.feinData.IsUBIOrganizationaStructure = false;
                }

            }
            //Get Business Details by UBI Number
            $scope.getBusinessDetails = function () {
                var ubidata = { params: { ubiNumber: $scope.feinData.UBINumber, cftType: $scope.feinData.CFTType } }
                if (ubidata.ubiNumber != '' && ubidata.ubiNumber != null) {
                    // IsUBINumberExists method is available in constants.js
                    wacorpService.get(webservices.CFT.IsUBINumberExists, ubidata, function (response) {
                        if (response.data == 'true') {
                            // Folder Name: app Folder
                            // Alert Name: isUBIExistorNot method is available in alertMessages.js 
                            wacorpService.alertDialog(messages.Fein.isUBIExistorNot);
                            $scope.feinData.IsUBINumberExistsorNot = false;
                            $scope.feinData.UBINumber = null;
                        }
                        else {
                            $scope.feinData.IsUBINumberExistsorNot = true;
                            var data = {
                                params: { UBINumber: $scope.feinData.UBINumber }
                            }
                            // getBusinessDetailsByUBINumber method is available in constants.js
                            wacorpService.get(webservices.CFT.getBusinessDetailsByUBINumber, data, function (response) {

                                if (response.data.EntityName != null) {
                                    $scope.feinData.EntityName = response.data.EntityName;
                                    $scope.feinData.IsOrganizationalStructureType = response.data.BusinessType;
                                    $scope.feinData.OrganizationStructureJurisdictionCountryId = response.data.OrganizationStructureJurisdictionCountryId == null ? "" : response.data.OrganizationStructureJurisdictionCountryId.toString();
                                    $scope.feinData.OrganizationalStructureStateJurisdictionId = response.data.OrganizationalStructureStateJurisdictionId == null ? "" : response.data.OrganizationalStructureStateJurisdictionId.toString();
                                    $scope.feinData.OSJurisdictionId = response.data.OrganizationalStructureJurisdictionId == 0 ? "" : response.data.OrganizationalStructureJurisdictionId.toString();
                                    $scope.feinData.IsOSNonProfitCorporation = (response.data.BusinessType == "C") ? true : false;
                                    $scope.feinData.CFTOfficersList = response.data.CFTOfficersList;
                                    $scope.feinData.isHavingEntityOnUBISearch = angular.isNullorEmpty($scope.feinData.EntityName) ? false : true;

                                    angular.forEach($scope.Countries, function (country) {
                                        if (country.Key == $scope.feinData.OrganizationStructureJurisdictionCountryId)
                                            $scope.feinData.OrganizationStructureJurisdictionCountryDesc = country.Value;
                                    });

                                    angular.forEach($scope.States, function (state) {
                                        if (state.Key == $scope.feinData.OrganizationalStructureStateJurisdictionId)
                                            $scope.feinData.OrganizationalStructureStateJurisdictionDesc = state.Value;
                                    });
                                } else {
                                    // Folder Name: app Folder
                                    // Alert Name: noDataFound method is available in alertMessages.js 
                                    wacorpService.alertDialog(messages.noDataFound);
                                    $scope.feinData.UBINumber = null;
                                }

                            }, function (response) { });
                        }
                    }, function (response) { });
                }

            };

            $scope.getOrganizationNameByUBI = function (value) {
                $scope.feinData.IsOrgNameExists = false;
                //$scope.feinData.isBusinessNameChanged = false;
                if ($scope.feinData.EntityName != "" && $scope.feinData.EntityName != undefined) {
                    if ($scope.feinData.FeinUbiCount == 0)
                        $scope.feinData.UBIOldName = $scope.feinData.EntityName;
                }

                if (value != "" && value != null && value.length == 9) {
                    var ubidata = { params: { UBINumber: $scope.feinData.UBINumber.replace(" ", "").replace(" ", "") } }
                    // getOrganizationNameByUBI method is available in constants.js
                    wacorpService.get(webservices.CFT.getOrganizationNameByUBI, ubidata, function (response) {
                        if (response.data.replace(/(^"|"$)/g, '') != "") {
                            $scope.feinData.EntityName = response.data.replace(/(^"|"$)/g, '').replace(/\\/g, '');
                            $scope.feinData.IsOrgNameExists = true;
                            $scope.feinData.IsUbiAssociated = false;
                            $scope.feinData.businessNames = 0;
                            if ($scope.feinData.UBIOldName != null && $scope.feinData.UBIOldName != undefined)
                                $scope.feinData.FeinUbiCount++;
                        }
                        else {
                            //$scope.feinData.EntityName = "";
                            $scope.feinData.EntityName = $scope.feinData.UBIOldName;
                            $scope.feinData.IsOrgNameExists = false;
                            $scope.feinData.IsUbiAssociated = true;
                        }
                    });

                }

            };

            $scope.getOrganizationNameByFEIN = function (value, type) {
                $scope.feinData.IsOrgNameExists = false;
                //$scope.feinData.isBusinessNameChanged = false;
                if (value != "" && value != null && value.replace("-", "").length == 9) {
                    var feindata = { params: { FEINNumber: value.replace("-", ""), cftType: type } }
                    // getOrganizationNameByFEIN method is available in constants.js
                    wacorpService.get(webservices.CFT.getOrganizationNameByFEIN, feindata, function (response) {
                        //new logic 10/03/2017 TFS:15366
                        $scope.OrganizationNames = [];
                        $scope.OrganizationNames = response.data;
                        if ($scope.OrganizationNames.length > 0)
                            $("#divOrganizationNamesList").modal('toggle');
                        if ($scope.feinData.FeinOldvalue == null || $scope.feinData.FeinOldvalue == "")
                            $scope.feinData.FeinOldvalue = $scope.feinData.FEINNumber;

                        if ($scope.feinData.FeinOldvalue != $scope.feinData.FEINNumber) {

                            //if (!$scope.feinData.IsNewRegistration) {
                            //    if ($scope.feinData.FederaltaxUpload.length > 0) {
                            //        angular.forEach($scope.feinData.FederaltaxUpload, function (value, data) {
                            //            if (value.BusinessFilingDocumentId > 0) {
                            //                wacorpService.confirmDialog($scope.messages.UploadFiles.irsConfirm, function () {
                            //                    value.Status = principalStatus.DELETE;
                            //                });
                            //            }
                            //            else {
                            //                var index = $scope.feinData.FederaltaxUpload.indexOf(value);
                            //                $scope.feinData.FederaltaxUpload.splice(index, constant.ONE);
                            //            }
                            //        });
                            //    }
                            //}
                            $scope.validateFeinRule(); // validateFeinRule method is available in this file only
                        }
                        else if ($scope.feinData.FeinOldvalue == $scope.feinData.FEINNumber) {
                            if (!$scope.feinData.IsNewRegistration) {
                                if (!$scope.feinData.IsNewRegistration) {
                                    if ($scope.feinData.FederaltaxUpload.length > 0) {
                                        angular.forEach($scope.feinData.FederaltaxUpload, function (value, data) {
                                                var index = $scope.feinData.FederaltaxUpload.indexOf(value);
                                                $scope.feinData.FederaltaxUpload.splice(index, constant.ONE);
                                        });
                                    }
                                }
                                //$scope.validateFeinRule();
                            }
                            $scope.feinData.IsFederalTax = $scope.feinData.OldIsFederalTax;
                            $scope.feinData.IsShowFederalTax = $scope.feinData.OldIsShowFederalTax;
                            $scope.feinData.FederalTaxExemptId = $scope.feinData.OldFederalTaxExemptId;
                            //$scope.validateFeinRule();
                        }


                        if (response.data == "")
                            $scope.feinData.IsOrgNameExists = false;
                        //if (response.data != "") {
                        //    $scope.OrganizationNames = response.data;
                        //    $("#divOrganizationNamesList").modal('toggle');
                        //    if ($scope.feinData.FeinOldvalue == null || $scope.feinData.FeinOldvalue == "") {
                        //        $scope.feinData.FeinOldvalue = $scope.feinData.FEINNumber;
                        //    }

                        //}
                        //else {
                        //    $scope.OrganizationNames = [];
                        //    $("#divOrganizationNamesList").modal('toggle');
                        //    //$scope.feinData.EntityName = "";
                        //    $scope.feinData.IsOrgNameExists = false;
                        //    //$scope.feinData.IsShowFederalTax = false;
                        //}
                    });
                }
            };


            $scope.validateFeinRule = function () {
                if ($scope.feinData.IsFederalTax
                                && $('#ddlTrustFein option:selected').text() != '--Select Status Type--'
                                && $('#ddlTrustFein option:selected').text() != 'Church/Church affiliated'
                                && $('#ddlTrustFein option:selected').text() != 'Government entity'
                                && $('#ddlTrustFein option:selected').text() != 'Annual gross receipts normally $5,000 or less') {
                    $scope.feinData.IsShowFederalTax = true;
                }
                else {
                    $scope.feinData.IsShowFederalTax = false;
                }
            };

            $scope.clearUBI = function () {
                //$scope.feinData.UBINumber = '';
                if ($scope.feinData.FeinUbiCount >= 0)
                    $scope.feinData.EntityName = $scope.feinData.UBIOldName;

                $scope.feinData.IsOrgNameExists = false;
                $scope.feinData.isHavingEntityOnUBISearch = false;
                $scope.feinData.UBINumber = '';
            }
            //Is FEIN Number exists or not checking
            $scope.IsFEINNumberExists = function () {
                var data = { params: { feinNumber: $scope.feinData.FEINNumber } }
                if (data.FEINNumber != '' && data.FEINNumber != null) {
                    // IsFEINNumberExists method is avialble in constants.js
                    wacorpService.get(webservices.CFT.IsFEINNumberExists, data, function (response) {
                        if (response.data == 'true') {
                            // Folder Name: app Folder
                            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
                            wacorpService.alertDialog(messages.Fein.isFEINExistorNot);
                            $scope.feinData.IsFEINNumberExistsorNot = false;
                            $scope.feinData.FEINNumber = null;
                        }
                        else {
                            $scope.feinData.IsFEINNumberExistsorNot = true;
                        }
                    }, function (response) {
                    });
                }

            };

            $scope.onSelectOrganization = function (org) {
                $scope.SelectedOrganization = undefined;
                $scope.SelectedOrganization = org;
            }

            $scope.selectOrganization = function () {
                if ($scope.SelectedOrganization != null && $scope.SelectedOrganization != undefined) {
                    $scope.feinData.EntityName = $scope.SelectedOrganization.EntityName.replace(/(^"|"$)/g, '');
                    $scope.feinData.IsOrgNameExists = true;
                    $scope.feinData.businessNames = 0;
                    //if ($scope.feinData.FEINNumber != $scope.feinData.FeinOldvalue) {
                    //    $scope.feinData.FeinOldvalue = $scope.feinData.FEINNumber;
                    //    //$scope.feinData.IsShowFederalTax = true;
                    //}
                    if ($scope.feinData.FeinOldvalue != $scope.feinData.FEINNumber) {

                        $scope.validateFeinRule();
                    }
                    else if ($scope.feinData.FeinOldvalue == $scope.feinData.FEINNumber) {

                        if (!$scope.feinData.IsNewRegistration) {
                            if ($scope.feinData.FederaltaxUpload.length > 0) {
                                angular.forEach($scope.feinData.FederaltaxUpload, function (value, data) {
                                    var index = $scope.feinData.FederaltaxUpload.indexOf(value);
                                    $scope.feinData.FederaltaxUpload.splice(index, constant.ONE);
                                });
                            }
                            $scope.feinData.IsFederalTax = $scope.feinData.OldIsFederalTax;
                            $scope.feinData.IsShowFederalTax = $scope.feinData.OldIsShowFederalTax;
                            $scope.feinData.FederalTaxExemptId = $scope.feinData.OldFederalTaxExemptId;
                        }
                        //$scope.validateFeinRule();
                    }
                    $("#divOrganizationNamesList").modal('toggle');
                }
            }

            $scope.cancel = function () {
                $("#divOrganizationNamesList").modal('toggle');
            };
            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.feinData.UBINumber = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.feinData.UBINumber = pastedText;
                    });
                    //$scope.feinData.UBINumber = (e.currentTarget.value).replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                }
            };

            $scope.setUBILength = function (e) {
                //if (e.currentTarget.value.length >= 9) {
                //    e.preventDefault();
                //}
                if (e.currentTarget.value != undefined && e.currentTarget.value != null && e.currentTarget.value!="" && e.currentTarget.value.length >= 9) {
                    // Allow: backspace, delete, tab, escape, enter and .
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                        // Allow: Ctrl+A, Command+A
                        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                        // Allow: home, end, left, right, down, up
                        (e.keyCode >= 35 && e.keyCode <= 40)) {
                        // let it happen, don't do anything
                        return;
                    }
                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                    }
                    e.preventDefault();
                }
            };

            var oldvalue1 = '';
            $scope.$watch('feinData.FederalTaxExemptId', function (newValue, oldValue) {
                if (newValue != oldValue) {
                    oldvalue1 = oldValue;
                }
            });

            $scope.FederalChange = function (id, files) {
                if (id > 0) {
                    var cartlist = $filter('filter')($scope.FederalTaxTypes, { Key: id });
                    if (cartlist[0].Value === "Church/Church affiliated" || cartlist[0].Value === "Government entity" || cartlist[0].Value === "Annual gross receipts normally $5,000 or less") {
                        $scope.feinData.IsShowFederalTax = false;
                        $scope.feinData.FederalTaxExemptText = cartlist[0].Value;
                    }
                    else {
                        $scope.feinData.IsShowFederalTax = true;
                    }
                    if (!$scope.feinData.IsShowFederalTax) {
                        switch ($scope.feinData.FederalTaxExemptText) {
                            case 'Church/Church affiliated':
                                if ($scope.feinData.FederaltaxUpload != undefined && $scope.feinData.FederaltaxUpload.length > 0) {
                                    // // Folder Name: app Folder
                                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                                        // deleteAllUploadedFiles method is available in constants.js
                                        wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                            $scope.feinData.FederaltaxUpload = [];
                                            $scope.feinData.IsShowFederalTax = false;
                                        })

                                    },
                                    function () {
                                        $scope.feinData.FederalTaxExemptId = oldvalue1;
                                        $scope.feinData.IsShowFederalTax = true;
                                    }
                                    );
                                }
                                break;
                            case 'Government entity':
                                if ($scope.feinData.FederaltaxUpload != undefined && $scope.feinData.FederaltaxUpload.length > 0) {
                                    // // Folder Name: app Folder
                                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js  
                                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                                        // deleteAllUploadedFiles method is available in constants.js
                                        wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                            $scope.feinData.FederaltaxUpload = [];
                                            $scope.feinData.IsShowFederalTax = false;
                                        })

                                    },
                                    function () {
                                        $scope.feinData.FederalTaxExemptId = oldvalue1;
                                        $scope.feinData.IsShowFederalTax = true;
                                    }
                                    );
                                }

                                break;
                            case 'Annual gross receipts normally $5,000 or less':
                                if ($scope.feinData.FederaltaxUpload != undefined && $scope.feinData.FederaltaxUpload.length > 0) {
                                    // // Folder Name: app Folder
                                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                                        // deleteAllUploadedFiles method is available in constants.js
                                        wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                            $scope.feinData.FederaltaxUpload = [];
                                            $scope.feinData.IsShowFederalTax = false;
                                        })

                                    },
                                    function () {
                                        $scope.feinData.FederalTaxExemptId = oldvalue1;
                                        $scope.feinData.IsShowFederalTax = true;
                                    });
                                }
                                break;
                        }
                    }
                }
                else if ($scope.feinData.FederalTaxExemptText != "Church/Church affiliated" || $scope.feinData.FederalTaxExemptText != "Government entity" || $scope.feinData.FederalTaxExemptText != "Annual gross receipts normally $5,000 or less") {
                    $scope.feinData.IsShowFederalTax = false;
                    if ($scope.feinData.FederaltaxUpload != undefined && $scope.feinData.FederaltaxUpload.length > 0) {
                        // // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            angular.forEach($scope.feinData.FederaltaxUpload, function (value, data) {
                                if (value.BusinessFilingDocumentId > 0) {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.feinData.FederaltaxUpload.indexOf(value);
                                    $scope.feinData.FederaltaxUpload.splice(index, 1);
                                }

                            });
                            $scope.feinData.IsShowFederalTax = false;
                            //wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                            //    $scope.feinData.FederaltaxUpload = [];
                            //})
                        }, function () {
                            $scope.feinData.IsShowFederalTax = true;
                            $scope.feinData.IsFederalTax = true;
                        });
                    }
                    else {
                        $scope.feinData.FederaltaxUpload = [];
                    }
                }
                else {
                    $scope.feinData.IsShowFederalTax = true;
                }

            }

            $scope.FederalNo = function () {
                $scope.feinData.FederalTaxExemptId = '';
            };

            $scope.checkArticleByLaws = function () {
                if ($scope.feinData.ArticlesOfIncorporationAndBylaws) {
                    $scope.feinData.TrustAgreement = false;
                    $scope.feinData.LastWillAndTestament = false;
                    $scope.feinData.ProbateOrder = false;
                }
            };

            $scope.checkTrustAgreement = function () {
                if ($scope.feinData.TrustAgreement) {
                    $scope.feinData.ArticlesOfIncorporationAndBylaws = false;
                    $scope.feinData.LastWillAndTestament = false;
                    $scope.feinData.ProbateOrder = false;
                }
            };

            $scope.checkLastWillAndTestament = function () {
                if ($scope.feinData.LastWillAndTestament) {
                    $scope.feinData.ArticlesOfIncorporationAndBylaws = false;
                    $scope.feinData.TrustAgreement = false;
                    $scope.feinData.ProbateOrder = false;
                }
            };

            $scope.checkProbateOrder = function () {
                if ($scope.feinData.ProbateOrder) {
                    $scope.feinData.LastWillAndTestament = false;
                    $scope.feinData.TrustAgreement = false;
                    $scope.feinData.ArticlesOfIncorporationAndBylaws = false;
                }
            };

        },
    };
});

wacorpApp.directive('trustfinancialhistory', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustFinancialHistory/_TrustFinancialHistory.html',
        restrict: 'A',
        scope: {
            isHistory: '=?isHistory',
            financialData: '=?financialData',
            currentData: '=?currentData'
            //isEdited: '=?isEdited',
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.isHistory = $scope.isHistory || false;
            $scope.financialData.CFTFinancialHistoryList = $scope.financialData.CFTFinancialHistoryList || [];
            //$scope.isEdited = $scope.isEdited || false;

            var FinancialInfoScope = {
                IsFIFullAccountingYear: false,
                AccountingyearBeginningDate: null,
                AccountingyearEndingDate: null,
                FirstAccountingyearEndDate: null,
                BeginingGrossAssets: null,
                GrantContributionsProgramService: null,
                TotalRevenue: null,
                EndingGrossAssets: null,
                Compensation: null,
                TotalExpenses: null,
                Comments: null,
                CFTFinancialHistoryList: []
            };

            //$scope.financialData = $scope.financialData ? angular.extend(FinancialInfoScope, $scope.financialData) : angular.copy(FinancialInfoScope);
            $scope.financialData = $scope.financialData;

            //$scope.$watch('financialData.CFTFinancialHistoryList', function () {
            //    angular.forEach($scope.financialData.CFTFinancialHistoryList, function (fiscalInfo) {
            //        fiscalInfo.AccountingyearBeginningDate = wacorpService.dateFormatService(fiscalInfo.AccountingyearEndingDate);
            //        fiscalInfo.AccountingyearEndingDate = wacorpService.dateFormatService(fiscalInfo.AccountingyearEndingDate);
            //    });

            //}, true);

            //Edit fundraiser Financial Info
            $scope.editFinancialInfo = function (financialItem) {
                $scope.currentData.IsFIFullAccountingYear = financialItem.IsFIFullAccountingYear;
                $scope.currentData.FinancialSeqNo = financialItem.SequenceNo;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.currentData.FirstAccountingyearEndDate = wacorpService.dateFormatService(financialItem.FirstAccountingyearEndDate);
                $scope.currentData.AccountingyearBeginningDate = wacorpService.dateFormatService(financialItem.AccountingyearBeginningDate);
                $scope.currentData.AccountingyearEndingDate = wacorpService.dateFormatService(financialItem.AccountingyearEndingDate);

                $scope.currentData.BeginingGrossAssets = financialItem.BeginingGrossAssets;
                $scope.currentData.GrantContributionsProgramService = financialItem.GrantContributionsProgramService;
                $scope.currentData.TotalRevenue = financialItem.TotalRevenue;
                $scope.currentData.EndingGrossAssets = financialItem.EndingGrossAssets;
                $scope.currentData.Compensation = financialItem.Compensation;
                $scope.currentData.TotalExpenses = financialItem.TotalExpenses;
                if ($scope.financialData.BusinessFiling != null && $scope.financialData.BusinessFiling != undefined) {
                    if ($scope.financialData.BusinessFiling.FilingTypeName == 'RE-REGISTRATION') {
                        $scope.currentData.IRSHisDocumentId = financialItem.IRSHisDocumentId;
                        $scope.currentData.FinancialIRSDocumentList = financialItem.FinancialIRSDocumentList;
                    }
                }
                $rootScope.isGlobalEdited = true;
            };
        },
    };
});
wacorpApp.directive('charitiesFundraiserServiceContract', function ($filter) {
    return {
        templateUrl: 'ng-app/directives/CFT/CharitiesFundraiserServiceContract/_charitiesFundraiserServiceContract.html',
        restrict: 'A',
        scope: {
            bondData: '=?bondData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.file = {};
            //$scope.file.FileLocation = "CharitiesUploadDocuments\\FundraiserUploadDocuments\\CommercialFundraiserBond.pdf";
            $scope.file.FileName = "ViewContractFile.pdf";
            $scope.file.TempFileName = "ViewContractFile.pdf";
            //$scope.file.TempFileLocation = "CharitiesUploadDocuments\\FundraiserUploadDocuments\\CommercialFundraiserBond.pdf";
        },
    };
});

wacorpApp.directive('contractBetweenCharityAndFundraiser', function ($filter) {
    return {
        templateUrl: 'ng-app/directives/CFT/CharitiesFundraiserContract/_contractBetweenCharityAndFundraiser.html',
        restrict: 'A',
        scope: {
            contractFiles: '=?contractFiles',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.showErrorMessage = $scope.showErrorMessage || false;



        },
    };
});

wacorpApp.directive('dateOfAdoption', function () {
    return {
        templateUrl: 'ng-app/directives/DateOfAdoption/DateOfAdoption.html',
        restrict: 'A',
        scope: {
            dateOfAdoptionData: '=?dateOfAdoptionData',
            showErrorMessage: '=?showErrorMessage',
            sectionName: '=?sectionName'
        },
        controller: function ($scope) {
            $scope.messages = messages;
            $scope.dateOfAdoptionData = $scope.dateOfAdoptionData || {};
            $scope.dateOfAdoptionData.DateOfAdoptionType = angular.isNullorEmpty($scope.dateOfAdoptionData.DateOfAdoptionType) ? ResultStatus.DATEOFADOPTIONFILING : $scope.dateOfAdoptionData.DateOfAdoptionType;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.sectionName = angular.isNullorEmpty($scope.sectionName) ? "" : $scope.sectionName;
            $scope.dateOfAdoptionData.IsAmendmentAdoptionChange = angular.isNullorEmpty($scope.dateOfAdoptionData.IsAmendmentAdoptionChange) ? false : $scope.dateOfAdoptionData.IsAmendmentAdoptionChange; //Is Entity Type Radio button

            if ($scope.sectionName == 'Amendment') {
                $scope.dateOfAdoptionData.DateOfAdoptionType = "DateOfAdoptionSpecify";
            }
        },
    };
});
wacorpApp.directive('charitiesOptionalQualifierQuestions', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CharitiesOptionalQualifierQuestions/_CharitiesOptionalQualifierQuestions.html',
        restrict: 'A',
        scope: {
            qualifierInfo: '=?qualifierInfo',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;

            //var qualifierScope = {
            //    IsIntegratedAuxiliary: false, IsPoliticalOrganization: false, IsRaisingFundsForIndividual: false,
            //    IsRaisingLessThan50000: false, IsAnyOnePaid: false, IsInfoAccurate: false
            //};

            //$scope.qualifierInfo = $scope.qualifierInfo ? angular.extend(qualifierScope, $scope.qualifierInfo) : angular.copy(qualifierScope);

            $scope.$watch('qualifierInfo', function () {
                $scope.qualifierInfo.IsIntegratedAuxiliary = angular.isNullorEmpty($scope.qualifierInfo.IsIntegratedAuxiliary) ? false : $scope.qualifierInfo.IsIntegratedAuxiliary;
                $scope.qualifierInfo.IsPoliticalOrganization = angular.isNullorEmpty($scope.qualifierInfo.IsPoliticalOrganization) ? false : $scope.qualifierInfo.IsPoliticalOrganization;
                $scope.qualifierInfo.IsRaisingFundsForIndividual = angular.isNullorEmpty($scope.qualifierInfo.IsRaisingFundsForIndividual) ? false : $scope.qualifierInfo.IsRaisingFundsForIndividual;
                $scope.qualifierInfo.IsRaisingLessThan50000 = angular.isNullorEmpty($scope.qualifierInfo.IsRaisingLessThan50000) ? false : $scope.qualifierInfo.IsRaisingLessThan50000;
                $scope.qualifierInfo.IsAnyOnePaid = angular.isNullorEmpty($scope.qualifierInfo.IsAnyOnePaid) ? false : $scope.qualifierInfo.IsAnyOnePaid;
                $scope.qualifierInfo.IsInfoAccurate = angular.isNullorEmpty($scope.qualifierInfo.IsInfoAccurate) ? false : $scope.qualifierInfo.IsInfoAccurate;
            });

            $scope.validateQualifierQuestions = function () {
                $scope.qualifierInfo.IsQualified = ($scope.qualifierInfo.IsIntegratedAuxiliary || $scope.qualifierInfo.IsPoliticalOrganization
                    || $scope.qualifierInfo.IsRaisingFundsForIndividual || $scope.qualifierInfo.IsRaisingLessThan50000 || $scope.qualifierInfo.IsAnyOnePaid);
            };

        },
    };
});

wacorpApp.directive('cftItemSummary', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CFTItemSummary/_CFTItemSummary.html',
        restrict: 'A',
        scope: {
            mainModel: '=?mainModel'
        },
        controller: function ($scope, wacorpService) {
            $scope.mainModel = $scope.mainModel;           
        },
    };
});

wacorpApp.directive("poAddressReturnMail", function myfunction() {
    return {
        templateUrl: 'ng-app/directives/POAddressReturnMail/POAddressReturnMail.html',
        restrict: 'A',
        scope: {
            poAddress: '=?poAddress'
        },
        controller: function ($scope, wacorpService) {
            $scope.poAddress = $scope.poAddress || {};
        }
    };
});
wacorpApp.directive("raAddressReturnMail", function () {
    return {
        restrict: 'A',
        templateUrl: 'ng-app/directives/RAAddressReturnMail/RAAddressReturnMail.html',
        scope: {
            raAddress:'=?raAddress'
        },
        controller: function ($scope, wacorpService) {
            $scope.raAddress = $scope.raAddress || {};
        }
    };
});
wacorpApp.directive('publicBenefitNonProfit', function () {
    return {
        templateUrl: 'ng-app/directives/PublicBenefitNonProfit/PublicBenefitNonProfit.html',
        restrict: 'A',
        scope: {
            publicBenefitNonProfitData: '=?publicBenefitNonProfitData',
            sectionName: '=?sectionName',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            isRequired: '=?isRequired'
        },
        controller: function ($scope, wacorpService, $timeout, $rootScope) {
            $scope.messages = messages;
            $scope.sectionName = $scope.sectionName || "";
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isRequired = true;

            // show/hide the screen parts based on entity types
            var ScreenPart = function (screenPart, modal, businessTypeID) {
                if (angular.isNullorEmpty(screenPart))
                    return false;
                return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
            };

            $(function () {
                // Document ready shorthand
                $scope.ValidateIsPublicBenefitNonProfitForm();
            });

            var isCanBePublicBenefitNonProfitValid = false;
            var isElectToBePublicBenefitNonProfitValid = false;
            var isBusinessNamePublicBenefit = false;
            var isBusinessNameValid = false;
            var isPublicBenefitNonProfitFormValid = false;
            $scope.businessName = $scope.publicBenefitNonProfitData.BusinessName != undefined ? $scope.publicBenefitNonProfitData.BusinessName : $rootScope.modal.BusinessName;

            if ($scope.isReview) {
                $scope.IsCanBePublicBenefitNonProfit = $rootScope.modal.IsCanBePublicBenefitNonProfit;
                $scope.IsElectToBePublicBenefitNonProfit = $rootScope.modal.IsElectToBePublicBenefitNonProfit;
            } else {
                $scope.IsCanBePublicBenefitNonProfit = $scope.publicBenefitNonProfitData.IsCanBePublicBenefitNonProfit != undefined ? $scope.publicBenefitNonProfitData.IsCanBePublicBenefitNonProfit : null;
                $scope.IsElectToBePublicBenefitNonProfit = $scope.publicBenefitNonProfitData.IsElectToBePublicBenefitNonProfit != undefined ? $scope.publicBenefitNonProfitData.IsElectToBePublicBenefitNonProfit : null;
            };

            // Set initial values if they exist
            $scope.init = function () {

            };

            // Click event
            $scope.CheckIsCanBePublicBenefitNonProfit = function () {
                if ($('#rdoIsCanBePublicBenefitNonProfitYes').is(':checked')) {
                    $scope.IsCanBePublicBenefitNonProfit = true;
                } else if ($('#rdoIsCanBePublicBenefitNonProfitNo').is(':checked')) {
                    $scope.IsCanBePublicBenefitNonProfit = false;
                    if (CheckIsBusinessNamePublicBenefit()) {
                        var publicBenefitNonProfitMsg = 'If the Nonprofit Corporation does not qualify or no longer elects to have the Public Benefit designation applied, the Nonprofit Corporation must file an Amendment to remove the words "Public Benefit" from its name prior to submitting the Annual Report.';
                        wacorpService.alertDialog(publicBenefitNonProfitMsg);
                    }
                } else {
                    $scope.IsCanBePublicBenefitNonProfit = null;
                }

                //alert("click worked");
                $scope.ValidateIsPublicBenefitNonProfitForm();
            };

            // Click event
            $scope.CheckIsElectToBePublicBenefitNonProfit = function () {
                if ($('#rdoIsElectToBePublicBenefitNonProfitYes').is(':checked')) {
                    $scope.IsElectToBePublicBenefitNonProfit = true;
                } else if ($('#rdoIsElectToBePublicBenefitNonProfitNo').is(':checked')) {
                    $scope.IsElectToBePublicBenefitNonProfit = false;
                    if (CheckIsBusinessNamePublicBenefit()) {
                        var publicBenefitNonProfitMsg = 'If the Nonprofit Corporation does not qualify or no longer elects to have the Public Benefit designation applied, the Nonprofit Corporation must file an Amendment to remove the words "Public Benefit" from its name prior to submitting the Annual Report.';
                        wacorpService.alertDialog(publicBenefitNonProfitMsg);
                    }
                } else {
                    $scope.IsElectToBePublicBenefitNonProfit = null;
                }

                //alert("click worked");
                $scope.ValidateIsPublicBenefitNonProfitForm();
            };

            // Check if question 1 is answered
            $scope.ValidateIsCanBePublicBenefitNonProfit = function () {
                if ($('#rdoIsCanBePublicBenefitNonProfitYes').is(':checked') || $('#rdoIsCanBePublicBenefitNonProfitNo').is(':checked')) {
                    isCanBePublicBenefitNonProfitValid = true;
                } else {
                    isCanBePublicBenefitNonProfitValid = false;
                }
                $scope.publicBenefitNonProfitData.isCanBePublicBenefitNonProfitValid = isCanBePublicBenefitNonProfitValid;
                return isCanBePublicBenefitNonProfitValid;
            };

            // Check if question 2 is answered
            $scope.ValidateIsElectToBePublicBenefitNonProfit = function () {
                if ($('#rdoIsElectToBePublicBenefitNonProfitYes').is(':checked') || $('#rdoIsElectToBePublicBenefitNonProfitNo').is(':checked')) {
                    isElectToBePublicBenefitNonProfitValid = true;
                } else {
                    isElectToBePublicBenefitNonProfitValid = false;
                }
                $scope.publicBenefitNonProfitData.isElectToBePublicBenefitNonProfitValid = isElectToBePublicBenefitNonProfitValid;
                return isElectToBePublicBenefitNonProfitValid;
            };

            // Check if business name contains 'PUBLIC BENEFIT'
            function CheckIsBusinessNamePublicBenefit() {
                if ($scope.businessName.toUpperCase().indexOf("PUBLIC BENEFIT") >= 0) {
                    return true;
                }
                else {
                    return false;
                }
            };

            // Check if business name is valid given answers to both questions
            $scope.CheckIsBusinessNameValid = function () {
                if (CheckIsBusinessNamePublicBenefit() == true) {
                    if ($scope.IsCanBePublicBenefitNonProfit == true && $scope.IsElectToBePublicBenefitNonProfit == true) {
                        isBusinessNameValid = true;
                    } else if ($scope.IsCanBePublicBenefitNonProfit == false || $scope.IsElectToBePublicBenefitNonProfit == false) {
                        isBusinessNameValid = false;
                    } else if ($scope.IsCanBePublicBenefitNonProfit == null || $scope.IsElectToBePublicBenefitNonProfit == null) {
                        isBusinessNameValid = null;
                    }
                } else {
                    isBusinessNameValid = true;
                }
                $scope.publicBenefitNonProfitData.isBusinessNameValid = isBusinessNameValid;
                $scope.isBusinessNameValid = isBusinessNameValid;
                return isBusinessNameValid
            };

            // Validate form
            $scope.ValidateIsPublicBenefitNonProfitForm = function () {
                var validIsCanBePublicBenefitNonprofit = $scope.ValidateIsCanBePublicBenefitNonProfit();
                var validIsElectToBePublicBenefitNonprofit = $scope.ValidateIsElectToBePublicBenefitNonProfit();

                if ($scope.CheckIsBusinessNameValid()) {
                    if (validIsCanBePublicBenefitNonprofit == true
                        && validIsElectToBePublicBenefitNonprofit == true) {
                        isPublicBenefitNonProfitFormValid = true;
                        $scope.isPublicBenefitNonProfitValid = true;
                        $scope.publicBenefitNonProfitData.isPublicBenefitNonProfitValid = true;
                    } else {
                        isPublicBenefitNonProfitFormValid = false;
                        $scope.isPublicBenefitNonProfitValid = false;
                        $scope.publicBenefitNonProfitData.isPublicBenefitNonProfitValid = false;
                    }
                }

                //alert("vars: " + $scope.isPublicBenefitNonProfitValid + "  " + $scope.publicBenefitNonProfitData.isPublicBenefitNonProfitValid);

            };
        }
    }
});

wacorpApp.directive('feinNonProfit', function () {
	return {
		templateUrl: 'ng-app/directives/FEINNonProfit/FEINNonProfit.html',
		restrict: 'A',
		scope: {
			feinNonProfitData: '=?feinNonProfitData',
			sectionName: '=?sectionName',
			isReview: '=?isReview',
			showErrorMessage: '=?showErrorMessage',
			isRequired: '=?isRequired',
		},
		controller: function ($scope, wacorpService, $timeout, $rootScope) {
			$scope.messages = messages;
			$scope.sectionName = $scope.sectionName || "";
			$scope.isReview = $scope.isReview || false;
			$scope.showErrorMessage = $scope.showErrorMessage || false;
			$scope.isRequired = true;

			// show/hide the screen parts based on entity types
			var ScreenPart = function (screenPart, modal, businessTypeID) {
				if (angular.isNullorEmpty(screenPart))
					return false;
				return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
			};

			$scope.feinNonProfitData = !$scope.feinNonProfitData ? null : $scope.feinNonProfitData;


			//$scope.setFEINNoLength = function (e) {
			//	if ($scope.feinNonProfitData.length > 8) {
			//		e.preventDefault();
			//	}
			//};


			//copypaste Fein Number
			$scope.setPastedFeinNumber = function (e) {
				var pastedText = "";
				if (typeof e.originalEvent.clipboardData !== "undefined") {
					pastedText = e.originalEvent.clipboardData.getData('text/plain');
					pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
					$scope.businessSearchCriteria.ID = pastedText;
					e.preventDefault();
				} else {
					$timeout(function () {
						pastedText = angular.element(e.currentTarget).val();
						pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
						$scope.businessSearchCriteria.ID = pastedText;
					});
				}
			};

		}
	}
});
wacorpApp.directive('charitableNonProfitReporting', function () {
    return {
        templateUrl: 'ng-app/directives/CharitableNonProfit/CharitableNonProfitReporting.html',
        restrict: 'A',
        scope: {
            charitableNonProfitReportingData: '=?charitableNonProfitReportingData',
            sectionName: '=?sectionName',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            isRequired: '=?isRequired'
        },
        controller: function ($scope, wacorpService, $timeout, $rootScope) {
            $scope.messages = messages;
            $scope.sectionName = $scope.sectionName || "";
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isRequired = true;

            //Validation Variables
            var isCharityValReq = false;
            var isExemptValReq = false;
            var isReporting1ValReq = false;
            var isReporting2ValReq = false;

            var isCharityValid = false;
            var isExemptValid = false;
            var isReporting1Valid = false;
            var isReporting2Valid = false;
            var isCharityAndReportingValid = false;
            //Validation Variables

            //Setting Filing Variables
            var FilingType = $scope.charitableNonProfitReportingData.BusinessFiling.FilingTypeName;
            var BusinessType = $scope.charitableNonProfitReportingData.BusinessType;
            //Set Domestic
            var isDomestic = false;
            if (BusinessType === "WA NONPROFIT CORPORATION"
                        || BusinessType === "WA NONPROFIT PROFESSIONAL SERVICE CORPORATION") {
                isDomestic = true;
            };
            var ShowCharitable = $scope.charitableNonProfitReportingData.ShowCharitable != undefined ? $scope.charitableNonProfitReportingData.ShowCharitable : false;
            var ShowExempt = $scope.charitableNonProfitReportingData.ShowExempt != undefined ? $scope.charitableNonProfitReportingData.ShowExempt : false;
            var ShowQuestions = $scope.charitableNonProfitReportingData.ShowQuestions != undefined ? $scope.charitableNonProfitReportingData.ShowQuestions : false;
            
            //NP Charitable and Reporting PDF Display Update
            $scope.isDomestic = isDomestic || false;
            $scope.ShowCharitable = ShowCharitable || false;
            $scope.ShowExempt = ShowExempt || false;
            $scope.ShowQuestions = ShowQuestions || false;
            //NP Charitable and Reporting PDF Display Update

            //TFS 2628
            $scope.ExistingIsCharitableNonProfit = $scope.charitableNonProfitReportingData.ExistingIsCharitableNonProfit != undefined ? $scope.charitableNonProfitReportingData.ExistingIsCharitableNonProfit : false;
            $scope.BusinessType = $scope.charitableNonProfitReportingData.BusinessType;

            if ($scope.isReview !== true) {
                $scope.IsCharitableNonProfit = $scope.charitableNonProfitReportingData.IsCharitableNonProfit != undefined ? $scope.charitableNonProfitReportingData.IsCharitableNonProfit : null;
                $scope.IsNonProfitExempt = $scope.charitableNonProfitReportingData.IsNonProfitExempt != undefined ? $scope.charitableNonProfitReportingData.IsNonProfitExempt : null;
                $scope.NonProfitReporting1 = $scope.charitableNonProfitReportingData.NonProfitReporting1 != undefined ? $scope.charitableNonProfitReportingData.NonProfitReporting1 : null;
                $scope.NonProfitReporting2 = $scope.charitableNonProfitReportingData.NonProfitReporting2 != undefined ? $scope.charitableNonProfitReportingData.NonProfitReporting2 : null;
            };

            //$scope.IsCharitableNonProfit = $scope.IsCharitableNonProfit;
            //$scope.IsNonProfitExempt = $scope.IsNonProfitExempt ;
            //$scope.NonProfitReporting1 = $scope.NonProfitReporting1;
            //$scope.NonProfitReporting2 = $scope.NonProfitReporting2;
            //$scope.entityData = $scope.entityData ? angular.extend(businessInformationScope, $scope.entityData) : angular.copy(businessInformationScope);

            // show/hide the screen parts based on entity types
            var ScreenPart = function (screenPart, modal, businessTypeID) {
                if (angular.isNullorEmpty(screenPart))
                    return false;
                return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
            };

            if ($scope.isReview) {
                $scope.ExistingIsCharitableNonProfit = $rootScope.modal.ExistingIsCharitableNonProfit;
                $scope.BusinessType = $rootScope.modal.BusinessType;

                $scope.IsCharitableNonProfit = $rootScope.modal.IsCharitableNonProfit;
                $scope.IsNonProfitExempt = $rootScope.modal.IsNonProfitExempt;
                $scope.NonProfitReporting1 = $rootScope.modal.NonProfitReporting1;
                $scope.NonProfitReporting2 = $rootScope.modal.NonProfitReporting2;


            };

            $(document).ready(function () {
                if ($scope.isReview != true){
                    $scope.SetDisplayedSections();
                };
                //$scope.ValidateCharitableReporting();
            });

            $scope.init = function () {

            };

            $scope.initCharity = function () {

            };

            $scope.initCharityChanges = function () {

            };

            $scope.initCharityQuestions = function () {

            };

            $scope.CheckIsCharitableNonProfit = function () {
                if ($('#rdoIsCharitableNonProfitYes').is(':checked')) {
                    $scope.IsCharitableNonProfit = true;
                } else if ($('#rdoIsCharitableNonProfitNo').is(':checked')) {
                    $scope.IsCharitableNonProfit = false;

                    //$('#rdoIsNonProfitExemptYes').prop('checked', false);
                    //$('#rdoIsNonProfitExemptNo').prop('checked', false);
                    document.getElementById("rdoIsNonProfitExemptYes").checked = false;
                    document.getElementById("rdoIsNonProfitExemptNo").checked = false;
                    $scope.IsNonProfitExempt = null;
                    document.getElementById("rdoNonProfitReporting1Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting1No").checked = false;
                    $scope.NonProfitReporting1 = null;
                    document.getElementById("rdoNonProfitReporting2Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting2No").checked = false;
                    $scope.NonProfitReporting2 = null;
                } else {
                    $('input:rdoIsCharitableNonProfitYes').prop('checked', false);
                    $('input:rdoIsCharitableNonProfitNo').prop('checked', false);
                    $scope.IsCharitableNonProfit = null;

                    document.getElementById("rdoIsNonProfitExemptYes").checked = false;
                    document.getElementById("rdoIsNonProfitExemptNo").checked = false;
                    $scope.IsNonProfitExempt = null;
                    document.getElementById("rdoNonProfitReporting1Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting1No").checked = false;
                    $scope.NonProfitReporting1 = null;
                    document.getElementById("rdoNonProfitReporting2Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting2No").checked = false;
                    $scope.NonProfitReporting2 = null;
                }
                $scope.SetDisplayedSections();
            };

            $scope.CheckCharitableChanges = function () {
                if ($('#rdoIsNonProfitExemptYes').is(':checked')) {
                    $scope.IsNonProfitExempt = true;

                    document.getElementById("rdoNonProfitReporting1Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting1No").checked = false;
                    $scope.NonProfitReporting1 = null;
                    document.getElementById("rdoNonProfitReporting2Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting2No").checked = false;
                    $scope.NonProfitReporting2 = null;
                } else if ($('#rdoIsNonProfitExemptNo').is(':checked')) {
                    $scope.IsNonProfitExempt = false;
                } else {
                    document.getElementById("rdoIsNonProfitExemptYes").checked = false;
                    document.getElementById("rdoIsNonProfitExemptNo").checked = false;
                    $scope.IsNonProfitExempt = null;
                    document.getElementById("rdoNonProfitReporting1Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting1No").checked = false;
                    $scope.NonProfitReporting1 = null;
                    document.getElementById("rdoNonProfitReporting2Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting2No").checked = false;
                    $scope.NonProfitReporting2 = null;
                }
                $scope.SetDisplayedSections();
            };

            $scope.CheckCharitableQuestions = function () {
                if ($('#rdoNonProfitReporting1Yes').is(':checked')) {
                    $scope.NonProfitReporting1 = true;
                } else if ($('#rdoNonProfitReporting1No').is(':checked')) {
                    $scope.NonProfitReporting1 = false;
                } else {
                    document.getElementById("rdoNonProfitReporting1Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting1No").checked = false;
                    $scope.NonProfitReporting1 = null;
                }

                if ($('#rdoNonProfitReporting2Yes').is(':checked')) {
                    $scope.NonProfitReporting2 = true;
                } else if ($('#rdoNonProfitReporting2No').is(':checked')) {
                    $scope.NonProfitReporting2 = false;
                } else {
                    document.getElementById("rdoNonProfitReporting2Yes").checked = false;
                    document.getElementById("rdoNonProfitReporting2No").checked = false;
                    $scope.NonProfitReporting2 = null;
                }

                $scope.SetDisplayedSections();
                //$scope.TestVaulues();  //Used to display values for testing
            };

            $scope.SetDisplayedSections = function () {               
                ShowCharitable = false;
                ShowExempt = false;
                ShowQuestions = false;

                //Check to show Charitable
                if ($scope.ExistingIsCharitableNonProfit !== true) {
                    // TFS#2347; adding REI to FilingType
                    if (
                        FilingType === "ANNUAL REPORT"
                        || FilingType === "REINSTATEMENT"
                        || FilingType === "ARTICLES OF INCORPORATION"
                       ) {
                        ShowCharitable = true;
                    };
                };

                //Check to show Exempt
                if (
                    FilingType === "ANNUAL REPORT"
                    || FilingType === "REINSTATEMENT"
                    ) {
                    if (
                        $scope.IsCharitableNonProfit === true
                        || $scope.ExistingIsCharitableNonProfit === true
                        ) {
                        ShowExempt = true;
                    };
                };

                //Check to Show Questions
                if ($scope.IsNonProfitExempt === false) {
                    ShowQuestions = true;
                }

                $scope.DisplaySections();
            };

            $scope.DisplaySections = function () {
                document.getElementById("divIsCharitable").style.display = "none";
                document.getElementById("divCharitableChanges").style.display = "none";
                document.getElementById("divCharitableQuestions").style.display = "none";
                document.getElementById("divForeignHeader").style.display = "none";
                //document.getElementById("lblForeignHeader").style.display = "none";
                document.getElementById("divDomesticHeader").style.display = "none";
                //document.getElementById("lblDomesticHeader").style.display = "none";
                document.getElementById("divDomesticQuestion").style.display = "none";

                document.getElementById("divIsCharitable").style.visibility = "hidden";
                document.getElementById("divCharitableChanges").style.visibility = "hidden";
                document.getElementById("divCharitableQuestions").style.visibility = "hidden";
                document.getElementById("divForeignHeader").style.visibility = "hidden";
                //document.getElementById("lblForeignHeader").style.visibility = "hidden";
                document.getElementById("divDomesticHeader").style.visibility = "hidden";
                //document.getElementById("lblDomesticHeader").style.visibility = "hidden";
                document.getElementById("divDomesticQuestion").style.visibility = "hidden";

                if (ShowCharitable) {
                    document.getElementById("divIsCharitable").style.display = "";
                    document.getElementById("divIsCharitable").style.visibility = "visible";
                };
                //else {
                //    $scope.IsNonProfitExempt = null;
                //};

                if (ShowExempt) {
                    document.getElementById("divCharitableChanges").style.display = "";
                    document.getElementById("divCharitableChanges").style.visibility = "visible";
                    $scope.IsCharitableNonProfit = true;
                } else {
                    $scope.IsNonProfitExempt = null;

                    $scope.NonProfitReporting1 = null;
                    $scope.NonProfitReporting2 = null;
                };

                if (ShowQuestions) {
                    document.getElementById("divCharitableQuestions").style.display = "";
                    document.getElementById("divCharitableQuestions").style.display = "";

                    document.getElementById("divCharitableQuestions").style.visibility = "visible";
                    document.getElementById("divCharitableQuestions").style.visibility = "visible";
                    if (isDomestic) {
                        document.getElementById("divForeignHeader").style.display = "none";
                        //document.getElementById("lblForeignHeader").style.display = "none";
                        document.getElementById("divDomesticHeader").style.display = "";
                        //document.getElementById("lblDomesticHeader").style.display = "";
                        document.getElementById("divDomesticQuestion").style.display = "";

                        document.getElementById("divForeignHeader").style.visibility = "hidden";
                        //document.getElementById("lblForeignHeader").style.visibility = "hidden";
                        document.getElementById("divDomesticHeader").style.visibility = "visible";
                        //document.getElementById("lblDomesticHeader").style.visibility = "visible";
                        document.getElementById("divDomesticQuestion").style.visibility = "visible";
                    } else {
                        document.getElementById("divForeignHeader").style.display = "";
                        //document.getElementById("lblForeignHeader").style.display = "";
                        document.getElementById("divDomesticHeader").style.display = "none";
                        //document.getElementById("lblDomesticHeader").style.display = "none";
                        document.getElementById("divDomesticQuestion").style.display = "none";

                        document.getElementById("divForeignHeader").style.visibility = "visible";
                        //document.getElementById("lblForeignHeader").style.visibility = "visible";
                        document.getElementById("divDomesticHeader").style.visibility = "hidden";
                        //document.getElementById("lblDomesticHeader").style.visibility = "hidden";
                        document.getElementById("divDomesticQuestion").style.visibility = "hidden";
                    }
                } else {
                    $scope.NonProfitReporting1 = null;
                    $scope.NonProfitReporting2 = null;
                };

                $scope.SetValues();
            };

            $scope.SetValues = function () {
                $scope.charitableNonProfitReportingData.IsCharitableNonProfit = $scope.IsCharitableNonProfit;
                $scope.charitableNonProfitReportingData.IsNonProfitExempt = $scope.IsNonProfitExempt;
                $scope.charitableNonProfitReportingData.NonProfitReporting1 = $scope.NonProfitReporting1;
                $scope.charitableNonProfitReportingData.NonProfitReporting2 = $scope.NonProfitReporting2;

                $scope.ValidateCharitableReporting();
            };

            $scope.ValidateCharitableNonProfit = function() {
                //Setting if validation is required
                if (document.getElementById("divIsCharitable").style.display === "") {
                //if (document.getElementById("divIsCharitable").style.visibility === "visible") {
                    isCharityValReq = true;
                } else {
                    isCharityValReq = false;
                };
                //Setting Validation
                if (isCharityValReq == true) {
                    if ($scope.IsCharitableNonProfit === true
                        || $scope.IsCharitableNonProfit === false) {
                        isCharityValid = true;
                    } else {
                        isCharityValid = false;
                    };
                } else {
                    isCharityValid = true;
                };

                $scope.charitableNonProfitReportingData.isCharityValid = isCharityValid;
                return isCharityValid;
            };

            $scope.ValidateCharitableNonProfitExempt = function () {
                //Setting if validation is required
                if (document.getElementById("divCharitableChanges").style.display === "") {
                //if (document.getElementById("divCharitableChanges").style.visibility === "visible") {
                    isExemptValReq = true;
                } else {
                    isExemptValReq = false;
                };
                //Setting Validation
                if (isExemptValReq == true) {
                    if ($scope.IsNonProfitExempt === true
                        || $scope.IsNonProfitExempt === false) {
                        isExemptValid = true;
                    } else {
                        isExemptValid = false;
                    };
                } else {
                    isExemptValid = true;
                };

                $scope.charitableNonProfitReportingData.isExemptValid = isExemptValid;
                return isExemptValid;
            };

            $scope.ValidateCharitableNonProfitReporting1 = function () {
                //Setting if validation is required
                if (document.getElementById("divDomesticQuestion").style.display === "") {
                //if (document.getElementById("divDomesticQuestion").style.visibility === "visible") {
                    isReporting1ValReq = true;
                } else {
                    isReporting1ValReq = false;
                };
                //Setting Validation
                if (isReporting1ValReq == true) {
                    if ($scope.NonProfitReporting1 === true
                        || $scope.NonProfitReporting1 === false) {
                        isReporting1Valid = true;
                    } else {
                        isReporting1Valid = false;
                    };
                } else {
                    isReporting1Valid = true;
                };

                $scope.charitableNonProfitReportingData.isReporting1Valid = isReporting1Valid;
                return isReporting1Valid;
            };

            $scope.ValidateCharitableNonProfitReporting2 = function () {
                //Setting if validation is required
                if (document.getElementById("divCharitableQuestions").style.display === "") {
                //if (document.getElementById("divCharitableQuestions").style.visibility === "visible") {
                    isReporting2ValReq = true;
                } else {
                    isReporting2ValReq = false;
                };
                //Setting Validation
                if (isReporting2ValReq == true) {
                    if ($scope.NonProfitReporting2 === true
                        || $scope.NonProfitReporting2 === false) {
                        isReporting2Valid = true;
                    } else {
                        isReporting2Valid = false;
                    };
                } else {
                    isReporting2Valid = true;
                };

                $scope.charitableNonProfitReportingData.isReporting2Valid = isReporting2Valid;
                return isReporting2Valid;
            };

            $scope.ValidateCharitableReporting = function () {
                var isCharityValid = $scope.ValidateCharitableNonProfit();
                var isExemptValid = $scope.ValidateCharitableNonProfitExempt();
                var isReporting1Valid = $scope.ValidateCharitableNonProfitReporting1();
                var isReporting2Valid = $scope.ValidateCharitableNonProfitReporting2();

                //Check is Partial view is valid
                if (isCharityValid == true
                   && isExemptValid == true
                   && isReporting1Valid == true
                   && isReporting2Valid == true)
                {
                    isCharityAndReportingValid = true;
                } else {
                    isCharityAndReportingValid = false;
                };
                //Check is Partial view is valid

                $scope.charitableNonProfitReportingData.isCharityAndReportingValid = isCharityAndReportingValid;
                //$scope.TestVaulues();  //Used to display values for testing

                //NP Charitable and Reporting PDF Display Update
                //$scope.TestVaulues();
                    $scope.charitableNonProfitReportingData.isDomestic = isDomestic;
                    $scope.charitableNonProfitReportingData.ShowCharitable = ShowCharitable;
                    $scope.charitableNonProfitReportingData.ShowExempt = ShowExempt;
                    $scope.charitableNonProfitReportingData.ShowQuestions = ShowQuestions;
                    //$scope.TestVaulues();
                //NP Charitable and Reporting PDF Display Update
            };

            $scope.TestVaulues = function () {
                //Function to keep a running tally of values for testing
                //alert("IsCharitiable: " + $scope.IsCharitableNonProfit + "\r\n"
                //    + "IsNonProfitExempt: " + $scope.IsNonProfitExempt + "\r\n"
                //    + "NonProfitReporting1: " + $scope.NonProfitReporting1 + "\r\n"
                //    + "NonProfitReporting2: " + $scope.NonProfitReporting2);
                //alert($scope.BusinessType);

                //alert("isCharityValReq: " + isCharityValReq + " - isCharityValid: " + isCharityValid + "\r\n"
                //    + "isExemptValReq: " + isExemptValReq + " - isExemptValid: " + isExemptValid + "\r\n"
                //    + "isReporting1ValReq: " + isReporting1ValReq + " - isReporting1Valid: " + isReporting1Valid + "\r\n"
                //    + "isReporting2ValReq: " + isReporting2ValReq + " - isReporting2Valid: " + isReporting2Valid + "\r\n"
                //    + "Is Partial CharityNonProfitReporting valid: " + isCharityAndReportingValid);

                //alert("CharityReportingPartial is valid: " + isCharityAndReportingValid);

                alert(
                    //"isReview: " + $scope.isReview + "\r\n" +
                    "isDomestic: " + $scope.charitableNonProfitReportingData.isDomestic + "\r\n" +
                    "ShowCharitable: " + $scope.charitableNonProfitReportingData.ShowCharitable + "\r\n" +
                    "ShowExempt: " + $scope.charitableNonProfitReportingData.ShowExempt + "\r\n" +
                    "ShowQuestions: " + $scope.charitableNonProfitReportingData.ShowQuestions
                    );
            };
        }
    }
});
wacorpApp.directive('grossRevenueNonProfit', function () {
    return {
        templateUrl: 'ng-app/directives/GrossRevenueNonProfit/GrossRevenueNonProfit.html',
        restrict: 'A',
        scope: {
            grossRevenueNonProfitData: '=?grossRevenueNonProfitData',
            sectionName: '=?sectionName',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            isRequired: '=?isRequired'
        },
        controller: function ($scope, wacorpService, $timeout, $rootScope) {
            $scope.messages = messages;
            $scope.sectionName = $scope.sectionName || "";
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isRequired = true;

            //Validation Variables
            var isGrossRevenueNonProfitValReq = true;
            var isGrossRevenueNonProfitValid = false;
            var isGrossRevenueNonProfitFormValid = false;
            //Validation Variables

            //TFS 2628

            $scope.BusinessType = $scope.grossRevenueNonProfitData.BusinessType;

            // show/hide the screen parts based on entity types
            var ScreenPart = function (screenPart, modal, businessTypeID) {
                if (angular.isNullorEmpty(screenPart))
                    return false;
                return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
            };

            if ($scope.isReview !== true) {
                $scope.IsGrossRevenueNonProfit = $scope.grossRevenueNonProfitData.IsGrossRevenueNonProfit != undefined ? $scope.grossRevenueNonProfitData.IsGrossRevenueNonProfit : $scope.IsGrossRevenueNonProfit;  //null;
            };

            if ($scope.isReview) {
                $scope.ExistingIsGrossRevenueNonProfit = $rootScope.modal.ExistingIsGrossRevenueNonProfit;
                $scope.BusinessType = $rootScope.modal.BusinessType;

                $scope.IsGrossRevenueNonProfit = $scope.grossRevenueNonProfitData.IsGrossRevenueNonProfit != undefined ? $scope.grossRevenueNonProfitData.IsGrossRevenueNonProfit : $scope.IsGrossRevenueNonProfit;  //null;
            };

            $(document).ready(function () {

            });

            $scope.init = function () {

                if ($rootScope.modal != null || $rootScope.modal != undefined) {
                    //load from json
                    $scope.IsGrossRevenueNonProfit = $rootScope.modal.IsGrossRevenueNonProfit;
                } else if ($rootScope.IsGrossRevenueNonProfit == null || $rootScope.IsGrossRevenueNonProfit == undefined) {
                    //Load From Cart
                    $scope.IsGrossRevenueNonProfit = $scope.$parent.$parent.IsGrossRevenueNonProfit;
                } else {
                    //New Filing, load from Root
                    $scope.IsGrossRevenueNonProfit = $rootScope.IsGrossRevenueNonProfit;//TFS 2628 getting value from business Search (index)
                };

            };

            $scope.initGrossRevenueNonProfit = function () {

            };

            $scope.CheckIsGrossRevenueNonProfit = function () {
                if ($('#rdoIsGrossRevenueNonProfitOver500K').is(':checked')) {
                    $scope.IsGrossRevenueNonProfit = true;
                } else if ($('#rdoIsGrossRevenueNonProfitUnder500K').is(':checked')) {
                    $scope.IsGrossRevenueNonProfit = false;
                };

                $scope.SetValues();
            };

            $scope.SetValues = function () {
                $scope.grossRevenueNonProfitData.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit;

                $scope.ValidateGrossRevenueNonProfitForm();  //Changed to display only, no validation
            };

            $scope.ValidateGrossRevenueNonProfit = function () {
                //Setting if validation is required
                if (document.getElementById("divIsGrossRevenueNonProfit").style.display === "block") {
                    isGrossRevenueNonProfitValReq = true;
                } else {
                    isGrossRevenueNonProfitValReq = false;
                };
                //Setting Validation
                if (isGrossRevenueNonProfitValReq == true) {
                    if ($scope.IsGrossRevenueNonProfit === true
                        || $scope.IsGrossRevenueNonProfit === false) {
                        isGrossRevenueNonProfitValid = true;
                    } else {
                        isGrossRevenueNonProfitValid = false;
                    };
                } else {
                    isGrossRevenueNonProfitValid = true;
                };

                $scope.grossRevenueNonProfitData.isGrossRevenueNonProfitValid = isGrossRevenueNonProfitValid;
                return isGrossRevenueNonProfitValid;
            };

            $scope.ValidateGrossRevenueNonProfitForm = function () {
                var isGrossRevenueNonProfitValid = $scope.ValidateGrossRevenueNonProfit();

                //Check is Partial view is valid
                if (isGrossRevenueNonProfitValid == true) {
                    isGrossRevenueNonProfitFormValid = true;
                } else {
                    isGrossRevenueNonProfitFormValid = false;
                };
                //Check is Partial view is valid

                $scope.grossRevenueNonProfitData.isGrossRevenueNonProfitFormValid = isGrossRevenueNonProfitFormValid;
                //$scope.TestVaulues();  //Used to display values for testing
            };

            $scope.TestVaulues = function () {
                //Function to keep a running tally of values for testing
                alert('$scope.grossRevenueNonProfitData.isGrossRevenueNonProfitValid' + ': ' + $scope.grossRevenueNonProfitData.isGrossRevenueNonProfitValid
                + '\r\n' +
                '$scope.isGrossRevenueNonProfit' + ': ' + $scope.IsGrossRevenueNonProfit
                + '\r\n' +
                '$scope.grossRevenueNonProfitData.isGrossRevenueNonProfit' + ': ' + $scope.grossRevenueNonProfitData.IsGrossRevenueNonProfit);
            };
        }
    }
});
wacorpApp.directive('commercialfundraiserBond', function ($filter) {
    return {
        templateUrl: 'ng-app/directives/CFT/CommercialFundraiserBond/_CommercialFundraiserBond.html',
        restrict: 'A',
        scope: {
            bondData: '=?bondData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.file = {};
            $scope.file.FileLocation = "CharitiesUploadDocuments\\FundraiserUploadDocuments\\CommercialFundraiserBond.pdf";
            $scope.file.FileName = "CommercialFundraiserBond.pdf";
            $scope.file.TempFileName = "CommercialFundraiserBond.pdf";
            $scope.file.TempFileLocation = "CharitiesUploadDocuments\\FundraiserUploadDocuments\\CommercialFundraiserBond.pdf";
        },
    };
});

wacorpApp.directive('commercialfein', function ($filter, $timeout) {
    return {
        templateUrl: 'ng-app/directives/CFT/CommercialFundraiserFEIN/_CommercialFEIN.html',
        restrict: 'A',
        scope: {
            commercialFeinData: '=?commercialFeinData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.usaCode = usaCode;
            $scope.washingtonCode = washingtonCode;
            $scope.isOptional = true;
            $scope.isCorporation = true;
            $scope.isOther = true;
            $scope.FederalTaxTypes = [];
            $scope.Countries = [];
            $scope.States = [];
            $scope.ShowIRSLetter = false;
            $scope.OrganizationNames = [];
            //$scope.commercialFeinData.IsShowFederalTax = false;
            $scope.washingtonIntegerCode = washingtonIntegerCode;
            //$scope.charityOrganization = {};
            //$scope.charityOrganization.AKANamesList = $scope.charityOrganization.AKANamesList || [];
            //$scope.commercialFeinData.IsFederalTax = false;

            var feinScope = {
                FEINNumber: constant.ZERO, UBINumber: constant.ZERO, IsEntityRegisteredInWA: false, IsUBIOrganizationaStructure: true, isShowAka: false,
                JurisdictionCountry: codes.USA, JurisdictionState: codes.WA, UBIOtherDescp: '', JurisdictionCountryDesc: null, JurisdictionStateDesc: null, UploadOverrideList: [],
                JurisdictionDesc: null, Jurisdiction: null, IsFEINNumberExistsorNot: false, IsUBINumberExistsorNot: false, IsShowFederalTax: false, IsOrgNameExists: false, IsFundraiserOverrideMandetoryReq: false, IsActiveFilingExist:false
            };

            $scope.commercialFeinData = $scope.commercialFeinData ? angular.extend(feinScope, $scope.commercialFeinData) : angular.copy(feinScope);

            $scope.selectedJurisdiction = function (items, selectedVal) {
                var result = "";
                angular.forEach(items, function (item) {
                    if (selectedVal == item.Key) {
                        result = item.Value;
                    }
                });
                return result;
            }
            var ubiCnt = 1;
            $scope.$watch('commercialFeinData', function () {
                $scope.commercialFeinData.FEINNumber = $scope.commercialFeinData.FEINNumber == 0 ? '' : $scope.commercialFeinData.FEINNumber;
                $scope.commercialFeinData.UBINumber = $scope.commercialFeinData.UBINumber == 0 ? '' : $scope.commercialFeinData.UBINumber;
                $scope.commercialFeinData.IsEntityRegisteredInWA = angular.isNullorEmpty($scope.commercialFeinData.IsEntityRegisteredInWA) ? false : $scope.commercialFeinData.IsEntityRegisteredInWA;
                $scope.commercialFeinData.IsUBIOrganizationaStructure = angular.isNullorEmpty($scope.commercialFeinData.IsUBIOrganizationaStructure) ? true : $scope.commercialFeinData.IsUBIOrganizationaStructure;
                $scope.commercialFeinData.JurisdictionCountry = $scope.commercialFeinData.JurisdictionCountry == 0 ? '' : $scope.commercialFeinData.JurisdictionCountry;
                $scope.commercialFeinData.JurisdictionState = $scope.commercialFeinData.JurisdictionState == 0 ? $scope.washingtonCode : $scope.commercialFeinData.JurisdictionState;
                $scope.commercialFeinData.isShowAka = angular.isNullorEmpty($scope.commercialFeinData.isShowAka) ? false : $scope.commercialFeinData.isShowAka;
                $scope.commercialFeinData.IsActiveFilingExist = angular.isNullorEmpty($scope.commercialFeinData.IsActiveFilingExist) ? false : $scope.commercialFeinData.IsActiveFilingExist;
                if (ubiCnt == 1 && typeof ($scope.commercialFeinData.UBINumber) != typeof (undefined) && $scope.commercialFeinData.UBINumber != null && $scope.commercialFeinData.UBINumber != '') {
                    $scope.getOrganizationNameByUBI($scope.commercialFeinData.UBINumber);
                    ubiCnt++;
                }
                //$scope.commercialFeinData.IsFundraiserOverrideMandetoryReq = $scope.commercialFeinData.UploadOverrideList == undefined ? false : ($scope.commercialFeinData.UploadOverrideList != null && $scope.commercialFeinData.UploadOverrideList.length > 0 ? true : false);

                //if ($scope.commercialFeinData.JurisdictionCountry != $scope.usaCode) {
                //    $scope.commercialFeinData.JurisdictionState = '';
                //}
                var cnt = 1;
                if (typeof ($scope.commercialFeinData.AKANamesList) != typeof (undefined) && $scope.commercialFeinData.AKANamesList != null) {
                    if ($scope.commercialFeinData.AKANamesList.length > 0) {
                        angular.forEach($scope.commercialFeinData.AKANamesList, function (akaInfo) {
                            if (akaInfo.Status != "D") {
                                cnt = 0;
                            }
                        });
                        if (cnt == 0) {
                            $scope.commercialFeinData.isShowAka = true;
                        }
                        else {
                            $scope.commercialFeinData.isShowAka = false;
                        }
                    }
                }

                angular.forEach($scope.FederalTaxTypes, function (tax) {
                    if (tax.Key == $scope.commercialFeinData.FederalTaxExemptId)
                        $scope.commercialFeinData.FederalTaxExemptText = tax.Value;
                    $scope.commercialFeinData.IsFTDocumentAttached = true;
                });

                angular.forEach($scope.Countries, function (country) {
                    if (country.Key == $scope.commercialFeinData.JurisdictionCountry)
                        $scope.commercialFeinData.JurisdictionCountryDesc = country.Value;
                });
                angular.forEach($scope.States, function (state) {
                    if (state.Key == $scope.commercialFeinData.JurisdictionState)
                        $scope.commercialFeinData.JurisdictionStateDesc = state.Value;
                });

                //$scope.FederalChange();
            }, true);

            //$scope.CountryChangeDesc = function () {
            //    $scope.commercialFeinData.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.Countries, $scope.commercialFeinData.JurisdictionCountry);
            //};
            //Get Federal Tax Types List
            $scope.getFederalTaxTypes = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.FederalTaxTypes(function (response) { $scope.FederalTaxTypes = response.data; });
            };
            $scope.getFederalTaxTypes(); // getFederalTaxTypes method is available in this file only.

            var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
                $scope.Countries = response.data;
            }, function (response) {
            });

            var lookupStatesParams = { params: { name: 'CFTStates' } };
            // GetLookUpData method is available in constants.js
            wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
                $scope.States = response.data;
            }, function (response) {
            });


            $scope.organizationStructure = function (value) {
                if (value) {
                    $scope.commercialFeinData.IsUBIOrganizationaStructure = true;
                }
                else {
                    $scope.commercialFeinData.IsUBIOrganizationaStructure = false;
                }

            }
            //Get Business Details by UBI Number
            $scope.getBusinessDetails = function () {
                var ubidata = { params: { ubiNumber: $scope.commercialFeinData.UBINumber, cftType: $scope.commercialFeinData.CFTType } }
                if (ubidata.ubiNumber != '' && ubidata.ubiNumber != null) {
                    // IsUBINumberExists method is available in constants.js
                    wacorpService.get(webservices.CFT.IsUBINumberExists, ubidata, function (response) {
                        if (response.data == 'true') {
                            // Folder Name: app Folder
                            // Alert Name: isUBIExistorNot method is available in alertMessages.js
                            wacorpService.alertDialog(messages.Fein.isUBIExistorNot);
                            $scope.commercialFeinData.IsUBINumberExistsorNot = false;
                            $scope.commercialFeinData.UBINumber = null;
                        }
                        else {
                            $scope.commercialFeinData.IsUBINumberExistsorNot = true;
                            var data = {
                                params: { UBINumber: $scope.commercialFeinData.UBINumber }
                            }
                            // getBusinessDetailsByUBINumber method is available in constants.js
                            wacorpService.get(webservices.CFT.getBusinessDetailsByUBINumber, data, function (response) {

                                if (response.data.EntityName != null) {
                                    $scope.commercialFeinData.EntityName = response.data.EntityName;
                                    $scope.commercialFeinData.IsOrganizationalStructureType = response.data.BusinessType;
                                    $scope.commercialFeinData.OrganizationStructureJurisdictionCountryId = response.data.OrganizationStructureJurisdictionCountryId == null ? "" : response.data.OrganizationStructureJurisdictionCountryId.toString();
                                    $scope.commercialFeinData.OrganizationalStructureStateJurisdictionId = response.data.OrganizationalStructureStateJurisdictionId == null ? "" : response.data.OrganizationalStructureStateJurisdictionId.toString();
                                    $scope.commercialFeinData.OSJurisdictionId = response.data.OrganizationalStructureJurisdictionId == 0 ? "" : response.data.OrganizationalStructureJurisdictionId.toString();
                                    $scope.commercialFeinData.IsOSNonProfitCorporation = (response.data.BusinessType == "C") ? true : false;
                                    $scope.commercialFeinData.CFTOfficersList = response.data.CFTOfficersList;
                                    $scope.commercialFeinData.isHavingEntityOnUBISearch = angular.isNullorEmpty($scope.commercialFeinData.EntityName) ? false : true;

                                    angular.forEach($scope.Countries, function (country) {
                                        if (country.Key == $scope.commercialFeinData.OrganizationStructureJurisdictionCountryId)
                                            $scope.commercialFeinData.OrganizationStructureJurisdictionCountryDesc = country.Value;
                                    });

                                    angular.forEach($scope.States, function (state) {
                                        if (state.Key == $scope.commercialFeinData.OrganizationalStructureStateJurisdictionId)
                                            $scope.commercialFeinData.OrganizationalStructureStateJurisdictionDesc = state.Value;
                                    });
                                } else {
                                    wacorpService.alertDialog(messages.noDataFound);
                                    $scope.commercialFeinData.UBINumber = null;
                                }

                            }, function (response) { });
                        }
                    }, function (response) { });
                }

            };

            $scope.getOrganizationNameByUBI = function (value) {
                $scope.commercialFeinData.IsOrgNameExists = false;
                //$scope.commercialFeinData.isBusinessNameChanged = false;
                if($scope.commercialFeinData.EntityName != "" && $scope.commercialFeinData.EntityName!=undefined)
                {
                    if ($scope.commercialFeinData.FeinUbiCount == 0)
                         $scope.commercialFeinData.UBIOldName = $scope.commercialFeinData.EntityName;
                }
                
                if (value != "" && value != null && value.length == 9) {
                    var ubidata = { params: { UBINumber: $scope.commercialFeinData.UBINumber.replace(" ", "").replace(" ", "") } }
                    // getOrganizationNameByUBI method is available in constants.js
                    wacorpService.get(webservices.CFT.getOrganizationNameByUBI, ubidata, function (response) {
                        if (response.data.replace(/(^"|"$)/g, '') != "") {
                            $scope.commercialFeinData.EntityName = response.data.replace(/(^"|"$)/g, '');
                            $scope.commercialFeinData.IsOrgNameExists = true;
                            $scope.commercialFeinData.IsUbiAssociated = false;
                            $scope.commercialFeinData.businessNames = 0;
                            if ($scope.commercialFeinData.UBIOldName != null && $scope.commercialFeinData.UBIOldName!=undefined)
                                 $scope.commercialFeinData.FeinUbiCount++;
                        }
                        else {
                            //$scope.commercialFeinData.EntityName = "";
                            $scope.commercialFeinData.EntityName=$scope.commercialFeinData.UBIOldName;
                            $scope.commercialFeinData.IsOrgNameExists = false;
                            $scope.commercialFeinData.IsUbiAssociated = true;
                        }
                    });
                }

            };

            $scope.getOrganizationNameByFEIN = function (value, type) {
                //$scope.commercialFeinData.IsOrgNameExists = false;
                //$scope.commercialFeinData.isBusinessNameChanged = false;
                if (value != "" && value != null) {
                    var feindata = { params: { FEINNumber: value.replace("-", ""), cftType: type } }
                    // getOrganizationNameByFEIN method is available in constants.js
                    wacorpService.get(webservices.CFT.getOrganizationNameByFEIN, feindata, function (response) {
                        if (response.data != "") {
                            $scope.OrganizationNames = response.data;
                            if ($scope.OrganizationNames.length > 0)
                                $("#divOrganizationNamesList").modal('toggle');
                            if ($scope.commercialFeinData.FeinOldvalue == null || $scope.commercialFeinData.FeinOldvalue == "") {
                                $scope.commercialFeinData.FeinOldvalue = $scope.commercialFeinData.FEINNumber;
                            }
                        }
                        else {
                            $scope.OrganizationNames = [];
                            //$("#divOrganizationNamesList").modal('toggle');
                            //$scope.commercialFeinData.EntityName = "";
                            $scope.commercialFeinData.IsOrgNameExists = false;
                            $scope.commercialFeinData.IsShowFederalTax = false;
                        }
                    });
                }
            };

            //Deleting All Override Documents
            $scope.isOverride = function (flag, files) {
                if (!flag && files.length > constant.ZERO) {
                    var fileList = { files: files }
                    if ($scope.commercialFeinData.UploadOverrideList.length > 0) {
                        // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            //files[constant.ZERO].TempFileLocation = "";
                            for (var i = 0; i < $scope.commercialFeinData.UploadOverrideList.length; i = 0) {
                                //angular.forEach($scope.commercialFeinData.UploadOverrideList, function (value, data) {
                                if ($scope.commercialFeinData.UploadOverrideList[i].BusinessFilingDocumentId > 0) {
                                    $scope.commercialFeinData.UploadOverrideList[i].Status = principalStatus.DELETE;
                                }
                                else {
                                    //var index = $scope.commercialFeinData.UploadOverrideList.indexOf(value);
                                    $scope.commercialFeinData.UploadOverrideList.splice(i, 1);
                                }
                            }
                            $scope.commercialFeinData.IsFundraiserOverrideMandetoryReq = false;
                        }, function () {
                            $scope.commercialFeinData.IsFundraiserOverrideMandetoryReq = true;
                        });
                    }
                    else {
                        $scope.commercialFeinData.IsFundraiserOverrideMandetoryReq = false;
                    }
                }
            };

            $scope.clearUBI = function () {
                //$scope.commercialFeinData.EntityName = "";
                if ($scope.commercialFeinData.FeinUbiCount >=0)  
                    $scope.commercialFeinData.EntityName = $scope.commercialFeinData.UBIOldName;

                $scope.commercialFeinData.IsOrgNameExists = false;
                $scope.commercialFeinData.isHavingEntityOnUBISearch = false;
                $scope.commercialFeinData.UBINumber = '';
                 
                
            };
            //Is FEIN Number exists or not checking
            $scope.IsFEINNumberExists = function () {
                var data = { params: { feinNumber: $scope.commercialFeinData.FEINNumber } }
                if (data.FEINNumber != '' && data.FEINNumber != null) {
                    // IsFEINNumberExists method is available in constants.js
                    wacorpService.get(webservices.CFT.IsFEINNumberExists, data, function (response) {
                        if (response.data == 'true') {
                            wacorpService.alertDialog(messages.Fein.isFEINExistorNot);
                            $scope.commercialFeinData.IsFEINNumberExistsorNot = false;
                            $scope.commercialFeinData.FEINNumber = null;
                        }
                        else {
                            $scope.commercialFeinData.IsFEINNumberExistsorNot = true;
                        }
                    }, function (response) {
                    });
                }
            };

            $scope.onSelectOrganization = function (org) {
                $scope.SelectedOrganization = undefined;
                $scope.SelectedOrganization = org;
            }

            $scope.selectOrganization = function () {
                if ($scope.SelectedOrganization != null && $scope.SelectedOrganization != undefined) {
                    $scope.commercialFeinData.EntityName = $scope.SelectedOrganization.EntityName.replace(/(^"|"$)/g, '');
                    $scope.commercialFeinData.IsOrgNameExists = true;
                    $scope.commercialFeinData.businessNames = 0;
                    if ($scope.commercialFeinData.FEINNumber != $scope.commercialFeinData.FeinOldvalue) {
                        $scope.commercialFeinData.IsShowFederalTax = true;
                    }
                    $("#divOrganizationNamesList").modal('toggle');
                }
            }

            $scope.cancel = function () {
                $("#divOrganizationNamesList").modal('toggle');
            }
            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.commercialFeinData.UBINumber = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.commercialFeinData.UBINumber = pastedText;
                    });
                }
            };

            $scope.setUBILength = function (e) {
                //if (e.currentTarget.value.length >= 9) {
                //    e.preventDefault();
                //}
                if (e.currentTarget.value != undefined && e.currentTarget.value != "" && e.currentTarget.value!=null && e.currentTarget.value.length >= 9) {
                    // Allow: backspace, delete, tab, escape, enter and .
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                        // Allow: Ctrl+A, Command+A
                        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                        // Allow: home, end, left, right, down, up
                        (e.keyCode >= 35 && e.keyCode <= 40)) {
                        // let it happen, don't do anything
                        return;
                    }
                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                    }
                    e.preventDefault();
                }
            };

            var oldvalue1 = '';
            $scope.$watch('commercialFeinData.FederalTaxExemptId', function (newValue, oldValue) {
                if (newValue != oldValue) {
                    oldvalue1 = oldValue;
                }
            });

            $scope.FederalChange = function (id, files) {
                if (id > 0) {
                    var cartlist = $filter('filter')($scope.FederalTaxTypes, { Key: id });
                    if (cartlist[0].Value === "Church/Church affiliated" || cartlist[0].Value === "Government entity" || cartlist[0].Value === "Annual gross receipts normally $5,000 or less") {
                        $scope.commercialFeinData.IsShowFederalTax = false;
                        $scope.commercialFeinData.FederalTaxExemptText = cartlist[0].Value;
                    }
                    else {
                        $scope.commercialFeinData.IsShowFederalTax = true;
                    }
                    if (!$scope.commercialFeinData.IsShowFederalTax) {
                        switch ($scope.commercialFeinData.FederalTaxExemptText) {
                            case 'Church/Church affiliated':
                                if ($scope.commercialFeinData.FederaltaxUpload != undefined && $scope.commercialFeinData.FederaltaxUpload.length > 0) {
                                    // // Folder Name: app Folder
                                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                                        // deleteAllUploadedFiles method is available in constants.js
                                        wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                            $scope.commercialFeinData.FederaltaxUpload = [];
                                        })

                                    },
                                    function () {
                                        $scope.commercialFeinData.FederalTaxExemptId = oldvalue1;
                                        $scope.commercialFeinData.IsShowFederalTax = true;
                                    }
                                    );
                                }
                                break;
                            case 'Government entity':
                                if ($scope.commercialFeinData.FederaltaxUpload != undefined && $scope.commercialFeinData.FederaltaxUpload.length > 0) {
                                    // Folder Name: app Folder
                                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                                        // deleteAllUploadedFiles method is available in constants.js
                                        wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                            $scope.commercialFeinData.FederaltaxUpload = [];
                                        })

                                    },
                                    function () {
                                        $scope.commercialFeinData.FederalTaxExemptId = oldvalue1;
                                        $scope.commercialFeinData.IsShowFederalTax = true;
                                    }
                                    );
                                }

                                break;
                            case 'Annual gross receipts normally $5,000 or less':
                                if ($scope.commercialFeinData.FederaltaxUpload != undefined && $scope.commercialFeinData.FederaltaxUpload.length > 0) {
                                    // Folder Name: app Folder
                                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                                        // deleteAllUploadedFiles method is available in constants.js
                                        wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                            $scope.commercialFeinData.FederaltaxUpload = [];
                                        })

                                    },
                                    function () {
                                        $scope.commercialFeinData.FederalTaxExemptId = oldvalue1;
                                        $scope.commercialFeinData.IsShowFederalTax = true;
                                    });
                                }
                                break;
                        }
                    }
                }
                else if ($scope.commercialFeinData.FederalTaxExemptText != "Church/Church affiliated" || $scope.commercialFeinData.FederalTaxExemptText != "Government entity" || $scope.commercialFeinData.FederalTaxExemptText != "Annual gross receipts normally $5,000 or less") {
                    $scope.commercialFeinData.IsShowFederalTax = false;
                    if ($scope.commercialFeinData.FederaltaxUpload != undefined && $scope.commercialFeinData.FederaltaxUpload.length > 0) {
                        // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            // deleteAllUploadedFiles method is available in constants.js
                            wacorpService.post(webservices.CFT.deleteAllUploadedFiles, files, function () {
                                $scope.commercialFeinData.FederaltaxUpload = [];
                            })

                        });
                    }
                    else {
                        $scope.commercialFeinData.FederaltaxUpload = [];
                    }
                }
                else {
                    $scope.commercialFeinData.IsShowFederalTax = true;
                }

            }

            $scope.FederalNo = function () {
                $scope.commercialFeinData.FederalTaxExemptId = '';
            }

        },
    };
});

wacorpApp.directive('fundriaserSuretyBond', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserSuretyBond/_FundriaserSuretyBond.html',
        restrict: 'A',
        scope: {
            fundraiserBondInfo: '=?fundriaserBondInfoData',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.isReview = $scope.isReview || false;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            var suretyBondScope = {
                IsBondWaiverSubmittedProofOfSurety: false, BondWaiversSOSBondUploadList: [], BondWaiversBondExpirationDate: null, IsBondWaiver: false, BondWaiversUploadedSuretyBondsList: [],
            };
            
            $scope.fundraiserBondInfo = $scope.fundraiserBondInfo ? angular.extend(suretyBondScope, $scope.fundraiserBondInfo) : angular.copy(suretyBondScope);

            //$scope.$watch('fundraiserBondInfo', function () {
            //    $scope.fundraiserBondInfo.IsBondWaiver = $scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList == undefined ? false : ($scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList != null && $scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList.length > 0 ? true : false);
            //    $scope.fundraiserBondInfo.IsBondWaiverSubmittedProofOfSurety = $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList == undefined ? false : ($scope.fundraiserBondInfo.BondWaiversSOSBondUploadList != null && $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.length > 0 ? true : false);
            //});

            $scope.deleteAllSOSFiles = function (flag, files) {
                if (flag && files.length > constant.ZERO) {
                    //files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    if ($scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.length > 0)
                    {
                        // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js 
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            angular.forEach($scope.fundraiserBondInfo.BondWaiversSOSBondUploadList, function (value, data) {
                                if (value.BusinessFilingDocumentId > 0) {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.indexOf(value);
                                    $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.splice(index, 1);
                                }
                            });
                            //for (var i = 0; i < $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.length;i++){
                            ////angular.forEach($scope.fundraiserBondInfo.BondWaiversSOSBondUploadList, function (value, data) {
                            //    if ($scope.fundraiserBondInfo.BondWaiversSOSBondUploadList[i].BusinessFilingDocumentId > 0) {
                            //        $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList[i].Status = principalStatus.DELETE;
                            //    }
                            //    else {
                            //        //var index = $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.indexOf(value);
                            //        //$scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.splice(i, 1);
                            //    }
                            //}
                            //for (var i = 0; i < $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.length; i = 0) {
                            //    //angular.forEach($scope.fundraiserBondInfo.BondWaiversSOSBondUploadList, function (value, data) {
                            //    if ($scope.fundraiserBondInfo.BondWaiversSOSBondUploadList[i].BusinessFilingDocumentId > 0) {
                            //        //$scope.fundraiserBondInfo.BondWaiversSOSBondUploadList[i].Status = principalStatus.DELETE;
                            //    }
                            //    else {
                            //        //var index = $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.indexOf(value);
                            //        $scope.fundraiserBondInfo.BondWaiversSOSBondUploadList.splice(i, 1);
                            //    }
                            //}
                            $scope.fundraiserBondInfo.IsBondWaiverSubmittedProofOfSurety = true;
                        },
                        function () {
                            $scope.fundraiserBondInfo.IsBondWaiverSubmittedProofOfSurety = false;
                        });
                    }
                    else {
                        $scope.fundraiserBondInfo.IsBondWaiverSubmittedProofOfSurety = false;
                    }
                }
            };

            //Deleting All Bond Waivers Documents
            $scope.isBondWaiver = function (flag, files) {
                if (!flag && files.length > constant.ZERO) {
                    var fileList = { files: files }
                    if ($scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList.length > 0) {
                        // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js 
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            //files[constant.ZERO].TempFileLocation = "";
                            for (var i = 0; i < $scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList.length;i=0){
                                //angular.forEach($scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList, function (value, data) {
                                if ($scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList[i].BusinessFilingDocumentId > 0) {
                                    $scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList[i].Status = principalStatus.DELETE;
                                }
                                else {
                                    //var index = $scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList.indexOf(value);
                                    $scope.fundraiserBondInfo.BondWaiversUploadedSuretyBondsList.splice(i, 1);
                                }
                            }
                            $scope.fundraiserBondInfo.IsBondWaiver = false;
                        }, function () {
                            $scope.fundraiserBondInfo.IsBondWaiver = true;
                        });
                    }
                    else {
                        $scope.fundraiserBondInfo.IsBondWaiver = false;
                    }
                }
            };
        },
    };
});
wacorpApp.directive('fundraiserCftOfficers', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserCFTOfficers/_FundraiserCFTOfficers.html',
        restrict: 'A',
        scope: {
            cftOfficersList: '=?cftOfficersList',
            showErrorMessage: '=?showErrorMessage',
            mainModel: '=?mainModel',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope, $location, $timeout) {
            $scope.messages = messages;
            $scope.cftOfficersList = $scope.cftOfficersList || [];
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add New Officer";
            $scope.ValidateErrorMessage = false;
            $scope.IsIamOfficer = false;
            $scope.cftOfficer = {
                OfficerID: "", FirstName: null, LastName: null, Title: null, FullName: null, SequenceNo: "", PhoneNumber: "", EmailAddress: "", TypeID: "", OfficerBaseType: "", IsCFTOfficer: false, Status: null,
                OfficerAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, Status: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO, OfficerStatus: principalStatus.INSERT,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null, IsSameAsAddressContactInfo: false
            };

            var cftOfficersScopeData = {
                OfficerID: "", FirstName: null, LastName: null, Title: null, FullName: null, SequenceNo: "", PhoneNumber: "", EmailAddress: "", TypeID: "", OfficerBaseType: "", IsCFTOfficer: false, Status: null,
                OfficerAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, Status: principalStatus.INSERT, FilerID: constant.ZERO, UserID: constant.ZERO, OfficerStatus: principalStatus.INSERT,
                CreatedBy: constant.ZERO, CreatedIPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null, IsSameAsAddressContactInfo: false
            };

            //Reset the fundraiser charitable organization
            $scope.resetCFTOfficer = function () {
                $scope.cftOfficer = angular.copy(cftOfficersScopeData);
                $scope.ValidateErrorMessage = false;
                $scope.addbuttonName = "Add New Officer";
                //$scope.IsIamOfficer = false;
                $("#loginOfficer").prop("checked", false);
            };

            //Add fundraiser charitable organization data
            $scope.AddCFTOfficer = function (cftOfficersForm) {
                $scope.ValidateErrorMessage = true;

                $scope.cftOfficer.OfficerAddress.StreetAddress1 = (($scope.cftOfficer.OfficerAddress.StreetAddress1 != null && $scope.cftOfficer.OfficerAddress.StreetAddress1.trim() == "" || $scope.cftOfficer.OfficerAddress.StreetAddress1 == undefined) ? $scope.cftOfficer.OfficerAddress.StreetAddress1 = null : $scope.cftOfficer.OfficerAddress.StreetAddress1.trim());
                if (!$scope.cftOfficer.OfficerAddress.StreetAddress1) {
                    $scope.fundraiserCftOfficersForm.CFTAddress.StreetAddress1.$setValidity("text", false);
                }
                else {
                    $scope.fundraiserCftOfficersForm.CFTAddress.StreetAddress1.$setValidity("text", true);
                }

                if ($scope[cftOfficersForm].$valid) {
                    $scope.ValidateErrorMessage = false;
                    $scope.addbuttonName = "Add New Officer";
                    if ($scope.cftOfficer.SequenceNo != 0) {
                        angular.forEach($scope.cftOfficersList, function (officer) {
                            if (officer.SequenceNo == $scope.cftOfficer.SequenceNo) {
                                //officer.OfficerStatus = principalStatus.UPDATE;
                                angular.copy($scope.cftOfficer, officer);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.cftOfficersList, function (officer) {
                            if (maxId == constant.ZERO || officer.SequenceNo > maxId)
                                maxId = officer.SequenceNo;
                        });
                        $scope.cftOfficer.SequenceNo = ++maxId;
                        $scope.cftOfficer.OfficerStatus = principalStatus.INSERT;
                        $scope.cftOfficer.IsCFTOfficer = true;
                        $scope.cftOfficersList.push($scope.cftOfficer);
                    }
                    $scope.resetCFTOfficer(); // resetCFTOfficer method is available in this file only
                }
            };

            //Edit fundraiser charitable organization data
            $scope.editCFTOfficer = function (cftOfficersData) {
                cftOfficersData.OfficerAddress.Country = cftOfficersData.OfficerAddress.Country || codes.USA;
                cftOfficersData.OfficerAddress.State = cftOfficersData.OfficerAddress.State || codes.USA;
                cftOfficersData.IsSameAsAddressContactInfo = false;
                $scope.cftOfficer = angular.copy(cftOfficersData);
                $scope.cftOfficer.OfficerStatus = principalStatus.UPDATE;
                $scope.addbuttonName = "Update Officer";
            };

            //Delete fundraiser charitable organization data
            $scope.deleteCFTOfficer = function (cftOfficersData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (cftOfficersData.OfficerID <= 0 || cftOfficersData.OfficerID == "") {
                        var index = $scope.cftOfficersList.indexOf(cftOfficersData);
                        $scope.cftOfficersList.splice(index, 1);
                    }
                    else
                        cftOfficersData.OfficerStatus = principalStatus.DELETE;
                    $scope.resetCFTOfficer(); // resetCFTOfficer method is available in this file only
                });
            };

            // Clear all controls data
            $scope.clearCFTOfficer = function () {
                $scope.resetCFTOfficer(); // resetCFTOfficer method is available in this file only
            };

            //Get User Login details during MySelf Select
            $scope.getUserLoginDetails = function (IsIamOfficerVal) {
                if (IsIamOfficerVal) {
                    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                        $scope.newUser = response.data;
                        $scope.cftOfficer.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.cftOfficer.LastName = angular.copy($scope.newUser.LastName);
                        $scope.cftOfficer.Title = angular.copy($scope.newUser.Title);
                        $scope.cftOfficer.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.cftOfficer.ConfirmEmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.cftOfficer.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        var addressId = $scope.cftOfficer.OfficerAddress.ID;
                        $scope.cftOfficer.OfficerAddress = angular.copy($scope.newUser.Address);
                        $scope.cftOfficer.OfficerAddress.ID = addressId;
                        $scope.cftOfficer.IsCFTOfficer = false;
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    });
                }
                else {
                    var seqNo = $scope.cftOfficer.SequenceNo;
                    var officerId = $scope.cftOfficer.OfficerID;
                    var addressId = $scope.cftOfficer.OfficerAddress.ID;
                    var status = $scope.cftOfficer.OfficerStatus;
                    $scope.cftOfficer = angular.copy(cftOfficersScopeData);
                    $scope.cftOfficer.OfficerAddress.ID = addressId;
                    $scope.cftOfficer.SequenceNo = seqNo;
                    $scope.cftOfficer.OfficerID = officerId;
                    $scope.cftOfficer.OfficerStatus = status;
                }
            };

            $scope.amendmentLink = function () {
                window.open('#/BusinessAmendmentIndex', '_blank');
                //$location.path('/BusinessAmendmentIndex');
            };

            $scope.copyFromContactInformation = function () {
                if ($scope.cftOfficer.IsSameAsAddressContactInfo) {
                    var addressId = $scope.cftOfficer.OfficerAddress.ID;
                    $scope.cftOfficer.OfficerAddress = angular.copy($scope.mainModel.EntityMailingAddress);
                    $scope.cftOfficer.OfficerAddress.ID = addressId;
                    $scope.cftOfficer.PhoneNumber = $scope.mainModel.EntityPhoneNumber;
                }
                else {
                    var addressId = $scope.cftOfficer.OfficerAddress.ID;
                    $scope.cftOfficer.OfficerAddress = angular.copy(cftOfficersScopeData.OfficerAddress);
                    $scope.cftOfficer.OfficerAddress.ID = addressId;
                    $scope.cftOfficer.PhoneNumber = "";
                }
            }

            $scope.changedAddress = function () {
                if ($scope.cftOfficer.IsSameAsAddressContactInfo) {
                    $scope.cftOfficer.IsSameAsAddressContactInfo = false;
                }
            };

            var changedMailingAddress = $scope.$on("onMailingAddressChanged", function () {
                $scope.changedAddress();
            });

            $scope.$on('$destroy', function () {
                changedMailingAddress();
            });

        },
    };
});

wacorpApp.directive('fundraiserLegalActions', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserLegalActions/_FundraiserLegalActions.html',
        restrict: 'A',
        scope: {
            legalInfoEntity: '=?legalInfoEntity',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope, $location) {
            $scope.messages = messages;
         //   $scope.legalInfoEntityList = $scope.legalInfoEntityList || [];
            $scope.isReview = $scope.isReview || false;
            $scope.addbuttonName = "Add Legal Information";
            $scope.hasValues = false;
            $scope.LegalCount = false;
            $scope.LegalUploadCount = false;
            $scope.legalInfo = {
                IsAnyLegalActions: false, isUploadDocument: false,SequenceNo:null,
                Court: '', Case: '', TitleofLegalAction: '', LegalActionDate: null, UploadSurityBondList: [], LegalInfoEntityList: []
            };
           
            $scope.hasValues = $scope.legalInfo.Court != '' || $scope.legalInfo.Case != '' ||
                               $scope.legalInfo.TitleofLegalAction != '' || $scope.legalInfo.legalActionData != null;

            var legalInfoScopeData = {
                IsAnyLegalActions: false, isUploadDocument: false,
                Court: '', Case: '', TitleofLegalAction: '', LegalActionDate: null, UploadSurityBondList: [], LegalInfoEntityList: []
            };

            $scope.legalInfoEntity = $scope.legalInfoEntity ? angular.extend(legalInfoScopeData, $scope.legalInfoEntity) : angular.copy(legalInfoScopeData);


            $scope.$watch('legalInfo', function () {
                $scope.legalInfo.isUploadDocument = $scope.legalInfo.UploadSurityBondList.length > 0 ? true : false;
            });

            //Reset the legal action
            $scope.resetLegalAction = function () {
                $scope.legalInfo = angular.copy(legalInfoScopeData);
               // $scope.ValidateErrorMessage = false;
                $scope.addbuttonName = "Add Legal Information";
            };

            //Add Legal Action data
            $scope.AddLeglAction = function (legalActionsForm) {
                $scope.ValidateErrorMessage = true;
                if ($scope[legalActionsForm].$valid) {
                    $scope.ValidateErrorMessage = false;
                    if ($scope.legalInfo.SequenceNo!=null && $scope.legalInfo.SequenceNo!=''&& $scope.legalInfo.SequenceNo != 0) {
                        angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (legalInfoItem) {
                            if (legalInfoItem.SequenceNo == $scope.legalInfo.SequenceNo) {
                                angular.copy($scope.legalInfo, legalInfoItem);
                                ////////////////Cross check.
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (legalInfoItem) {
                            if (maxId == constant.ZERO || legalInfoItem.SequenceNo > maxId)
                                maxId = legalInfoItem.SequenceNo;
                        });
                        $scope.legalInfo.SequenceNo = ++maxId;
                        $scope.legalInfo.Status = principalStatus.INSERT;
                        $scope.legalInfoEntity.LegalInfoEntityList.push($scope.legalInfo);
                    }
                    $scope.resetLegalAction(); // resetLegalAction method is avialable in this file only
                }
                 
            };

            //Edit fundraiser charitable organization data
            $scope.editLegalAction = function (legalActionData) {
                $scope.legalInfo = angular.copy(legalActionData);
                $scope.legalInfo.LegalActionDate = $scope.legalInfo.LegalActionDate == "0001-01-01T00:00:00" ? null : wacorpService.dateFormatService($scope.legalInfo.LegalActionDate);
                $scope.legalInfo.Status = principalStatus.UPDATE;
                $scope.addbuttonName = "Update Legal Information";
            };

            //Delete fundraiser charitable organization data
            $scope.deleteLegalAction = function (legalActionData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (legalActionData.LegalInfoId <= 0 || legalActionData.LegalInfoId == "")
                    {
                        var index = $scope.legalInfoEntity.LegalInfoEntityList.indexOf(legalActionData);
                        $scope.legalInfoEntity.LegalInfoEntityList.splice(index, 1);
                    }
                    else
                        legalActionData.Status = principalStatus.DELETE;
                    $scope.resetLegalAction();  // resetLegalAction method is avialable in this file only
                });
            };
            
            $scope.deleteAllFiles = function (flag, uploadfiles, legalInfo) {
                $scope.resetLegalAction();  // resetLegalAction method is avialable in this file only
                if (!flag && (uploadfiles.length > constant.ZERO || legalInfo.length > constant.ZERO)) {
                    var confirmMsg = '';
                    if (uploadfiles.length == constant.ZERO) {
                        confirmMsg = "All the records will be deleted. Do you want to continue?";
                    }
                    else {
                        confirmMsg = $scope.messages.UploadFiles.filesDeleteConfirm;
                    }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog(confirmMsg, function () {
                        //Removing Uploaded List
                        if ($scope.legalInfoEntity.UploadSurityBondList.length > 0)
                        {
                            //for(var i=0;i<$scope.legalInfoEntity.UploadSurityBondList.length;i=0){
                            angular.forEach($scope.legalInfoEntity.UploadSurityBondList, function (value, data) {
                                if (value.BusinessFilingDocumentId > 0)
                                {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.legalInfoEntity.UploadSurityBondList.indexOf(value);
                                    $scope.legalInfoEntity.UploadSurityBondList.splice(index, 1);
                                }
                            });
                        }
                        //Removing Legal Info List
                        if ($scope.legalInfoEntity.LegalInfoEntityList.length > 0) {
                            angular.forEach($scope.legalInfoEntity.LegalInfoEntityList, function (value, data) {
                                if (value.LegalInfoId > 0) {
                                    value.Status = principalStatus.DELETE;
                                }
                                else {
                                    var index = $scope.legalInfoEntity.LegalInfoEntityList.indexOf(value);
                                    $scope.legalInfoEntity.LegalInfoEntityList.splice(index, 1);
                                }

                            });
                        }
                    },
                    function () {
                        $scope.legalInfoEntity.LegalInfo.IsAnyLegalActions = true;
                    });
                }
            };

            $scope.amendmentLink = function () {
                $location.path('/BusinessAmendmentIndex');
            };

        },
    };
});

wacorpApp.directive('fundraiserCftCorrespondenceAddress', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserCorrespondingAddress/_FundraiserCorrespondenceAddress.html',
        restrict: 'A',
        scope: {
            cftCorrespondenceAddressEntity: '=?cftCorrespondenceAddressEntity',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            isCorrespAddress: '=?isCorrespAddress',
            isShowReturnAddress:'=?isShowReturnAddress'
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope, $location) {
            $scope.messages = messages;
            $scope.ValidateConfirmEmailAddress = function () {
                if (($scope.cftCorrespondenceAddressEntity.CorrespondenceConfrimEmailAddress).toUpperCase() != ($scope.cftCorrespondenceAddressEntity.CorrespondenceEmailAddress).toUpperCase()) {
                    // Folder Name: app Folder
                    // Alert Name: emailMatch method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.PrincipalOffice.emailMatch);
                    $('#txtFundemailFocus').focus();
                }
            }

        }
    };

    });
wacorpApp.directive('fundraiserCharitySearch', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserCharityClients/_fundraiserCharitySearch.html',
        restrict: 'A',
        scope: {
            charityClients: '=?charityClients',
            selectedEntity: '=?selectedEntity',
            isReview: '=?isReview',
        },
        controller: function ($scope, wacorpService, focus) {
            // declare scope variables
            $scope.page = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.messages = messages;
            $scope.charityClients = $scope.charityClients || "";
            $scope.charitySearchCriteria = { Type: searchTypes.RegistrationNumber, ID: "", IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, IsOnline: true, charityClients: $scope.charityClients, isSearchClick: false };
            $scope.selectedEntity = null;
            var criteria = null;
            $scope.search = loadCharityList;
            $scope.searchval = '';
            $scope.isButtonSerach = false;
            focus("entityNameSearchField");

            $scope.charity = {
                CFTID: constant.ZERO, FEINNumber: "", UBINumber: "", EntityName: "", IsNewCFTFundraiser: false, Status: '',RegistrationNumber:'',
                EntityMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }
            }

            // search cft list
            $scope.searchEntity = function (searchform) {
                $scope.isShowErrorFlag = true;
                if ($scope[searchform].$valid) {
                    $scope.charitySearchCriteria.isSearchClick = true;
                    $scope.isShowErrorFlag = false;
                    $scope.isButtonSerach = true
                    loadCharityList(constant.ZERO); // loadCharityList method is available in this file only
                }
            };
            //clear text on selecting radio button
            $scope.cleartext = function () {
                $scope.charitySearchCriteria.ID = null;
                $scope.charitySearchCriteria.OrgName = null;
            };

            // clear fields
            $scope.clearFun = function () {
                $scope.charitySearchCriteria.ID = "";
                $scope.charitySearchCriteria.OrgName = "";
                $scope.charitySearchCriteria.isSearchClick = false;
                $scope.charitySearchCriteria.Type = searchTypes.RegistrationNumber;
                $scope.isShowErrorFlag = false;
            };

            // get selected entity information
            $scope.getSelectedEntity = function (charityEntity) {
                $scope.selectedEntity = charityEntity;
                $scope.selectedEntityID = charityEntity.CFTId || $scope.charitySearchCriteria.OrgName;

            };

            // get charity list data from server
            function loadCharityList(page) {
                page = page || constant.ZERO;
                $scope.charitySearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                $scope.selectedEntity = null;
                var data = angular.copy($scope.charitySearchCriteria);
                $scope.isButtonSerach = page == 0;
                data.ID = angular.copy($scope.isButtonSerach ? $scope.charitySearchCriteria.ID || $scope.charitySearchCriteria.OrgName : $scope.searchval);
                if (criteria == null) {
                    criteria = {};
                    criteria.Type = $scope.charitySearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.SearchCriteria = "contains";
                    criteria.ID = constant.ONE;
                    criteria.PageCount = 10;
                    //criteria.TotalRowCount = $scope.totalCount;
                    criteria.PageID = $scope.charitySearchCriteria.PageID;
                }
                else {
                    criteria.Type = $scope.charitySearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.charitySearchCriteria.PageID;
                }
                //wacorpService.post(webservices.CFT.getCharitySearchDetails, data, function (response) {
                // getCharityCommonBasicSearchDetails method is available in constants.js
                wacorpService.post(webservices.CFT.getCharityCommonBasicSearchDetails, criteria, function (response) {
                    $scope.selectedEntity = null;
                    $scope.selectedCharitesList = response.data;
                    $scope.selectedEntityID = null;
                    if ($scope.isButtonSerach && response.data.length > 0) {
                        var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                        $scope.pagesCount = response.data.length < $scope.charitySearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                        $scope.totalCount = totalcount;
                        //$scope.searchval = angular.copy($scope.isButtonSerach ? $scope.charitySearchCriteria.ID : $scope.searchval);
                        $scope.searchval = criteria.SearchValue;
                        criteria = response.data[constant.ZERO].Criteria;
                        criteria.SearchCriteria = "contains";
                    }
                    $scope.page = page;
                    $scope.BusinessListProgressBar = false;
                    $("#divCharitiesList").modal('show');
                }, function (response) {
                    $scope.selectedEntity = null;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    searchResultsLoading(false);
                    $("#divCharitiesList").modal('hide');
                });
            }

            //Add Search Fundraiser
            $scope.addSearchCharity = function () {
                if ($scope.selectedEntity && $scope.selectedEntityID != constant.ZERO) {
                    var cObj = {
                        CFTID: constant.ZERO, FEINNumber: "", UBINumber: "", EntityName: "", IsNewCFTFundraiser: false, Status: '', RegistrationNumber: '',isCharityDeleted:false,
                        EntityMailingAddress: {
                            ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                                FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                                ModifiedIPAddress: null
                            }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                            Zip5: null, Zip4: null, PostalCode: null, County: null,
                        }
                    };
                    cObj.CFTID = $scope.selectedEntity.CFTId;
                    cObj.FEINNumber = $scope.selectedEntity.FEINNumber;
                    cObj.UBINumber = $scope.selectedEntity.UBINumber;
                    cObj.EntityName = $scope.selectedEntity.EntityName;
                    //StreetAddress1
                    //StreetAddress2
                    //City
                    //State
                    //OtherState
                    //Country
                    //Zip5
                    //Zip4
                    //PostalCode
                    //County
                    cObj.EntityMailingAddress = $scope.selectedEntity.EntityMailingAddress;
                    cObj.RegistrationNumber = $scope.selectedEntity.RegistrationNumber;
                    cObj.Status = principalStatus.INSERT;
                    $scope.charityClients.CharitiesList.push(cObj);
                    $("#divCharitiesList").modal('hide');
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: selectCharity method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.FundraiserSearch.selectCharity);
                }
            };

            //Delete charities data
            $scope.deleteCFTCharity = function (charityData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (charityData != null && charityData.Status == null) {
                        charityData.Status = principalStatus.UPDATE;
                        charityData.isCharityDeleted = true;
                    }
                    else if (charityData != null) {
                        var index = $scope.charityClients.CharitiesList.indexOf(charityData);
                        $scope.charityClients.CharitiesList.splice(index, 1);
                    }
                });
            };

            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.charitySearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.charitySearchCriteria.ID = pastedText;
                    });
                }
            };

            //copypaste Fein Number
            $scope.setPastedFeinNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.charitySearchCriteria.ID = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.charitySearchCriteria.ID = pastedText;
                    });
                }
            };

            $scope.$watch('selectedCharitesList', function () {
                if ($scope.selectedCharitesList == undefined)
                    return;
                if ($scope.selectedCharitesList.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);
        },
    }
});


wacorpApp.directive('commercialFundraisersSubContractors', function () {

    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserSubContractors/_CommercialFundraisersSubContractors.html',
        restrict: 'A',
        scope: {
            commercialFundraisersContractors: '=?commercialFundraisersContractors',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, $rootScope, $timeout) {
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.showFundraiserSearchValidation = false;
            $scope.showFRAddValidation = false;
            $scope.isReview = $scope.isReview || false;
            $scope.messages = messages;
            $scope.addHideFundraiser = "Add New Fundraiser";
            $scope.search = getFundraiserList;
            $scope.isButtonSerach = false;
            var criteria = null;

            //$scope.commercialFundraisersContractors.FundraisersList = $scope.commercialFundraisersContractors.FundraisersList || [];

            //$scope.commercialFundraisersContractors.IsCommercialFundraisersContributionsInWA = false;

            $scope.fundRaiser = {
                FundraiserCFTId: constant.ZERO, FundraiserSearchID: constant.ZERO, FundraiserFEINNumber: "", FundraiserUBINumber: "", FundraiserSearchName: "", isFundraiserAdded: false, FundraiserStatus: '',
                FundraiserSearchMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }
            }

            var fundRaiserScopeData = {
                FundraiserCFTId: constant.ZERO, FundraiserSearchID: constant.ZERO, FundraiserFEINNumber: "", FundraiserUBINumber: "", FundraiserSearchName: "", isFundraiserAdded: false, FundraiserStatus: '',
                FundraiserSearchMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }
            }

            var fundRaiserResetScope = {
                FundraiserCFTId: constant.ZERO, FundraiserSearchID: constant.ZERO, FundraiserFEINNumber: "", FundraiserUBINumber: "", EntityName: "", isFundraiserAdded: false, FundraiserStatus: '',
                FundraiserSearchMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }
            }
            $scope.fundraiserSearchCriteria = { FundraiserName: "", FundraiserID: "", FEINNo: "", FundraiserUBINumber: "", RegistrationNumber: "", Type: "", PageID: constant.ONE, PageCount: constant.TEN, ID: "" };
            $scope.fundraiserSearchCriteria.Type = "FundOrgName";
            $scope.AddFundraiser = function () {
                $scope.IsAddNewFundraiser = true;
                $("#divFundraisersList").modal('toggle');
            }

            //Search Fundraiser -- start
            $scope.searchFundraiser = function (searchform) {
                $scope.showFundraiserSearchValidation = true;
                if ($scope.fundraisersForm.searchform.$valid) {
                    $scope.showFundraiserSearchValidation = false;
                    $scope.selectedFundraiser = undefined;
                    $scope.isButtonSerach = false;
                    getFundraiserList(constant.ZERO); // getFundraiserList method is available in this file only
                    $("#divFundraisersList").modal('toggle');
                }
            };

            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.fundraiserSearchCriteria.UBINumber = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.fundraiserSearchCriteria.UBINumber = pastedText;
                    });
                }
            };

            $scope.$watch('fundraiserInfo', function () {
                if ($scope.fundraiserInfo == undefined)
                    return;
                if ($scope.fundraiserInfo.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);

            function getFundraiserList(page) {
                page = page || constant.ZERO;
                $scope.fundraiserSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                var data = angular.copy($scope.fundraiserSearchCriteria);
                $scope.isButtonSerach = page == 0;
                data.ID = angular.copy($scope.isButtonSerach ? ($scope.fundraiserSearchCriteria.RegistrationNumber || $scope.fundraiserSearchCriteria.FEINNo
                                                                || $scope.fundraiserSearchCriteria.UBINumber || $scope.fundraiserSearchCriteria.FundraiserName) : $scope.searchval);
                if (criteria == null) {
                    criteria = {};
                    criteria.SearchCriteria = $scope.fundraiserSearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.fundraiserSearchCriteria.PageID;
                    criteria.PageCount = 10;
                }
                else {
                    criteria.SearchCriteria = $scope.fundraiserSearchCriteria.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.fundraiserSearchCriteria.PageID;
                    criteria.PageCount = 10;
                }

                if (criteria.SearchCriteria == "FundRegNumber") {
                    criteria.RegistrationNumber = criteria.SearchValue;
                    criteria.FEINNo = null;
                    criteria.UBINumber = null;
                    criteria.EntityName = null;
                }
                else if (criteria.SearchCriteria == "FundFEINNo") {
                    criteria.FEINNo = criteria.SearchValue;
                    criteria.UBINumber = null;
                    criteria.RegistrationNumber = null;
                    criteria.EntityName = null;
                }
                else if (criteria.SearchCriteria == "FundUBINo") {
                    criteria.UBINumber = criteria.SearchValue;
                    criteria.FEINNo = null;
                    criteria.RegistrationNumber = null;
                    criteria.EntityName = null;
                } else {
                    criteria.EntityName = criteria.SearchValue;
                    criteria.FEINNo = null;
                    criteria.UBINumber = null;
                    criteria.RegistrationNumber = null;
                }
                // FundraiserSearchForCharities method is available in constants.js
                wacorpService.post(webservices.CFT.FundraiserSearchForCharities, criteria,
                    function (response) {
                        if (response.data != null) {
                            $scope.fundraiserInfo = angular.copy(response.data);
                            //$scope.clearSearch();
                            if ($scope.isButtonSerach && response.data.length > 0) {
                                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                                $scope.pagesCount = response.data.length < $scope.fundraiserSearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                                $scope.totalCount = totalcount;
                                $scope.searchval = criteria.SearchValue;
                                $scope.SearchCriteria = criteria.SearchCriteria;
                                criteria = response.data[constant.ZERO].Criteria;
                            }
                            $scope.page = page;

                        }
                        else
                            // Folder Name: app Folder
                            // Alert Name: noDataFound method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.noDataFound);
                        //$scope.clearSearch();
                    },
                    function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    }
                );
            }


            $scope.clearSearch = function () {
                $scope.fundraiserSearchCriteria.FundraiserName = "";
                $scope.fundraiserSearchCriteria.FEINNo = "";
                $scope.fundraiserSearchCriteria.UBINumber = "";
                $scope.fundraiserSearchCriteria.RegistrationNumber = "";
            }
            //On select fundraiser from fundraisers list
            $scope.onSelectFundraiser = function (selectFundraiser) {
                $scope.selectedFundraiser = undefined;
                $scope.selectedFundraiser = selectFundraiser;
            };

            //Add Search Fundraiser
            $scope.addSearchFundraiser = function () {
                if ($scope.selectedFundraiser && $scope.selectedFundraiser.FundraiserID != constant.ZERO) {
                    var maxId = constant.ZERO;
                    angular.forEach($scope.commercialFundraisersContractors.FundraisersList, function (fundraiser) {
                        if (maxId == constant.ZERO || fundraiser.FundraiserSearchID > maxId)
                            maxId = fundraiser.FundraiserSearchID;
                    });
                    $scope.fundRaiser.FundraiserSearchID = ++maxId;
                    $scope.fundRaiser.FundraiserFEINNumber = $scope.selectedFundraiser.FEINNumber;
                    $scope.fundRaiser.FundraiserUBINumber = $scope.selectedFundraiser.UBINumber;
                    $scope.fundRaiser.FundraiserSearchName = $scope.selectedFundraiser.EntityName;
                    $scope.fundRaiser.FundraiserSearchMailingAddress = $scope.selectedFundraiser.EntityMailingAddress;
                    $scope.fundRaiser.FundraiserStatus = principalStatus.INSERT;
                    $scope.fundRaiser.isFundraiserAdded = false;
                    $scope.commercialFundraisersContractors.FundraisersList.push($scope.fundRaiser);
                    $scope.resetFundraiser(); // resetFundraiser method is available in this file only
                    $("#divFundraisersList").modal('toggle');
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: selectFundraiser method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.FundraiserSearch.selectFundraiser);
                }
            };

            //Search Fundraiser -- End

            ///Add/Edit/Delete New Fundraiser - Start
            //Reset the fundraiser charitable organization
            $scope.resetFundraiser = function () {
                $scope.fundRaiser = angular.copy(fundRaiserScopeData);
                $scope.showErrorMessage = false;
                $scope.addHideFundraiser = "Add New Fundraiser";
            };

            $scope.ShowHideAddNewFundraiser = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsAddNewFundraiser = $scope.IsAddNewFundraiser ? false : true;
                $scope.addHideFundraiser = $scope.IsAddNewFundraiser ? "Add New Fundraiser" : "Cancel Fundraiser";
            }
            $scope.AddNewFundraiser = function (fundraiserForm) {
                $scope.showFRAddValidation = true;

                $scope.fundRaiser.FundraiserSearchMailingAddress.StreetAddress1 = (($scope.fundRaiser.FundraiserSearchMailingAddress.StreetAddress1 != null && $scope.fundRaiser.FundraiserSearchMailingAddress.StreetAddress1.trim() == "" || $scope.fundRaiser.FundraiserSearchMailingAddress.StreetAddress1 == undefined) ? $scope.fundRaiser.FundraiserSearchMailingAddress.StreetAddress1 = null : $scope.fundRaiser.FundraiserSearchMailingAddress.StreetAddress1.trim());
                if (!$scope.fundRaiser.FundraiserSearchMailingAddress.StreetAddress1) {
                    $scope.fundraisersForm.fundraiserForm.CFTAddress.StreetAddress1.$setValidity("text", false);
                }
                else {
                    $scope.fundraisersForm.fundraiserForm.CFTAddress.StreetAddress1.$setValidity("text", true);
                }

                if ($scope.fundraisersForm[fundraiserForm].$valid) {
                    $scope.showFRAddValidation = false;
                    if ($scope.fundRaiser.FundraiserSearchID != "") {
                        angular.forEach($scope.commercialFundraisersContractors.FundraisersList, function (fundraiser) {
                            if (fundraiser.FundraiserSearchID == $scope.fundRaiser.FundraiserSearchID) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                $scope.fundRaiser.FundraiserSearchMailingAddress.FullAddress = wacorpService.fullAddressService($scope.fundRaiser.FundraiserSearchMailingAddress);
                                angular.copy($scope.fundRaiser, fundraiser);
                            }
                        });
                        $scope.IsAddNewFundraiser = false;
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.commercialFundraisersContractors.FundraisersList, function (fundraiser) {
                            if (maxId == constant.ZERO || fundraiser.FundraiserSearchID > maxId)
                                maxId = fundraiser.FundraiserSearchID;
                        });
                        $scope.fundRaiser.FundraiserSearchID = ++maxId;
                        $scope.fundRaiser.isFundraiserAdded = true;
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.fundRaiser.FundraiserSearchMailingAddress.FundraiserSearchMailingAddress = wacorpService.fullAddressService($scope.fundRaiser.FundraiserSearchMailingAddress);
                        $scope.fundRaiser.FundraiserStatus = principalStatus.INSERT;
                        $scope.commercialFundraisersContractors.FundraisersList.push($scope.fundRaiser);
                        $scope.IsAddNewFundraiser = false;
                    }
                    $scope.resetFundraiser();  // resetFundraiser method is available in this file only
                }

            }

            //Edit fundraiser charitable organization data
            $scope.editCFTFundRaiser = function (fundraiserData) {
                $scope.IsAddNewFundraiser = true;
                fundraiserData.FundraiserSearchMailingAddress.Country = fundraiserData.FundraiserSearchMailingAddress.Country || codes.USA;
                fundraiserData.FundraiserSearchMailingAddress.State = fundraiserData.FundraiserSearchMailingAddress.State || codes.USA;
                if (fundraiserData.FundraiserStatus != principalStatus.INSERT)
                    fundraiserData.FundraiserStatus = principalStatus.UPDATE;
                $scope.fundRaiser = angular.copy(fundraiserData);
                $scope.addHideFundraiser = "Update Fundraiser";
            };

            //Delete fundraiser charitable organization data
            $scope.deleteCFTFundRaiser = function (fundraiserData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    //if (fundraiserData.CFTID <= 0) {
                    var index = $scope.commercialFundraisersContractors.FundraisersList.indexOf(fundraiserData);
                    $scope.commercialFundraisersContractors.FundraisersList.splice(index, 1);
                    //}
                    //else
                    //    fundraiserData.FundraiserStatus = principalStatus.DELETE;
                    //$scope.FundCount = 0;
                    //angular.forEach($scope.commercialFundraisersContractors.FundraisersList, function (fundraiser) {
                    //    if (fundraiser.FundraiserStatus != "D") {
                    //        $scope.FundCount++;
                    //    }
                    //});
                    $scope.resetFundraiser(); // resetFundraiser method is available in this file only
                });
            };

            //Clear new the Fundraiser Information
            $scope.clearFRDetails = function () {
                $scope.fundRaiser = angular.copy(fundRaiserResetScope);
                $scope.selectedFundraiser = angular.copy(fundRaiserResetScope);
            };

            //selection of fundraiser
            $scope.resetFundSelection = function (flag, count) {
                if (!flag && count.length > 0) {
                    wacorpService.confirmDialog($scope.commercialFundraisersContractors.FundraisersList.filesDeleteConfirm, function () {
                        for (var i = 0; i < $scope.commercialFundraisersContractors.FundraisersList.length; i = 0) {
                            $scope.commercialFundraisersContractors.FundraisersList.splice(i, 1);
                        }
                        $scope.commercialFundraisersContractors.IsCommercialFundraisersContributionsInWA = false;
                    },
                      function () {
                          $scope.commercialFundraisersContractors.IsCommercialFundraisersContributionsInWA = true;
                      });
                }
            };

            $scope.YesNo = function () {
                $scope.fundraiserSearchCriteria.Type = 'FundOrgName';
                //$timeout(function () {
                //    $("#frNameSearchField").focus();
                //},200);

            }

            $scope.$watch("fundraiserSearchCriteria.Type", function (newvalue) {
                angular.extend($scope.fundraiserSearchCriteria, { FundraiserName: "", FundraiserID: "", FEINNo: "", FundraiserUBINumber: "", RegistrationNumber: "" });
                //var ele = '';
                //if (newvalue == 'FundOrgName')
                //    ele = '#frNameSearchField';
                //else if (newvalue == 'FundFEINNo')
                //    ele = '#frNoSearchField';
                //else if (newvalue == 'FundUBINo')
                //    ele = '#frNameSearchField';
                //else if (newvalue == '')
                //    ele = '#frNameSearchField';

            });

            //copypaste Fein Number
            $scope.setPastedFeinNumber = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.fundraiserSearchCriteria.FEINNo = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.fundraiserSearchCriteria.FEINNo = pastedText;
                    });
                }
            };

        },
    };
});
wacorpApp.directive('fundraiserfinancialhistory', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserFinancialHistory/_FundraiserFinancialHistory.html',
        restrict: 'A',
        scope: {
            isHistory: '=?isHistory',
            financialData: '=?financialData',
            currentData: '=?currentData'
            //isEdited: '=?isEdited',
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.isHistory = $scope.isHistory || false;
            $scope.financialData.CFTFinancialHistoryList = $scope.financialData.CFTFinancialHistoryList || [];
            //$scope.isEdited = $scope.isEdited || false;

            var FinancialInfoScope = {
                IsFIFullAccountingYear: false,
                AccountingyearBeginningDate: null,
                AccountingyearEndingDate: null,
                FirstAccountingyearEndDate: null,
                //BeginingGrossAssets: null,
                RevenueGDfromSolicitations: null,
                RevenueGDRevenueAllOtherSources: null,
                //TotalDollarValueofGrossReceipts: null,
                ExpensesGDExpendituresProgramServices: null,
                //ExpensesGDValueofAllExpenditures: null,
                //EndingGrossAssets: null,
                //PercentToProgramServices: null,
                Comments: null,
                CFTFinancialHistoryList: []
            };

            //$scope.financialData = $scope.financialData ? angular.extend(FinancialInfoScope, $scope.financialData) : angular.copy(FinancialInfoScope);
            //$scope.financialData = $scope.financialData ;

            //$scope.$watch('financialData.CFTFinancialHistoryList', function () {
            //    angular.forEach($scope.financialData.CFTFinancialHistoryList, function (fiscalInfo) {
            //        fiscalInfo.AccountingyearBeginningDate = wacorpService.dateFormatService(fiscalInfo.AccountingyearEndingDate);
            //        fiscalInfo.AccountingyearEndingDate = wacorpService.dateFormatService(fiscalInfo.AccountingyearEndingDate);
            //    });

            //}, true);

            //Edit fundraiser Financial Info
            $scope.editFinancialInfo = function (financialItem) {
                $scope.currentData.FinancialSeqNo = financialItem.SequenceNo;
                $scope.currentData.HasOrganizationCompletedFullAccountingYear = financialItem.IsFIFullAccountingYear;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.currentData.AccountingYearBeginningDate = wacorpService.dateFormatService(financialItem.AccountingyearBeginningDate);
                $scope.currentData.AccountingYearEndingDate = wacorpService.dateFormatService(financialItem.AccountingyearEndingDate);

                $scope.currentData.AllContributionsReceived = financialItem.AllContributionsReceived;
                $scope.currentData.AmountOfFunds = financialItem.AmountOfFunds;
                $scope.currentData.AveragePercentToCharity = financialItem.AveragePercentToCharity;
                $rootScope.isGlobalEdited = true;
            };

            //Delete fundraiser financial Info
            $scope.deleteFinancialInfo = function (financialItem) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    var index = $scope.financialData.CFTFinancialHistoryList.indexOf(financialItem);
                    $scope.financialData.CFTFinancialHistoryList.splice(index, 1);
                    $scope.financialData.NewFinCount = 0;
                    angular.forEach($scope.financialData.CFTFinancialHistoryList, function (value) {
                        if (value.Flag == 'C') {
                            $scope.financialData.NewFinCount++;
                        }
                    });
                });
            };
        },
    };
});
wacorpApp.directive('charitiesFinancialInfoForReRegistration', function ($q) {

    return {
        templateUrl: 'ng-app/directives/CFT/CharitiesFinancialInfoForReRegistration/_CharitiesFinancialInfoForReRegistration.html',
        restrict: 'A',
        scope: {
            charityFinancialInfo: '=?charityFinancialInfo',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            officerNotRequired: '=?officerNotRequired',
            showFinancialHistory: '=?showFinancialHistory',
            financialBtn: '=?financialBtn',
            accDate: '=?accDate'
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope) {
            $scope.initialLoad = true;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isReview = $scope.isReview || false;
            $rootScope.isGlobalEdited = $rootScope.isGlobalEdited || false;
            $scope.isEdited = $scope.isEdited || false;
            $scope.isNewFinInfo = false;
            $scope.messages = messages;
            $scope.Countries = [];
            $scope.States = [];
            $scope.ValidateFinancialEndDateMessage = false;
            $scope.addbuttonName = "Add";
            $scope.currentFinancialObj = {};
            $scope.FinancialInfoButtonName = $scope.FinancialInfoButtonName ? $scope.FinancialInfoButtonName : "Add Financial Information";
            $scope.showEndDateErrorMessage = false;
            $scope.currentDate = wacorpService.dateFormatService(new Date());
            $scope.endCurrentDate = wacorpService.dateFormatService(new Date());
            $scope.isMandetory = true;

            var charityFinancialInfoScope = {
                FinancialSeqNo: null,
                IsFIFullAccountingYear: false,
                AccountingyearBeginningDate: null,
                AccountingyearEndingDate: null,
                FirstAccountingyearEndDate: null,
                BeginingGrossAssets: null,
                RevenueGDfromSolicitations: null,
                RevenueGDRevenueAllOtherSources: null,
                TotalDollarValueofGrossReceipts: null,
                ExpensesGDExpendituresProgramServices: null,
                ExpensesGDValueofAllExpenditures: null,
                EndingGrossAssets: null,
                PercentToProgramServices: null,
                IsFISolicitCollectcontributionsinWA: true,
                Comments: null,
                CFTOfficersList: [],
                OfficersHighPay: null,
                OfficersHighPayList: [],
                CFTFinancialHistoryList: [],
                shortFiscalYearEntity: {
                    FiscalStartDate: "", FiscalEndDate: "", BeginingGrossAssetsForShortFY: null, RevenueGDfromSolicitationsForShortFY: null, RevenueGDRevenueAllOtherSourcesForShortFY: null,
                    TotalDollarValueofGrossReceiptsForShortFY: null, ExpensesGDExpendituresProgramServicesForShortFY: null, ExpensesGDValueofAllExpendituresForShortFY: null,
                    EndingGrossAssetsForShortFY: null, PercentToProgramServicesForShortFY: null
                }
            };
            angular.copy($scope.currentFinancialObj, charityFinancialInfoScope);

            //For Financial History Validations
            var finHistoryObj = {
                currentYearFinancialObj: {
                    AccountingyearBeginningDate: null, AccountingyearEndingDate: null, BeginingGrossAssets: null, RevenueGDfromSolicitations: null, RevenueGDRevenueAllOtherSources: null
                    , TotalDollarValueofGrossReceipts: null, EndingGrossAssets: null, ExpensesGDExpendituresProgramServices: null, ExpensesGDValueofAllExpenditures: null, PercentToProgramServices: null
                }, HistoryFinancialObj: {
                    AccountingyearBeginningDate: null, AccountingyearEndingDate: null, BeginingGrossAssets: null, RevenueGDfromSolicitations: null, RevenueGDRevenueAllOtherSources: null
                    , TotalDollarValueofGrossReceipts: null, EndingGrossAssets: null, ExpensesGDExpendituresProgramServices: null, ExpensesGDValueofAllExpenditures: null, PercentToProgramServices: null
                },
                financialHistoryList: [], LastAccountingYearEndDate: null
            };


            $scope.OfficershighPayData = { ID: '', FirstName: '', LastName: '', SequenceNo: null, Status: '', IsPayOfficers: false, CreatedBy: null };

            $scope.OfficershighPayScopeData = { ID: '', FirstName: '', LastName: '', SequenceNo: null, Status: '', IsPayOfficers: false, CreatedBy: null };

            $scope.charityFinancialInfo = $scope.charityFinancialInfo ? angular.extend(charityFinancialInfoScope, $scope.charityFinancialInfo) : angular.copy(charityFinancialInfoScope);

            $scope.isNeedValidation = function () {
                return $scope.showErrorMessage || false;
            };
            //Get Countries List
            $scope.getCountries = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.countriesList(function (response) {
                    $scope.Countries = response.data;
                });
            };

            //Get States List
            $scope.getStates = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.statesList(function (response) {
                    $scope.States = response.data;
                });
            };

            $scope.getCountries(); // getCountries method is available in this controller only.
            $scope.getStates(); // getStates method is available in this controller only.

            //For Current Financial Info
            $scope.$watchGroup(['charityFinancialInfo.ExpensesGDExpendituresProgramServices', 'charityFinancialInfo.ExpensesGDValueofAllExpenditures'], function () {

                var value1 = parseFloat($scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices == null || $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices == '') ? 0 : $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices;
                var value2 = parseFloat($scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures == null || $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures == '') ? 0 : $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures;
                var percentage = null;
                if (value1 && value2)
                    percentage = ((value1 / value2) * 100).toFixed(2);
                else
                    percentage = null;

                //$scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = parseFloat($scope.charityFinancialInfo.TotalDollarValueofGrossReceipts).toFixed(2);

                if (isNaN(percentage) || percentage === 0)
                    $scope.charityFinancialInfo.PercentToProgramServices = null;
                else {
                    if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                        $scope.charityFinancialInfo.PercentToProgramServices = "-" + Math.round(percentage);
                    } else {
                        $scope.charityFinancialInfo.PercentToProgramServices = Math.round(percentage);
                    }
                }
            }, true);


            //For History Financial Info
            $scope.$watchGroup(['currentFinancialObj.ExpensesGDExpendituresProgramServices', 'currentFinancialObj.ExpensesGDValueofAllExpenditures'], function () {

                var value1 = parseFloat($scope.currentFinancialObj.ExpensesGDExpendituresProgramServices == null || $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices == '') ? 0 : $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices;
                var value2 = parseFloat($scope.currentFinancialObj.ExpensesGDValueofAllExpenditures == null || $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures == '') ? 0 : $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures;
                var percentage = null;
                if (value1 && value2)
                    percentage = ((value1 / value2) * 100).toFixed(2);
                else
                    percentage = null;
                if (isNaN(percentage) || percentage === 0)
                    $scope.currentFinancialObj.PercentToProgramServices = null;
                else {
                    if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                        $scope.currentFinancialObj.PercentToProgramServices = "-" + Math.round(percentage);
                    } else {
                        $scope.currentFinancialObj.PercentToProgramServices = Math.round(percentage);
                    }
                }
            }, true);


            ////For Short Fiscal Financial Info
            //$scope.$watchGroup(['charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY', 'charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY'], function () {
            //    if ($scope.charityFinancialInfo.shortFiscalYearEntity != undefined && $scope.charityFinancialInfo.shortFiscalYearEntity != null) {
            //        var value1 = parseFloat($scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY == null || $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY == '') ? 0 : $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY;
            //        var value2 = parseFloat($scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY == null || $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY == '') ? 0 : $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY;
            //        var percentage = null;
            //        if (value1 && value2)
            //            percentage = ((value1 / value2) * 100).toFixed(2);
            //        else
            //            percentage = null;

            //        if (isNaN(percentage) || percentage === 0)
            //            $scope.charityFinancialInfo.shortFiscalYearEntity.PercentToProgramServicesForShortFY = null;
            //        else {
            //            if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
            //                $scope.charityFinancialInfo.shortFiscalYearEntity.PercentToProgramServicesForShortFY = "-" + Math.round(percentage);
            //            }
            //            else {
            //                $scope.charityFinancialInfo.shortFiscalYearEntity.PercentToProgramServicesForShortFY = Math.round(percentage);
            //            }
            //        }
            //    }
            //}, true);

            //Current
            $scope.calCulateTGDV = function () {
                var totalVal =
                               parseFloat(($scope.charityFinancialInfo.RevenueGDfromSolicitations == null || $scope.charityFinancialInfo.RevenueGDfromSolicitations == '') ? 0 : $scope.charityFinancialInfo.RevenueGDfromSolicitations) +
                               parseFloat(($scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources == '' || $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources == null) ? 0 : $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources);

                if (totalVal === 0)
                    $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = 0;
                else
                    $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = Math.round(totalVal);

            };

            //History
            $scope.calCulateHistoryTGDV = function () {
                var totalVal =
                               parseFloat(($scope.currentFinancialObj.RevenueGDfromSolicitations == null || $scope.currentFinancialObj.RevenueGDfromSolicitations == '') ? 0 : $scope.currentFinancialObj.RevenueGDfromSolicitations) +
                               parseFloat(($scope.currentFinancialObj.RevenueGDRevenueAllOtherSources == '' || $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources == null) ? 0 : $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources);

                if (totalVal === 0)
                    $scope.currentFinancialObj.TotalDollarValueofGrossReceipts = 0;
                else
                    $scope.currentFinancialObj.TotalDollarValueofGrossReceipts = Math.round(totalVal);

            };

            //Short Fiscal Year
            $scope.calCulateShortFiscalTGDV = function () {
                var totalVal =
                               parseFloat(($scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY == null || $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY == '') ? 0 : $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY) +
                               parseFloat(($scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY == '' || $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY == null) ? 0 : $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY);

                if (totalVal === 0)
                    $scope.charityFinancialInfo.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY = 0;
                else
                    $scope.charityFinancialInfo.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY = Math.round(totalVal);
            };


            var resultHistoryDate = "";
            $scope.ValidateHistoryEndDate = function () {
                if ($scope.currentFinancialObj.AccountingyearBeginningDate != null && $scope.currentFinancialObj.AccountingyearBeginningDate != "") {
                    var value = $scope.currentFinancialObj.AccountingyearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultHistoryDate = lastDayWithSlashes;
                        $scope.currentFinancialObj.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");

                        $("#idHisEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.currentFinancialObj.AccountingyearEndingDate = null;
                    }
                }
                else {
                    $scope.currentFinancialObj.AccountingyearEndingDate = null;
                }

                //if (typeof ($scope.currentFinancialObj.AccountingyearBeginningDate) != typeof (undefined)
                //    && $scope.currentFinancialObj.AccountingyearBeginningDate != null) {
                //    if ($scope.currentFinancialObj.AccountingyearEndingDate && $scope.charityFinancialInfo.LastAccountingYearEndDate) {
                //        if (new Date($scope.currentFinancialObj.AccountingyearBeginningDate) < new Date($scope.charityFinancialInfo.LastAccountingYearEndDate)) {
                //            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = true;
                //        }
                //        else {
                //            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                //        }
                //    }
                //}

                if ($scope.currentFinancialObj.AccountingyearBeginningDate != "") {
                    var histotyBegDate = new Date($scope.currentFinancialObj.AccountingyearBeginningDate);
                    if (typeof ($scope.charityFinancialInfo.AccountingyearBeginningDate) != typeof (undefined) && $scope.charityFinancialInfo.AccountingyearBeginningDate != null) {
                        var curretnDate = new Date($scope.charityFinancialInfo.AccountingyearBeginningDate);
                        var curretnEndDate = new Date($scope.charityFinancialInfo.AccountingyearEndingDate);
                        if (histotyBegDate >= curretnDate) {
                            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = true;
                        }
                        else {
                            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                        }
                    }
                }

                $scope.CheckHistoryEndDate(); // CheckHistoryEndDate method is available in this file only.
            };


            $scope.CheckHistoryEndDate = function () {
                if ($scope.currentFinancialObj.AccountingyearBeginningDate != null && $scope.currentFinancialObj.AccountingyearBeginningDate != "") {
                    var value = $scope.currentFinancialObj.AccountingyearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultHistoryDate = lastDayWithSlashes;
                        $scope.currentFinancialObj.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");

                        $("#idHisEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.currentFinancialObj.AccountingyearEndingDate = null;
                    }
                }
                else {
                    $scope.currentFinancialObj.AccountingyearEndingDate = null;
                }
                if (new Date($scope.currentFinancialObj.AccountingyearEndingDate) < new Date($scope.currentFinancialObj.AccountingyearBeginningDate)) {
                    $scope.ValidateHistoryFinancialEndDateMessage = true;
                }
                else
                    $scope.ValidateHistoryFinancialEndDateMessage = false;
            };

            //$scope.charityFinancialInfo.PercentToProgramServices = ((value1 / value2) * 100).toFixed(2);
            var resultDate = "";
            $scope.ValidateEndDate = function () {
                if ($scope.charityFinancialInfo.AccountingyearBeginningDate != null && $scope.charityFinancialInfo.AccountingyearBeginningDate != "") {
                    var value = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultDate = lastDayWithSlashes;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                    }
                }
                else {
                    $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                }

                if (typeof ($scope.charityFinancialInfo.BusinessFiling) != typeof (undefined) && $scope.charityFinancialInfo.BusinessFiling != null && $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION AMENDMENT') {
                    $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = false;
                    if ($scope.charityFinancialInfo.IsFIFullAccountingYear) {
                        $scope.charityFinancialInfo.AccYearStartDateForAmendment = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                        //$scope.charityFinancialInfo.AccStartDateMoreThanOneYear = wacorpService.checkForAccYearMaxThenOneYear($scope.charityFinancialInfo.AccYearStartDateForAmendment, $scope.charityFinancialInfo.CurrentEndDateForAmendment);
                    }
                }

                if (typeof ($scope.charityFinancialInfo.AccountingyearBeginningDate) != typeof (undefined)
                    && $scope.charityFinancialInfo.AccountingyearBeginningDate != null) {
                    $scope.checkStartDate = false;
                    if ($scope.charityFinancialInfo.AccountingyearEndingDate && $scope.charityFinancialInfo.LastAccountingYearEndDate) {
                        if (new Date($scope.charityFinancialInfo.AccountingyearBeginningDate) < new Date($scope.charityFinancialInfo.LastAccountingYearEndDate)) {
                            $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = true;
                        }
                        else {
                            $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = false;
                        }

                        //var val = wacorpService.checkDateValidity($scope.charityFinancialInfo.CurrentEndDateForAmendment, $scope.charityFinancialInfo.AccountingyearBeginningDate, $scope.charityFinancialInfo.IsShortFiscalYear);
                        //if (val == 'SFY') {
                        //    $scope.charityFinancialInfo.IsShortFiscalYear = true;
                        //    var startDate = wacorpService.getShortYearStartDate($scope.charityFinancialInfo.CurrentEndDateForAmendment);
                        //    $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalStartDate = wacorpService.dateFormatService(startDate);
                        //    var endDate = wacorpService.getShortYearEndDate($scope.charityFinancialInfo.AccountingyearBeginningDate);
                        //    $scope.charityFinancialInfo.shortFiscalYearEntity.FiscalEndDate = wacorpService.dateFormatService(endDate);
                        //    $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = false;
                        //    $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = false;
                        //} else if (val == 'SDgPnD') {
                        //    $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = true;
                        //    $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = false;
                        //    $scope.charityFinancialInfo.IsShortFiscalYear = false;
                        //} else if (val == 'Y1Plus') {
                        //    $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = true;
                        //    $scope.charityFinancialInfo.IsShortFiscalYear = false;
                        //    $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = false;
                        //} else {
                        //    $scope.charityFinancialInfo.AccStartDateMoreThanOneYear = false;
                        //    $scope.charityFinancialInfo.IsShortFiscalYear = false;
                        //    $scope.charityFinancialInfo.AccEndDateLessThanCurrentYear = false;
                        //}
                    }
                }

                $scope.CheckEndDate();
            };

            $scope.CheckEndDate = function () {
                if ($scope.charityFinancialInfo.AccountingyearEndingDate != null && $scope.charityFinancialInfo.AccountingyearBeginningDate != null) {
                    if (new Date($scope.charityFinancialInfo.AccountingyearEndingDate) < new Date($scope.charityFinancialInfo.AccountingyearBeginningDate)) {
                        $scope.ValidateFinancialEndDateMessage = true;
                    }
                    else
                        $scope.ValidateFinancialEndDateMessage = false;
                }
            };



            $scope.setEndDate = function () {
                $scope.charityFinancialInfo.AccountingyearEndingDate = resultDate;
            }

            $scope.resetHighPay = function () {
                $scope.OfficershighPayData = angular.copy($scope.OfficershighPayScopeData);
                $scope.addbuttonName = "Add";
            }

            $scope.addOfficerHighPay = function (officerHighPay) {
                $scope.hasValues = officerHighPay.FirstName != null && officerHighPay.FirstName != "" && officerHighPay.FirstName != undefined && officerHighPay.LastName != null && officerHighPay.LastName != "" && officerHighPay.LastName != undefined ? true : false;
                //$scope.hasValues = officerHighPay.FirstName != null && officerHighPay.FirstName != "" || officerHighPay.Lastname != null && officerHighPay.Lastname!="";
                if (!$scope.hasValues) {
                    return false;
                }
                else {
                    $scope.ValidateErrorMessage = false;
                    if ($scope.OfficershighPayData.SequenceNo != null && $scope.OfficershighPayData.SequenceNo != '' && $scope.OfficershighPayData.SequenceNo != 0) {
                        angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (highpayItem) {
                            if (highpayItem.SequenceNo == $scope.OfficershighPayData.SequenceNo) {
                                //$scope.cftOfficer.OfficerAddress.FullAddress = wacorpService.cftFullAddressService($scope.cftOfficer.OfficerAddress);
                                angular.copy($scope.OfficershighPayData, highpayItem);
                                $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only.

                                //if ($scope.charityFinancialInfo.OfficersHighPayList.length >= 3)
                                //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                                //else
                                //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (highpayItem) {
                            if (maxId == constant.ZERO || highpayItem.SequenceNo > maxId)
                                maxId = highpayItem.SequenceNo;
                        });
                        $scope.OfficershighPayData.SequenceNo = ++maxId;
                        $scope.OfficershighPayData.Status = principalStatus.INSERT;
                        $scope.charityFinancialInfo.OfficersHighPayList.push($scope.OfficershighPayData);

                        $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only.
                        //if ($scope.charityFinancialInfo.OfficersHighPayList.length >= 3)
                        //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                        //else
                        //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                        //$scope.ShowHighPayList = true;
                    }
                    $scope.resetHighPay(); // resetHighPay method is available in this file only.
                }
            };

            $scope.editOfficerHighPay = function (highPayActionData) {
                $scope.OfficershighPayData = angular.copy(highPayActionData);
                $scope.OfficershighPayData.Status = principalStatus.UPDATE;
                $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                $scope.addbuttonName = "Update";

            };

            $scope.deleteOfficerHighPay = function (highPayActionData) {
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (highPayActionData.ID <= 0) {
                        var index = $scope.charityFinancialInfo.OfficersHighPayList.indexOf(highPayActionData);
                        $scope.charityFinancialInfo.OfficersHighPayList.splice(index, 1);
                    }
                    else
                        highPayActionData.Status = principalStatus.DELETE;

                    $scope.checkHighpayCount();  // checkHighpayCount method is available in this file only.
                    //$scope.Count = 0;
                    //angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (highpayItem) {

                    //    if (highpayItem.Status != "D")
                    //    {
                    //        $scope.Count++;
                    //        if ($scope.Count >=3)
                    //        {
                    //            $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                    //        }
                    //        else {
                    //            $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                    //        }
                    //    }
                    //});
                    if ($scope.charityFinancialInfo.OfficersHighPayList.length == 0)
                        //$scope.ShowHighPayList = true;
                        //if ($scope.charityFinancialInfo.OfficersHighPayList.length >= 3)
                        //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                        //else
                        //    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                        $scope.resetHighPay();
                });
            };


            $scope.checkHighpayCount = function () {
                var count = 0;
                angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (highpayItem) {
                    if (highpayItem.Status != "D") {
                        count++;
                    }
                });

                if (count >= 3) {
                    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = true;
                }
                else {
                    $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
                }
                return count <= 0;
            };

            $scope.clearFields = function (flag, type) {
                if (!flag) {
                    $scope.charityFinancialInfo.isUpdated = false;
                    if (type == "CHARITABLE ORGANIZATION RENEWAL") {
                        $scope.charityFinancialInfo.AccountingyearBeginningDate = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = $scope.charityFinancialInfo.AccountingyearEndingDate;
                        $scope.charityFinancialInfo.FirstAccountingyearEndDate = $scope.charityFinancialInfo.FirstAccountingyearEndDate;
                        $scope.charityFinancialInfo.BeginingGrossAssets = null;
                        $scope.charityFinancialInfo.RevenueGDfromSolicitations = null;
                        $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources = null;
                        $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = null;
                        $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices = null;
                        $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures = null;
                        $scope.charityFinancialInfo.EndingGrossAssets = null;
                        $scope.charityFinancialInfo.PercentToProgramServices = null;
                        $scope.charityFinancialInfo.Comments = null;
                    }
                    else {
                        $scope.charityFinancialInfo.AccountingyearBeginningDate = null;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = null;
                        $scope.charityFinancialInfo.BeginingGrossAssets = null;
                        $scope.charityFinancialInfo.RevenueGDfromSolicitations = null;
                        $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources = null;
                        $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts = null;
                        $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices = null;
                        $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures = null;
                        $scope.charityFinancialInfo.EndingGrossAssets = null;
                        $scope.charityFinancialInfo.PercentToProgramServices = null;
                        $scope.charityFinancialInfo.Comments = null;
                    }
                }
                else {
                    $scope.charityFinancialInfo.isUpdated = true;
                    if (type == "CHARITABLE ORGANIZATION RENEWAL") {
                        $scope.charityFinancialInfo.BeginingGrossAssets = null;
                        $scope.charityFinancialInfo.AccountingyearBeginningDate = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                        $scope.charityFinancialInfo.AccountingyearEndingDate = $scope.charityFinancialInfo.AccountingyearEndingDate;
                        $scope.charityFinancialInfo.FirstAccountingyearEndDate = $scope.charityFinancialInfo.FirstAccountingyearEndDate;
                    }
                    else {
                        $scope.charityFinancialInfo.FirstAccountingyearEndDate = null;
                        $scope.charityFinancialInfo.IsShortFiscalYear = false;
                    }

                }
            };

            $scope.resetHighPayOfficer = function () {
                $scope.charityFinancialInfo.OfficersHighPayList = [];
                $scope.OfficershighPayData.FirstName = '';
                $scope.OfficershighPayData.LastName = '';
                $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;
            };

            $scope.resetSelection = function () {
                if ($scope.charityFinancialInfo.OfficersHighPayList.length > 0) {
                    wacorpService.confirmDialog($scope.messages.UploadFiles.deleteallRecords, function () {
                        angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (value, data) {
                            if (value.ID > 0) {
                                value.Status = principalStatus.DELETE;
                            }
                            else {
                                var index = $scope.charityFinancialInfo.OfficersHighPayList.indexOf(value);
                                $scope.charityFinancialInfo.OfficersHighPayList.splice(index);
                            }
                        });

                        $scope.OfficershighPayData.FirstName = '';
                        $scope.OfficershighPayData.LastName = '';
                        //$scope.ShowHighPayList = false;
                        $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only.
                        $scope.charityFinancialInfo.OfficersHighPay.IsCountMax = false;

                    },
                 function () {
                     $scope.charityFinancialInfo.OfficersHighPay.IsPayOfficers = true;
                 });
                }
                //angular.forEach($scope.charityFinancialInfo.OfficersHighPayList, function (value, data) {
                //    if (value.ID > 0)
                //    {
                //        value.Status = principalStatus.DELETE;

                //    }
                //    else {
                //        var index = $scope.charityFinancialInfo.OfficersHighPayList.indexOf(value);
                //        $scope.charityFinancialInfo.OfficersHighPayList.splice(index);
                //    }
                //})

            };

            //reset contributions
            $scope.resetContributions = function () {
                $scope.charityFinancialInfo.ContributionServicesTypeId = [];
            };

            //reset fundraiser outside of wa
            $scope.resetFundOutsideWA = function () {
                $scope.charityFinancialInfo.FinancialInfoStateId = [];
            };

            //CFT Financial History Methods


            $rootScope.$watch('isGlobalEdited', function (val) {
                $scope.isEdited = val;
                $scope.isNewFinInfo = val;
                //if ($scope.isEdited) {
                //    $scope.charityFinancialInfo.IsShortFiscalYear = false;
                //}
            });


            var addNewFinancialHistory = function () {
                $scope.showErrorMessageForHistory = true;
                var isExpensesValid = ($scope.currentFinancialObj.ExpensesGDValueofAllExpenditures < $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices ? false : true);
                var isDatesValid = ((new Date($scope.currentFinancialObj.AccountingyearEndingDate) > new Date($scope.currentFinancialObj.AccountingyearBeginningDate)) ? true : false);
                if ($scope.CharityFinancialInfoForm.divFinHistory.$valid && isExpensesValid && isDatesValid && !$scope.ValidateHistoryFinancialEndDateMessage && !$scope.currentFinancialObj.AccEndDateLessThanCurrentYear) {
                    $scope.showErrorMessageForHistory = false;
                    $scope.FinancialInfoButtonName = "Add Financial Information";
                    var maxId = constant.ZERO;
                    angular.forEach($scope.charityFinancialInfo.CFTFinancialHistoryList, function (finInfo) {
                        if (maxId == constant.ZERO || finInfo.SequenceNo > maxId)
                            maxId = finInfo.SequenceNo;
                    });
                    var financialInfoObj = {};
                    financialInfoObj.SequenceNo = ++maxId;
                    //financialInfoObj.FinancialId = financialInfoObj.SequenceNo;
                    financialInfoObj.Flag = 'C';
                    financialInfoObj.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingyearBeginningDate;
                    financialInfoObj.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingyearEndingDate;
                    financialInfoObj.BeginingGrossAssets = $scope.currentFinancialObj.BeginingGrossAssets;
                    financialInfoObj.RevenueGDfromSolicitations = $scope.currentFinancialObj.RevenueGDfromSolicitations;
                    financialInfoObj.RevenueGDRevenueAllOtherSources = $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources;
                    financialInfoObj.TotalDollarValueofGrossReceipts = $scope.currentFinancialObj.TotalDollarValueofGrossReceipts;
                    financialInfoObj.TotalRevenue = $scope.currentFinancialObj.RevenueGDfromSolicitations + $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources;
                    financialInfoObj.ExpensesGDExpendituresProgramServices = $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices;
                    financialInfoObj.ExpensesGDValueofAllExpenditures = $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures;
                    financialInfoObj.TotalExpenses = $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices + $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures;
                    financialInfoObj.EndingGrossAssets = $scope.currentFinancialObj.EndingGrossAssets;
                    financialInfoObj.PercentToProgramServices = $scope.currentFinancialObj.PercentToProgramServices;
                    financialInfoObj.Status = principalStatus.INSERT;
                    $scope.charityFinancialInfo.CFTFinancialHistoryList.push(financialInfoObj);

                    $scope.charityFinancialInfo.CFTFinancialHistoryList.sort(function (a, b) {
                        a = new Date(a.AccountingyearEndingDate);
                        b = new Date(b.AccountingyearEndingDate);
                        return a > b ? -1 : a < b ? 1 : 0;
                    });
                    $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                    //$scope.charityFinancialInfo.LastAccountingYearEndDate = financialInfoObj.AccountingyearEndingDate;
                    $scope.clearFinancialInfo();
                    $scope.charityFinancialInfo.NewFinCount = 0;
                    angular.forEach($scope.charityFinancialInfo.CFTFinancialHistoryList, function (value) {
                        if (value.Flag == 'C') {
                            $scope.charityFinancialInfo.NewFinCount++;
                        }
                    });
                }
            };

            //Add Financial History data
            $scope.AddFinancialInfo = function (cftFinancialForm) {
                addNewFinancialHistory(); // addNewFinancialHistory method is available in this file only.
            };

            $scope.UpdateFinancialInfo = function () {

                var endDate = $scope.charityFinancialInfo.AccountingyearEndingDate;
                if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                    if (isEndDateMore) {
                        // Folder Name: app Folder
                        // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js
                        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                        return false;
                    }
                }

                if ($scope.currentFinancialObj.AccountingyearBeginningDate != "") {
                    var histotyBegDate = new Date($scope.currentFinancialObj.AccountingyearBeginningDate);
                    if (typeof ($scope.charityFinancialInfo.AccountingyearBeginningDate) != typeof (undefined) && $scope.charityFinancialInfo.AccountingyearBeginningDate != null) {
                        var curretnDate = new Date($scope.charityFinancialInfo.AccountingyearBeginningDate);
                        var curretnEndDate = new Date($scope.charityFinancialInfo.AccountingyearEndingDate);
                        //if (histotyBegDate > curretnDate && histotyBegDate > curretnEndDate) {
                        if (histotyBegDate >= curretnDate) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog("Accounting Year Beginning Date cannot be greater than current Accounting Year");
                            return false;
                        }
                    }
                    else {
                        var curretnDate = new Date();
                        var histotyEndDate = new Date($scope.currentFinancialObj.AccountingyearEndingDate);
                        if (histotyEndDate >= curretnDate) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog("Accounting Year End Date cannot be greater than current date");
                            return false;
                        }
                    }
                }
                $scope.showErrorMessageForHistory = true;
                var isExpensesValid = ($scope.currentFinancialObj.IsFIFullAccountingYear ? ($scope.currentFinancialObj.ExpensesGDValueofAllExpenditures < $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices ? false : true) : true);
                var isDatesValid = ($scope.currentFinancialObj.IsFIFullAccountingYear ? ((new Date($scope.currentFinancialObj.AccountingyearEndingDate) > new Date($scope.currentFinancialObj.AccountingyearBeginningDate)) ? true : false) : true);
                if ($scope.CharityFinancialInfoForm.divFinHistory.$valid && isExpensesValid && isDatesValid) {
                    $scope.showErrorMessageForHistory = false;
                    angular.forEach($scope.charityFinancialInfo.CFTFinancialHistoryList, function (financialInfoItem) {
                        if (financialInfoItem.SequenceNo == $scope.currentFinancialObj.FinancialSeqNo) {
                            financialInfoItem.FinancialId = $scope.currentFinancialObj.FinancialId;
                            financialInfoItem.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingyearBeginningDate;
                            financialInfoItem.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingyearEndingDate;
                            financialInfoItem.BeginingGrossAssets = $scope.currentFinancialObj.BeginingGrossAssets;
                            financialInfoItem.RevenueGDfromSolicitations = $scope.currentFinancialObj.RevenueGDfromSolicitations;
                            financialInfoItem.RevenueGDRevenueAllOtherSources = $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources;
                            financialInfoItem.TotalDollarValueofGrossReceipts = $scope.currentFinancialObj.TotalDollarValueofGrossReceipts;
                            financialInfoItem.TotalRevenue = $scope.currentFinancialObj.RevenueGDfromSolicitations + $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources;
                            financialInfoItem.ExpensesGDExpendituresProgramServices = $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices;
                            financialInfoItem.ExpensesGDValueofAllExpenditures = $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures;
                            financialInfoItem.TotalExpenses = $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices + $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures;
                            financialInfoItem.EndingGrossAssets = $scope.currentFinancialObj.EndingGrossAssets;
                            financialInfoItem.PercentToProgramServices = $scope.currentFinancialObj.PercentToProgramServices;
                            financialInfoItem.Status = principalStatus.UPDATE;
                        }
                    });

                    $scope.charityFinancialInfo.CFTFinancialHistoryList.sort(function (a, b) {
                        a = new Date(a.AccountingyearEndingDate);
                        b = new Date(b.AccountingyearEndingDate);
                        return a > b ? -1 : a < b ? 1 : 0;
                    });
                    $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                    $rootScope.isGlobalEdited = false;
                    $scope.charityFinancialInfo.isUpdated = true;
                    $scope.clearFinancialInfo(); // clearFinancialInfo method is available in this file only
                }
            };

            // Clear all controls data
            $scope.clearFinancialInfo = function () {
                $scope.currentFinancialObj.AccountingyearBeginningDate = null;
                $scope.currentFinancialObj.AccountingyearEndingDate = null;
                $scope.currentFinancialObj.BeginingGrossAssets = null;
                $scope.currentFinancialObj.RevenueGDfromSolicitations = null;
                $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources = null;
                $scope.currentFinancialObj.TotalDollarValueofGrossReceipts = null;
                $scope.currentFinancialObj.EndingGrossAssets = null;
                $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices = null;
                $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures = null;
                $scope.currentFinancialObj.PercentToProgramServices = null;
                $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                $rootScope.isGlobalEdited = false;
                $scope.isNewFinInfo = false;
            };

            $scope.resetFinancialInfo = function () {
                //$scope.charityFinancialInfo.shortFiscalYearEntity.FiscalStartDate = null,
                //$scope.charityFinancialInfo.shortFiscalYearEntity.FiscalEndDate = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.BeginingGrossAssetsForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.EndingGrossAssetsForShortFY = null,
                $scope.charityFinancialInfo.shortFiscalYearEntity.PercentToProgramServicesForShortFY = null
            };

            $scope.$watch("charityFinancialInfo.AccountingyearEndingDate", function () {
                if (typeof ($scope.charityFinancialInfo.AccountingyearEndingDate) != typeof (undefined) && $scope.charityFinancialInfo.AccountingyearEndingDate != null && $scope.charityFinancialInfo.AccountingyearEndingDate != "") {
                    $scope.accDate = wacorpService.checkAccYearEndDateForReg($scope.charityFinancialInfo.AccountingyearEndingDate, true);
                }
            });

            $scope.$watch('charityFinancialInfo.AccountingyearEndingDate', function () {
                if ($scope.charityFinancialInfo.AccountingyearEndingDate != null && typeof ($scope.charityFinancialInfo.AccountingyearEndingDate) != typeof (undefined) && $scope.charityFinancialInfo.BusinessFiling.FilingTypeName == 'CHARITABLE ORGANIZATION AMENDMENT') {
                    //var isFinSectionMandetory = wacorpService.isFinancialMandetory($scope.charityFinancialInfo.AccountingyearEndingDate);
                    var isFinSectionMandetory = false;
                    if (isFinSectionMandetory) {
                        $scope.isMandetory = true;
                    }
                    else {
                        $scope.isMandetory = false;
                    }
                }
            });

            var checkFinHistoryValidation = function () {
                var defer = $q.defer();

                //Current Financial Object
                finHistoryObj.currentYearFinancialObj.AccountingyearBeginningDate = $scope.charityFinancialInfo.AccountingyearBeginningDate;
                finHistoryObj.currentYearFinancialObj.AccountingyearEndingDate = $scope.charityFinancialInfo.AccountingyearEndingDate;

                finHistoryObj.currentYearFinancialObj.BeginingGrossAssets = $scope.charityFinancialInfo.BeginingGrossAssets;
                finHistoryObj.currentYearFinancialObj.RevenueGDfromSolicitations = $scope.charityFinancialInfo.RevenueGDfromSolicitations;
                finHistoryObj.currentYearFinancialObj.RevenueGDRevenueAllOtherSources = $scope.charityFinancialInfo.RevenueGDRevenueAllOtherSources;

                finHistoryObj.currentYearFinancialObj.TotalDollarValueofGrossReceipts = $scope.charityFinancialInfo.TotalDollarValueofGrossReceipts;
                finHistoryObj.currentYearFinancialObj.EndingGrossAssets = $scope.charityFinancialInfo.EndingGrossAssets;
                finHistoryObj.currentYearFinancialObj.ExpensesGDExpendituresProgramServices = $scope.charityFinancialInfo.ExpensesGDExpendituresProgramServices;

                finHistoryObj.currentYearFinancialObj.ExpensesGDValueofAllExpenditures = $scope.charityFinancialInfo.ExpensesGDValueofAllExpenditures;
                finHistoryObj.currentYearFinancialObj.PercentToProgramServices = $scope.charityFinancialInfo.PercentToProgramServices;

                //History Financial Object
                finHistoryObj.HistoryFinancialObj.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingyearBeginningDate;
                finHistoryObj.HistoryFinancialObj.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingyearEndingDate;

                finHistoryObj.HistoryFinancialObj.BeginingGrossAssets = $scope.currentFinancialObj.BeginingGrossAssets;
                finHistoryObj.HistoryFinancialObj.RevenueGDfromSolicitations = $scope.currentFinancialObj.RevenueGDfromSolicitations;
                finHistoryObj.HistoryFinancialObj.RevenueGDRevenueAllOtherSources = $scope.currentFinancialObj.RevenueGDRevenueAllOtherSources;

                finHistoryObj.HistoryFinancialObj.TotalDollarValueofGrossReceipts = $scope.currentFinancialObj.TotalDollarValueofGrossReceipts;
                finHistoryObj.HistoryFinancialObj.EndingGrossAssets = $scope.currentFinancialObj.EndingGrossAssets;
                finHistoryObj.HistoryFinancialObj.ExpensesGDExpendituresProgramServices = $scope.currentFinancialObj.ExpensesGDExpendituresProgramServices;

                finHistoryObj.HistoryFinancialObj.ExpensesGDValueofAllExpenditures = $scope.currentFinancialObj.ExpensesGDValueofAllExpenditures;
                finHistoryObj.HistoryFinancialObj.PercentToProgramServices = $scope.currentFinancialObj.PercentToProgramServices;

                //Financial History List
                finHistoryObj.financialHistoryList = $scope.charityFinancialInfo.CFTFinancialHistoryList;

                //Last Accounting Year End Date
                finHistoryObj.LastAccountingYearEndDate = $scope.charityFinancialInfo.LastAccountingYearEndDate;

                //Hit to Api for Financial history Date Validations
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.post(webservices.CFT.getCFTFinHistoryValidation, finHistoryObj, function (response) {
                    defer.resolve(response);
                }, function (response) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    defer.reject(response);
                });

                return defer.promise;
            };

            $scope.AddNewFinInfo = function () {
                $scope.isNewFinInfo = true;
                if ($scope.charityFinancialInfo.CFTFinancialHistoryList.length > 0) {
                    var latestFinancialData = $scope.charityFinancialInfo.CFTFinancialHistoryList[0];
                    $scope.currentFinancialObj.AccountingyearBeginningDate = wacorpService.addDaysToGivenDate(latestFinancialData.AccountingyearEndingDate, 1);
                }
                else if ($scope.charityFinancialInfo.AccountingyearEndingDateForFAY != null) {
                    $scope.currentFinancialObj.AccountingyearBeginningDate = wacorpService.addDaysToGivenDate($scope.charityFinancialInfo.AccountingyearEndingDateForFAY, 1);
                }
            };
        },
    };
});
wacorpApp.directive('fundraiserFinancialInfoForReRegistration', function ($q) {
    return {
        templateUrl: 'ng-app/directives/CFT/FundraiserFinancialInfoForReRegistration/_FundraiserFinancialInfoForReRegistration.html',
        restrict: 'A',
        scope: {
            financialInfoData: '=?financialInfoData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
            showFinancialHistory: '=?showFinancialHistory',
            financialBtn: '=?financialBtn',
            accDate: '=?accDate'
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope) {
            $scope.isFNameValid = true;
            $scope.isLNameValid = true;
            $scope.checkStartDate = false;
            $scope.messages = messages;
            $scope.Countries = [];
            $scope.States = [];
            $scope.ValidateFinancialEndDateMessage = false;
            $scope.addbuttonName = "Add";
            $scope.currentFinancialObj = {};
            $scope.isMandetory = true;
            $scope.isNewFinInfo = false;
            //$scope.financialInfoData.AccStartDateMoreThanOneYear = true;

            var financialInfoScope = {
                HasOrganizationCompletedFullAccountingYear: false, AccountingYearBeginningDate: "", AccountingYearEndingDate: "", FirstAccountingYearEndDate: "",
                SolicitationComments: "", IsOrganizationCollectedContributionsInWA: false, ContributionServicesTypes: "", ContributionServicesTypeId: "",
                ContributionServicesOtherComments: "", IsRegisteredOutSideOfWashington: false, FinancialInfoStateId: "", FinancialInfoStateDesc: "",
                IsResponsibleForFundraisingInWA: "", BeginningGrossAssets: "", IsContributionServicesOther: false, CFTOfficersList: [],
                //BeginingGrossAssets: null, TotalDollarValueofGrossReceipts: null, EndingGrossAssets: null, ExpensesGDValueofAllExpenditures: null, PercentToProgramServices: null,
                AllContributionsReceived: null, AveragePercentToCharity: null, AmountOfFunds: null, OfficersHighPayList: [], AccStartDateMoreThanOneYear: false,
                OfficersHighPay: {
                    IsPayOfficers: true
                }, CFTFinancialHistoryList: [], BusinessFiling: { FilingTypeName: "" }, AccEndDateLessThanCurrentYear: false,
                shortFiscalYearEntity: {
                    FiscalStartDate: "", FiscalEndDate: "", AllContributionsReceivedForShortFY: null, AveragePercentToCharityForShortFY: null, AmountOfFundsForShortFY: null
                }
            };

            angular.copy($scope.currentFinancialObj, financialInfoScope);

            //For Financial History Validations
            var finHistoryObj = {
                currentYearFinancialObj: {
                    AccountingyearBeginningDate: null, AccountingyearEndingDate: null, AllContributionsReceived: null, AveragePercentToCharity: null, AmountOfFunds: null
                }, HistoryFinancialObj: {
                    AccountingyearBeginningDate: null, AccountingyearEndingDate: null, AllContributionsReceived: null, AveragePercentToCharity: null, AmountOfFunds: null
                },
                financialHistoryList: [], LastAccountingYearEndDate: null
            };

            //if ($scope.financialInfoData != null && $scope.financialInfoData != undefined && $scope.financialInfoData.BusinessFiling != null && $scope.financialInfoData.BusinessFiling != undefined && $scope.financialInfoData.BusinessFiling.FilingTypeName != 'COMMERCIAL FUNDRAISER AMENDMENT') {
            //    $scope.isMandetory = true;
            //}
            //else {
            //    $scope.isMandetory = false;
            //}

            $scope.OfficershighPayData = { ID: '', FirstName: '', LastName: '', SequenceNo: null, Status: '', IsPayOfficers: false, CreatedBy: null };

            $scope.OfficershighPayScopeData = { ID: '', FirstName: '', LastName: '', SequenceNo: null, Status: '', IsPayOfficers: false, CreatedBy: null };

            $scope.financialInfoData = $scope.financialInfoData ? angular.extend(financialInfoScope, $scope.financialInfoData) : angular.copy(financialInfoScope);

            //For Current Financial Info
            $scope.$watchGroup(['financialInfoData.AllContributionsReceived', 'financialInfoData.AmountOfFunds'], function () {

                var value1 = parseFloat($scope.financialInfoData.AmountOfFunds == null || $scope.financialInfoData.AmountOfFunds == '') ? 0 : $scope.financialInfoData.AmountOfFunds;
                var value2 = parseFloat($scope.financialInfoData.AllContributionsReceived == null || $scope.financialInfoData.AllContributionsReceived == '') ? 0 : $scope.financialInfoData.AllContributionsReceived;

                var percentage = null;
                if (value1 && value2)
                    percentage = ((value1 / value2) * 100).toFixed(2);
                else
                    percentage = null;

                if (isNaN(percentage) || percentage === 0)
                    $scope.financialInfoData.AveragePercentToCharity = null;
                else {
                    if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                        $scope.financialInfoData.AveragePercentToCharity = "-" + Math.round(percentage);
                    }
                    else {
                        $scope.financialInfoData.AveragePercentToCharity = Math.round(percentage);
                    }
                }
            }, true);

            //For History Financial Info
            $scope.$watchGroup(['currentFinancialObj.AllContributionsReceived', 'currentFinancialObj.AmountOfFunds'], function () {
                var value1 = parseFloat($scope.currentFinancialObj.AmountOfFunds == null || $scope.currentFinancialObj.AmountOfFunds == '') ? 0 : $scope.currentFinancialObj.AmountOfFunds;
                var value2 = parseFloat($scope.currentFinancialObj.AllContributionsReceived == null || $scope.currentFinancialObj.AllContributionsReceived == '') ? 0 : $scope.currentFinancialObj.AllContributionsReceived;
                var percentage = null;
                if (value1 && value2)
                    percentage = ((value1 / value2) * 100).toFixed(2);
                else
                    percentage = null;

                if (isNaN(percentage) || percentage === 0)
                    $scope.currentFinancialObj.AveragePercentToCharity = null;
                else {
                    if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                        $scope.currentFinancialObj.AveragePercentToCharity = "-" + Math.round(percentage);
                    } else {
                        $scope.currentFinancialObj.AveragePercentToCharity = Math.round(percentage);
                    }
                }
            }, true);

            //For Short Fiscal Financial Info
            $scope.$watchGroup(['financialInfoData.shortFiscalYearEntity.AllContributionsReceivedForShortFY', 'financialInfoData.shortFiscalYearEntity.AmountOfFundsForShortFY'], function () {
                if ($scope.financialInfoData.shortFiscalYearEntity != undefined && $scope.financialInfoData.shortFiscalYearEntity != null) {
                    var value1 = parseFloat($scope.financialInfoData.shortFiscalYearEntity.AmountOfFundsForShortFY == null || $scope.financialInfoData.shortFiscalYearEntity.AmountOfFundsForShortFY == '') ? 0 : $scope.financialInfoData.shortFiscalYearEntity.AmountOfFundsForShortFY;
                    var value2 = parseFloat($scope.financialInfoData.shortFiscalYearEntity.AllContributionsReceivedForShortFY == null || $scope.financialInfoData.shortFiscalYearEntity.AllContributionsReceivedForShortFY == '') ? 0 : $scope.financialInfoData.shortFiscalYearEntity.AllContributionsReceivedForShortFY;
                    var percentage = null;
                    if (value1 && value2)
                        percentage = ((value1 / value2) * 100).toFixed(2);
                    else
                        percentage = null;

                    if (isNaN(percentage) || percentage === 0)
                        $scope.financialInfoData.shortFiscalYearEntity.AveragePercentToCharityForShortFY = null;
                    else {
                        if (value1 != undefined && value2 != undefined && value1.toString().indexOf("-") == 0 && value2.toString().indexOf("-") == 0) {
                            $scope.financialInfoData.shortFiscalYearEntity.AveragePercentToCharityForShortFY = "-" + Math.round(percentage);
                        } else {
                            $scope.financialInfoData.shortFiscalYearEntity.AveragePercentToCharityForShortFY = Math.round(percentage);
                        }
                    }
                }
            }, true);


            //Get Countries List
            $scope.getCountries = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.countriesList(function (response) { $scope.Countries = response.data; });
            };


            //Get States List
            $scope.getStates = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.statesList(function (response) { $scope.States = response.data; });
            };

            $scope.getCountries(); // getCountries method is available in this file only
            $scope.getStates(); // getStates method is available in this file only

            var resultDate = "";
            $scope.CalculateEndDate = function () {
                if ($scope.financialInfoData.AccountingYearBeginningDate != null && $scope.financialInfoData.AccountingYearBeginningDate != "") {
                    var value = $scope.financialInfoData.AccountingYearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultDate = lastDayWithSlashes;
                        $scope.financialInfoData.AccountingYearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.financialInfoData.AccountingYearEndingDate = null;
                    }
                }

                if (typeof ($scope.financialInfoData.AccountingYearBeginningDate) != typeof (undefined) && $scope.financialInfoData.AccountingYearBeginningDate != null) {

                    if ($scope.financialInfoData.AccountingYearBeginningDate && $scope.financialInfoData.LastAccountingYearEndDate) {
                        if (new Date($scope.financialInfoData.AccountingYearBeginningDate) < new Date($scope.financialInfoData.LastAccountingYearEndDate)) {
                            $scope.financialInfoData.AccEndDateLessThanCurrentYear = true;
                        }
                        else {
                            $scope.financialInfoData.AccEndDateLessThanCurrentYear = false;
                        }
                    }
                }

                $scope.CheckEndDate(); // CheckEndDate method is available in this file only
            };

            $scope.CheckEndDate = function () {
                if ($scope.financialInfoData.AccountingYearEndingDate != null && $scope.financialInfoData.AccountingYearBeginningDate != null) {
                    if (new Date($scope.financialInfoData.AccountingYearEndingDate) < new Date($scope.financialInfoData.AccountingYearBeginningDate)) {
                        $scope.ValidateFinancialEndDateMessage = true;
                    }
                    else
                        $scope.ValidateFinancialEndDateMessage = false;
                }
            };

            var resultHistoryDate = "";
            $scope.CalculateHistoryEndDate = function () {
                if ($scope.currentFinancialObj.AccountingYearBeginningDate != null && $scope.currentFinancialObj.AccountingYearBeginningDate != "") {
                    var value = $scope.currentFinancialObj.AccountingYearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultHistoryDate = lastDayWithSlashes;
                        $scope.currentFinancialObj.AccountingYearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idHisEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.currentFinancialObj.AccountingYearEndingDate = null;
                    }
                }
                else {
                    $scope.currentFinancialObj.AccountingYearEndingDate = null;
                }

                //if (typeof ($scope.currentFinancialObj.AccountingYearEndingDate) != typeof (undefined)
                //    && $scope.currentFinancialObj.AccountingYearEndingDate != null) {
                //    if ($scope.currentFinancialObj.AccountingYearEndingDate && $scope.financialInfoData.LastAccountingYearEndDate) {
                //        if (new Date($scope.currentFinancialObj.AccountingYearBeginningDate) < new Date($scope.financialInfoData.LastAccountingYearEndDate)) {
                //            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = true;
                //        }
                //        else {
                //            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                //        }
                //    }
                //}

                if ($scope.currentFinancialObj.AccountingYearBeginningDate != "") {
                    var histotyBegDate = new Date($scope.currentFinancialObj.AccountingYearBeginningDate);
                    if (typeof ($scope.financialInfoData.AccountingYearBeginningDate) != typeof (undefined) && $scope.financialInfoData.AccountingYearBeginningDate != null) {
                        var curretnDate = new Date($scope.financialInfoData.AccountingYearBeginningDate);
                        var curretnEndDate = new Date($scope.financialInfoData.AccountingYearEndingDate);
                        if (histotyBegDate >= curretnDate) {
                            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = true;
                        }
                        else {
                            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                        }
                    }
                }

                $scope.CheckHistoryEndDate(); // CheckHistoryEndDate method is available in this file only
            };

            $scope.CheckHistoryEndDate = function () {
                if ($scope.currentFinancialObj.AccountingYearBeginningDate != null && $scope.currentFinancialObj.AccountingYearBeginningDate != "") {
                    var value = $scope.currentFinancialObj.AccountingYearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultHistoryDate = lastDayWithSlashes;
                        $scope.currentFinancialObj.AccountingYearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idHisEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.currentFinancialObj.AccountingYearEndingDate = null;
                    }
                }
                else {
                    $scope.currentFinancialObj.AccountingYearEndingDate = null;
                }
                if (new Date($scope.currentFinancialObj.AccountingYearEndingDate) < new Date($scope.currentFinancialObj.AccountingYearBeginningDate)) {
                    $scope.ValidateHistoryFinancialEndDateMessage = true;
                }
                else
                    $scope.ValidateHistoryFinancialEndDateMessage = false;
            };

            $scope.ValidateEndDate = function () {
                if (new Date($scope.financialInfoData.AccountingYearEndingDate) < new Date($scope.financialInfoData.AccountingYearBeginningDate)) {
                    $scope.ValidateFinancialEndDateMessage = true;
                }
                else
                    $scope.ValidateFinancialEndDateMessage = false;
            };


            $scope.clearFields = function (flag) {
                if (!flag) {
                    $scope.financialInfoData.isUpdated = false;
                    $scope.financialInfoData.AccountingYearBeginningDate = null;
                    $scope.financialInfoData.AccountingYearEndingDate = null;
                    //$scope.financialInfoData.BeginingGrossAssets = null;
                    $scope.financialInfoData.AllContributionsReceived = null;
                    $scope.financialInfoData.AveragePercentToCharity = null;
                    //$scope.financialInfoData.TotalDollarValueofGrossReceipts = null;
                    $scope.financialInfoData.AmountOfFunds = null;
                    //$scope.financialInfoData.ExpensesGDValueofAllExpenditures = null;
                    //$scope.financialInfoData.EndingGrossAssets = null;
                    //$scope.financialInfoData.PercentToProgramServices = null;
                    $scope.financialInfoData.SolicitationComments = null;
                }
                else {
                    $scope.financialInfoData.isUpdated = true;
                    $scope.financialInfoData.FirstAccountingYearEndDate = null;
                    $scope.financialInfoData.IsShortFiscalYear = false;
                }

            };

            $scope.addOfficerHighPay = function (officerHighPay) {
                $scope.isFNameValid = officerHighPay.FirstName != null && officerHighPay.FirstName != "" && officerHighPay.FirstName != undefined;
                $scope.isLNameValid = officerHighPay.LastName != null && officerHighPay.LastName != "" && officerHighPay.LastName != undefined;
                $scope.hasValues = officerHighPay.FirstName != null && officerHighPay.FirstName != "" && officerHighPay.FirstName != undefined && officerHighPay.LastName != null && officerHighPay.LastName != "" && officerHighPay.LastName != undefined ? true : false;
                if (!$scope.hasValues) {
                    return false;
                }
                else {
                    $scope.ValidateErrorMessage = false;
                    if ($scope.OfficershighPayData.SequenceNo != null && $scope.OfficershighPayData.SequenceNo != '' && $scope.OfficershighPayData.SequenceNo != 0) {
                        angular.forEach($scope.financialInfoData.OfficersHighPayList, function (highpayItem) {
                            if (highpayItem.SequenceNo == $scope.OfficershighPayData.SequenceNo) {
                                angular.copy($scope.OfficershighPayData, highpayItem);
                                $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.financialInfoData.OfficersHighPayList, function (highpayItem) {
                            if (maxId == constant.ZERO || highpayItem.SequenceNo > maxId)
                                maxId = highpayItem.SequenceNo;
                        });
                        $scope.OfficershighPayData.SequenceNo = ++maxId;
                        $scope.OfficershighPayData.Status = principalStatus.INSERT;
                        $scope.financialInfoData.OfficersHighPayList.push($scope.OfficershighPayData);
                        $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only
                    }
                    $scope.resetHighPay(); // resetHighPay method is available in this file only
                }
            };

            $scope.resetHighPay = function () {
                $scope.OfficershighPayData = angular.copy($scope.OfficershighPayScopeData);
                $scope.addbuttonName = "Add";
            }

            $scope.checkHighpayCount = function () {
                $scope.Count = 0;
                angular.forEach($scope.financialInfoData.OfficersHighPayList, function (highpayItem) {

                    if (highpayItem.Status != "D") {
                        $scope.Count++;
                        if ($scope.Count >= 3) {
                            $scope.financialInfoData.OfficersHighPay.IsCountMax = true;
                        }
                        else {
                            $scope.financialInfoData.OfficersHighPay.IsCountMax = false;
                        }
                    }
                });
            };

            $scope.editOfficerHighPay = function (highPayActionData) {
                $scope.OfficershighPayData = angular.copy(highPayActionData);
                $scope.OfficershighPayData.Status = principalStatus.UPDATE;
                $scope.financialInfoData.OfficersHighPay.IsCountMax = false;
                //$scope.IsCountMax = false;
                $scope.addbuttonName = "Update";
            };

            $scope.deleteOfficerHighPay = function (highPayActionData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    if (highPayActionData.ID <= 0) {
                        var index = $scope.financialInfoData.OfficersHighPayList.indexOf(highPayActionData);
                        $scope.financialInfoData.OfficersHighPayList.splice(index, 1);
                    }
                    else
                        highPayActionData.Status = principalStatus.DELETE;

                    $scope.checkHighpayCount(); // checkHighpayCount method is available in this file only
                    //if ($scope.financialInfoData.OfficersHighPayList.length == 0)
                    $scope.resetHighPay(); // resetHighPay method is available in this file only
                });
            };

            //$scope.resetSelection = function () {
            //    if ($scope.financialInfoData.OfficersHighPayList.length > 0) {
            //        wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
            //            angular.forEach($scope.financialInfoData.OfficersHighPayList, function (value, data) {
            //                if (value.ID > 0) {
            //                    value.Status = principalStatus.DELETE;

            //                }
            //                else {
            //                    var index = $scope.financialInfoData.OfficersHighPayList.indexOf(value);
            //                    $scope.financialInfoData.OfficersHighPayList.splice(index);
            //                }
            //            })
            //            $scope.OfficershighPayData.FirstName = '';
            //            $scope.OfficershighPayData.LastName = '';
            //            //$scope.ShowHighPayList = false;
            //            $scope.financialInfoData.OfficersHighPay.IsCountMax = false;
            //        }, function () {
            //            $scope.financialInfoData.IsRegisteredOutSideOfWashington = false;
            //        });
            //    }
            //};


            //CFT Financial History Methods

            $rootScope.$watch('isGlobalEdited', function (val) {
                $scope.isEdited = val;
                $scope.isNewFinInfo = val;
            });


            var addNewFinancialHistory = function () {
                $scope.showForHistoryErrorMessage = true;
                var isExpensesValid = ($scope.currentFinancialObj.AllContributionsReceived < $scope.currentFinancialObj.AmountOfFunds ? false : true);
                var isDatesValid = ((new Date($scope.currentFinancialObj.AccountingYearEndingDate) > new Date($scope.currentFinancialObj.AccountingYearBeginningDate)) ? true : false);
                if ($scope.fundraiserFinancialInfo.divFinHistory.$valid && isExpensesValid && isDatesValid && !$scope.ValidateHistoryFinancialEndDateMessage && !$scope.currentFinancialObj.AccEndDateLessThanCurrentYear) {
                    $scope.showForHistoryErrorMessage = false;
                    var maxId = constant.ZERO;
                    angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (finInfo) {
                        //angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (finInfo) {
                        if (maxId == constant.ZERO || finInfo.SequenceNo > maxId)
                            maxId = finInfo.SequenceNo;
                        //});
                    });
                    var financialInfoObj = {};
                    financialInfoObj.SequenceNo = ++maxId;
                    financialInfoObj.Flag = 'C';
                    financialInfoObj.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingYearBeginningDate;
                    financialInfoObj.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingYearEndingDate;
                    financialInfoObj.AllContributionsReceived = $scope.currentFinancialObj.AllContributionsReceived;
                    financialInfoObj.AveragePercentToCharity = $scope.currentFinancialObj.AveragePercentToCharity;
                    financialInfoObj.AmountOfFunds = $scope.currentFinancialObj.AmountOfFunds;
                    financialInfoObj.Status = principalStatus.INSERT;
                    $scope.financialInfoData.CFTFinancialHistoryList.push(financialInfoObj);

                    $scope.financialInfoData.CFTFinancialHistoryList.sort(function (a, b) {
                        a = new Date(a.AccountingyearEndingDate);
                        b = new Date(b.AccountingyearEndingDate);
                        return a > b ? -1 : a < b ? 1 : 0;
                    });

                    //$scope.financialInfoData.LastAccountingYearEndDate = financialInfoObj.AccountingyearEndingDate;
                    $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                    $scope.clearFinancialInfo();
                    $scope.financialInfoData.NewFinCount = 0;
                    angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (value) {
                        if (value.Flag == 'C') {
                            $scope.financialInfoData.NewFinCount++;
                        }
                    });
                }
            };

            $scope.AddFinancialInfo = function (cftFinancialForm) {
                addNewFinancialHistory(); // addNewFinancialHistory method is available in this file only
            };

            $scope.UpdateFinancialInfo = function () {

                var endDate = $scope.financialInfoData.AccountingYearEndingDate;
                if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                    if (isEndDateMore) {
                        // Folder Name: app Folder
                        // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js
                        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                        return false;
                    }
                }

                if ($scope.currentFinancialObj.AccountingYearBeginningDate != "") {
                    var histotyBegDate = new Date($scope.currentFinancialObj.AccountingYearBeginningDate);
                    if (typeof ($scope.financialInfoData.AccountingYearBeginningDate) != typeof (undefined) && $scope.financialInfoData.AccountingYearBeginningDate != null) {
                        var curretnDate = new Date($scope.financialInfoData.AccountingYearBeginningDate);
                        var curretnEndDate = new Date($scope.financialInfoData.AccountingYearEndingDate);
                        //if (histotyBegDate > curretnDate && histotyBegDate > curretnEndDate) {
                        if (histotyBegDate >= curretnDate) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog("Accounting Year Beginning Date cannot be greater than current Accounting Year");
                            return false;
                        }
                    }
                    else {
                        var curretnDate = new Date();
                        var histotyEndDate = new Date($scope.currentFinancialObj.AccountingYearEndingDate);
                        if (histotyEndDate >= curretnDate) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog("Accounting Year End Date cannot be greater than current date");
                            return false;
                        }
                    }

                    //Editing
                    $scope.showForHistoryErrorMessage = true;
                    var isExpensesValid = ($scope.currentFinancialObj.AllContributionsReceived < $scope.currentFinancialObj.AmountOfFunds ? false : true);
                    var isDatesValid = ((new Date($scope.currentFinancialObj.AccountingYearEndingDate) > new Date($scope.currentFinancialObj.AccountingYearBeginningDate)) ? true : false);
                    if ($scope.fundraiserFinancialInfo.divFinHistory.$valid && isExpensesValid && isDatesValid) {
                        $scope.showForHistoryErrorMessage = false;
                        angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (financialInfoItem) {
                            if (financialInfoItem.SequenceNo == $scope.currentFinancialObj.FinancialSeqNo) {
                                financialInfoItem.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingYearBeginningDate;
                                financialInfoItem.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingYearEndingDate;
                                financialInfoItem.AllContributionsReceived = $scope.currentFinancialObj.AllContributionsReceived;
                                financialInfoItem.AveragePercentToCharity = $scope.currentFinancialObj.AveragePercentToCharity;
                                financialInfoItem.TotalRevenue = $scope.currentFinancialObj.AllContributionsReceived;
                                financialInfoItem.AmountOfFunds = $scope.currentFinancialObj.AmountOfFunds;
                                financialInfoItem.TotalExpenses = $scope.currentFinancialObj.AmountOfFunds;
                                financialInfoItem.Status = principalStatus.UPDATE;
                                //$scope.financialInfoData.isFinInfoChanged =true;
                            }
                        });
                        $scope.financialInfoData.CFTFinancialHistoryList.sort(function (a, b) {
                            a = new Date(a.AccountingyearEndingDate);
                            b = new Date(b.AccountingyearEndingDate);
                            return a > b ? -1 : a < b ? 1 : 0;
                        });
                        $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                        $rootScope.isGlobalEdited = false;
                        $scope.financialInfoData.isUpdated = true;
                        $scope.clearFinancialInfo();
                    }

                    //if ($scope.financialInfoData.CFTFinancialHistoryList.length > 0) {
                    //    var historyFinancialValidationObj = checkFinHistoryValidation();
                    //    historyFinancialValidationObj.then(function (response) {
                    //        if (response.data.isError) {
                    //            wacorpService.alertDialog(response.data.errorMsg);
                    //        }
                    //        else {
                    //            // Paste the Editing Here when required
                    //        }
                    //    }, function (error) { });
                    //}
                }
            };

            // Clear all controls data
            $scope.clearFinancialInfo = function () {
                $scope.currentFinancialObj.AccountingYearBeginningDate = null,
                $scope.currentFinancialObj.AccountingYearEndingDate = null,
                $scope.currentFinancialObj.AllContributionsReceived = null,
                $scope.currentFinancialObj.AveragePercentToCharity = null,
                $scope.currentFinancialObj.AmountOfFunds = null,
                $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false,
                $rootScope.isGlobalEdited = false
                $scope.isNewFinInfo = false;
            };

            $scope.$watch("financialInfoData.AccountingYearEndingDate", function () {
                if (typeof ($scope.financialInfoData.AccountingYearEndingDate) != typeof (undefined) && $scope.financialInfoData.AccountingYearEndingDate != null && $scope.financialInfoData.AccountingYearEndingDate != "") {
                    $scope.accDate = wacorpService.checkAccYearEndDateForReg($scope.financialInfoData.AccountingYearEndingDate, true);
                }
            });

            $scope.getShortYearStartDate = function () {
                if ($scope.financialInfoData.CurrentEndDateForAmendment != null && typeof ($scope.financialInfoData.CurrentEndDateForAmendment) != typeof (undefined)) {
                    $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate = "";
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var startDate = wacorpService.getShortYearStartDate($scope.financialInfoData.CurrentEndDateForAmendment);
                    $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate = wacorpService.dateFormatService(startDate);
                    return $scope.financialInfoData.shortFiscalYearEntity.FiscalStartDate;
                }
            };

            $scope.getShortYearEndDate = function () {
                if ($scope.financialInfoData.AccountingYearBeginningDate != null && typeof ($scope.financialInfoData.AccountingYearBeginningDate) != typeof (undefined)) {
                    $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate = "";
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var endDate = wacorpService.getShortYearEndDate($scope.financialInfoData.AccountingYearBeginningDate);
                    $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate = wacorpService.dateFormatService(endDate);
                    return $scope.financialInfoData.shortFiscalYearEntity.FiscalEndDate;
                }
            };

            //$scope.$watch('financialInfoData.IsShortFiscalYear', function (val) {
            //    if(val) {
            //        if (($scope.financialInfoData.AccountingYearBeginningDate != null && typeof ($scope.financialInfoData.AccountingYearBeginningDate) != typeof (undefined)) && ($scope.financialInfoData.CurrentEndDateForAmendment != null && typeof ($scope.financialInfoData.CurrentEndDateForAmendment) != typeof (undefined))) {
            //            $scope.getShortYearStartDate();
            //            $scope.getShortYearEndDate();
            //        }
            //    }
            //});

            $scope.$watch('financialInfoData.AccountingYearEndingDate', function () {
                if ($scope.financialInfoData.AccountingYearEndingDate != null && typeof ($scope.financialInfoData.AccountingYearEndingDate) != typeof (undefined) && $scope.financialInfoData.BusinessFiling.FilingTypeName == 'COMMERCIAL FUNDRAISER AMENDMENT') {
                    //var isFinSectionMandetory = wacorpService.isFinancialMandetory($scope.financialInfoData.AccountingYearEndingDate);
                    //if ($scope.financialInfoData.BusinessFiling.FilingTypeName != 'COMMERCIAL FUNDRAISER AMENDMENT') {
                    //    $scope.isMandetory = true;
                    //}
                    //else {
                    //    $scope.isMandetory = false;
                    //}
                    var isFinSectionMandetory = false;

                    if (isFinSectionMandetory) {
                        $scope.isMandetory = true;
                    }
                    else {
                        $scope.isMandetory = false;
                    }
                }
            });

            var checkFinHistoryValidation = function () {
                var defer = $q.defer();

                //Current Financial Object
                finHistoryObj.currentYearFinancialObj.AccountingyearBeginningDate = $scope.financialInfoData.AccountingYearBeginningDate;
                finHistoryObj.currentYearFinancialObj.AccountingyearEndingDate = $scope.financialInfoData.AccountingYearEndingDate;
                finHistoryObj.currentYearFinancialObj.AllContributionsReceived = $scope.financialInfoData.AllContributionsReceived;
                finHistoryObj.currentYearFinancialObj.AmountOfFunds = $scope.financialInfoData.AmountOfFunds;
                finHistoryObj.currentYearFinancialObj.AveragePercentToCharity = $scope.financialInfoData.AveragePercentToCharity;

                //History Financial Object
                finHistoryObj.HistoryFinancialObj.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingYearBeginningDate;
                finHistoryObj.HistoryFinancialObj.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingYearEndingDate;
                finHistoryObj.HistoryFinancialObj.AllContributionsReceived = $scope.currentFinancialObj.AllContributionsReceived;
                finHistoryObj.HistoryFinancialObj.AmountOfFunds = $scope.currentFinancialObj.AmountOfFunds;
                finHistoryObj.HistoryFinancialObj.AveragePercentToCharity = $scope.currentFinancialObj.AveragePercentToCharity;

                //Financial History List
                finHistoryObj.financialHistoryList = $scope.financialInfoData.CFTFinancialHistoryList;

                //Last Accounting Year End Date
                finHistoryObj.LastAccountingYearEndDate = $scope.financialInfoData.LastAccountingYearEndDate;

                //Hit to Api for Financial history Date Validations
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.post(webservices.CFT.getCFTFinHistoryValidation, finHistoryObj, function (response) {
                    defer.resolve(response);
                }, function (response) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                    defer.reject(response);
                });

                return defer.promise;

                //$scope.financialInfoData.LastAccountingYearEndDate = financialInfoObj.AccountingyearEndingDate;
                //var isDateExists = false;
                //var isFormatChanged = false;
                //angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (value) {
                //    if (new Date($scope.currentFinancialObj.AccountingYearBeginningDate) >= new Date(value.AccountingyearBeginningDate) && new Date($scope.currentFinancialObj.AccountingYearBeginningDate) <= new Date(value.AccountingyearEndingDate)) {
                //        isDateExists = true;
                //        return false;
                //    }
                //});
                //angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (value) {
                //    var beginDate = new Date(value.AccountingyearBeginningDate);
                //    var endDate = new Date(value.AccountingyearEndingDate);

                //    var currBeginDate = new Date($scope.currentFinancialObj.AccountingYearBeginningDate);
                //    var currEndDate = new Date($scope.currentFinancialObj.AccountingYearEndingDate);
                //    if (currBeginDate.getDate() == beginDate.getDate() && currBeginDate.getMonth() == beginDate.getMonth()) {

                //    }

                //});
                //if (new Date($scope.currentFinancialObj.AccountingYearBeginningDate) <= new Date($scope.financialInfoData.LastAccountingYearEndDate)) {
                //    wacorpService.alertDialog("Accounting Year Beginning Date must be greater than the most recent Fiscal End Date.");
                //    return false;
                //}
                //else if (isDateExists) {
                //    wacorpService.alertDialog("Accounting Information for this year has already been provided.");
                //    return false;
                //}
                //else
                //    return true;
            };

            $scope.AddNewFinInfo = function () {
                $scope.isNewFinInfo = true;
                if ($scope.financialInfoData.CFTFinancialHistoryList.length > 0) {
                    var latestFinancialData = $scope.financialInfoData.CFTFinancialHistoryList[0];
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.currentFinancialObj.AccountingYearBeginningDate = wacorpService.addDaysToGivenDate(latestFinancialData.AccountingyearEndingDate, 1);
                }
                else if ($scope.financialInfoData.AccountingyearEndingDateForFAY != null) {
                    $scope.currentFinancialObj.AccountingYearBeginningDate = wacorpService.addDaysToGivenDate($scope.financialInfoData.AccountingyearEndingDateForFAY, 1);
                }
            };

        },
    };
});

wacorpApp.directive('trustFinancialInfoForReRegistration', function ($rootScope) {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustFinancialInfoForReRegistration/_trustFinancialInfoForReRegistration.html',
        restrict: 'A',
        scope: {
            financialInfoData: '=?financialInfoData',
            showErrorMessage: '=?showErrorMessage',
            isReview: '=?isReview',
            showFinancialHistory: '=?showFinancialHistory',
            financialBtn: '=?financialBtn',
            accDate: '=?accDate'
        },
        controller: function ($scope, lookupService, wacorpService) {
            $scope.messages = messages;
            $scope.IRSDocumentTypes = [];
            $scope.ValidateFinancialEndDateMessage = false;
            $scope.UploadTaxReturnList = [];
            $scope.currentFinancialObj = {};
            $scope.isEdited = false;
            $scope.isNewFinInfo = false;
            var financialInfoScope = {
                IsFIFullAccountingYear: "", AccountingyearBeginningDate: "", AccountingyearEndingDate: "", FirstAccountingyearEndDate: "",
                BeginingGrossAssets: null, TotalRevenue: null, Compensation: null, GrantContributionsProgramService: null, Comments: "", IsFiscalAccountingYearReported: false, FiscalYearReportedType: "",
                TotalExpenses: null, EndingGrossAssets: null, IsDocumentAttached: false, IsFirstAccountingYear: "", FiscalYearOther: "", IRSDocumentId: "", OldIRSDocumentId: "",
                FinancialId: "", UploadTaxReturnList: [], FinancialInfoIRSUploadTypeText: "", CFTFinancialHistoryList: []
            };

            angular.copy($scope.currentFinancialObj, financialInfoScope);

            $scope.financialInfoData = $scope.financialInfoData ? angular.extend(financialInfoScope, $scope.financialInfoData) : angular.copy(financialInfoScope);


            var getIRSDocumentList = function () {
                // Service Folder: services
                // File Name: lookupService.js (you can search with file name in solution explorer)
                lookupService.irsDocumentsList(function (response) { $scope.IRSDocumentTypes = response.data; });
            };

            getIRSDocumentList(); // getIRSDocumentList method is available in this file only

            var resultDate = "";
            $scope.CalculateEndDate = function () {
                if ($scope.financialInfoData.AccountingyearBeginningDate != null && $scope.financialInfoData.AccountingyearBeginningDate != "") {
                    var value = $scope.financialInfoData.AccountingyearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultDate = lastDayWithSlashes;
                        $scope.financialInfoData.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.financialInfoData.AccountingyearEndingDate = null;
                    }
                }

                if (typeof ($scope.financialInfoData.AccountingyearBeginningDate) != typeof (undefined) && $scope.financialInfoData.AccountingyearBeginningDate != null) {
                    if ($scope.financialInfoData.AccountingyearBeginningDate && $scope.financialInfoData.LastAccountingYearEndDate) {
                        if (new Date($scope.financialInfoData.AccountingyearBeginningDate) < new Date($scope.financialInfoData.LastAccountingYearEndDate)) {
                            $scope.financialInfoData.AccEndDateLessThanCurrentYear = true;
                        }
                        else {
                            $scope.financialInfoData.AccEndDateLessThanCurrentYear = false;
                        }
                    }
                }

                $scope.ValidateEndDate(); // ValidateEndDate method is available in this file only
            };

            $scope.ValidateEndDate = function () {
                if ($scope.financialInfoData.AccountingyearEndingDate != null && $scope.financialInfoData.AccountingyearBeginningDate != null) {
                    if (new Date($scope.financialInfoData.AccountingyearEndingDate) < new Date($scope.financialInfoData.AccountingyearBeginningDate)) {
                        $scope.ValidateFinancialEndDateMessage = true;
                    }
                    else
                        $scope.ValidateFinancialEndDateMessage = false;
                }
            };

            var resultHistoryDate = "";
            $scope.CalculateHistoryEndDate = function () {
                if ($scope.currentFinancialObj.AccountingyearBeginningDate != null && $scope.currentFinancialObj.AccountingyearBeginningDate != "") {
                    var value = $scope.currentFinancialObj.AccountingyearBeginningDate;
                    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
                    var result = value.match(rxDatePattern);
                    if (result != null) {
                        var dateValue = new Date(value);
                        dateValue.setYear(dateValue.getFullYear() + 1);
                        var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                        var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                        var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                        resultHistoryDate = lastDayWithSlashes;
                        $scope.currentFinancialObj.AccountingyearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                        $("#idHisEndDate").datepicker("setDate", lastDayWithSlashes);
                    }
                    else {
                        $scope.currentFinancialObj.AccountingyearEndingDate = null;
                    }
                }
                else {
                    $scope.currentFinancialObj.AccountingyearEndingDate = null;
                }

                //if (typeof ($scope.currentFinancialObj.AccountingyearEndingDate) != typeof (undefined)
                //    && $scope.currentFinancialObj.AccountingyearEndingDate != null) {
                //    if ($scope.currentFinancialObj.AccountingyearEndingDate && $scope.financialInfoData.LastAccountingYearEndDate) {
                //        if (new Date($scope.currentFinancialObj.AccountingyearBeginningDate) < new Date($scope.financialInfoData.LastAccountingYearEndDate)) {
                //            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = true;
                //        }
                //        else {
                //            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                //        }
                //    }
                //}

                if ($scope.currentFinancialObj.AccountingyearBeginningDate != "") {
                    var histotyBegDate = new Date($scope.currentFinancialObj.AccountingyearBeginningDate);
                    if (typeof ($scope.financialInfoData.AccountingyearBeginningDate) != typeof (undefined) && $scope.financialInfoData.AccountingyearBeginningDate != null) {
                        var curretnDate = new Date($scope.financialInfoData.AccountingyearBeginningDate);
                        var curretnEndDate = new Date($scope.financialInfoData.AccountingyearEndingDate);
                        if (histotyBegDate >= curretnDate) {
                            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = true;
                        }
                        else {
                            $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                        }
                    }
                }

                $scope.CheckHistoryEndDate(); // CheckHistoryEndDate method is available in this file only
            };

            $scope.CheckHistoryEndDate = function () {
                if (new Date($scope.currentFinancialObj.AccountingyearEndingDate) < new Date($scope.currentFinancialObj.AccountingyearBeginningDate)) {
                    $scope.ValidateHistoryFinancialEndDateMessage = true;
                }
                else
                    $scope.ValidateHistoryFinancialEndDateMessage = false;
            };

            $scope.deleteAllFiles = function (files) {
                if (files.length > constant.ZERO) {
                    files[constant.ZERO].TempFileLocation = "";
                    var fileList = { files: files }
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        // deleteAllUploadedFiles method is available in constants.js
                        wacorpService.post(webservices.Common.deleteAllUploadedFiles, files,
                            function (response) {
                                $scope.financialInfoData.UploadTaxReturnList = [];
                            },
                            function (response) {
                            }
                        );
                    },
                    function () {
                        $scope.financialInfoData.IsFIFullAccountingYear = true;
                    });
                }
            };

            $scope.IRSHistoryChange = function (irsId, docsList, oldIRS) {
                //if (irsId == 0) {
                if ($scope.currentFinancialObj.FinancialIRSDocumentList != undefined && $scope.currentFinancialObj.FinancialIRSDocumentList.length > 0) {
                    // Folder Name: app Folder
                    // Alert Name: filesDeleteConfirm method is available in alertMessages.js
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        angular.forEach($scope.currentFinancialObj.FinancialIRSDocumentList, function (value, data) {
                            if (value.BusinessFilingDocumentId > 0) {
                                value.Status = principalStatus.DELETE;
                            }
                            else {
                                var index = $scope.currentFinancialObj.FinancialIRSDocumentList.indexOf(value);
                                $scope.currentFinancialObj.FinancialIRSDocumentList.splice(index, 1);
                            }

                        });
                    }, function () {
                        $scope.currentFinancialObj.IRSHisDocumentId = oldIRS;
                    });
                }
                else {
                    $scope.currentFinancialObj.FinancialIRSDocumentList = [];
                }
                //}
            };

            $scope.IRSChange = function (irsId, docsList, oldIRS) {
                //if (irsId == 0) {
                if ($scope.financialInfoData.FinancialInfoIRSUpload != undefined && $scope.financialInfoData.FinancialInfoIRSUpload.length > 0) {
                    wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                        angular.forEach($scope.financialInfoData.FinancialInfoIRSUpload, function (value, data) {
                            if (value.BusinessFilingDocumentId > 0) {
                                value.Status = principalStatus.DELETE;
                            }
                            else {
                                var index = $scope.financialInfoData.FinancialInfoIRSUpload.indexOf(value);
                                $scope.financialInfoData.FinancialInfoIRSUpload.splice(index, 1);
                            }

                        });
                        angular.forEach($scope.IRSDocumentTypes, function (doc) {
                            if (doc.Key == $scope.financialInfoData.IRSDocumentId)
                                $scope.financialInfoData.FinancialInfoIRSUploadTypeText = doc.Value;
                        });
                    }, function () {
                        $scope.financialInfoData.IRSDocumentId = oldIRS;
                        angular.forEach($scope.IRSDocumentTypes, function (doc) {
                            if (doc.Key == $scope.financialInfoData.IRSDocumentId)
                                $scope.financialInfoData.FinancialInfoIRSUploadTypeText = doc.Value;
                        });
                    });
                }
                else {
                    $scope.financialInfoData.FinancialInfoIRSUpload = [];
                }
                //}
            };

            $rootScope.$watch('isGlobalEdited', function (val) {
                $scope.isEdited = val;
                $scope.isNewFinInfo = val;
            });

            $scope.AddFinancialInfo = function (cftFinancialForm) {
                $scope.showForHistoryErrorMessage = true;
                var isDatesValid = ((new Date($scope.currentFinancialObj.AccountingyearEndingDate) > new Date($scope.currentFinancialObj.AccountingyearBeginningDate)) ? true : false);
                if ($scope.trustFinancialInfoForm.divFinHistory.$valid && isDatesValid && !$scope.ValidateHistoryFinancialEndDateMessage && !$scope.currentFinancialObj.AccEndDateLessThanCurrentYear && $scope.currentFinancialObj.IRSHisDocumentId != 0 && $scope.currentFinancialObj.FinancialIRSDocumentList.length != 0) {
                    $scope.showForHistoryErrorMessage = false;
                    var maxId = constant.ZERO;
                    angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (finInfo) {
                        if (maxId == constant.ZERO || finInfo.SequenceNo > maxId)
                            maxId = finInfo.SequenceNo;
                    });
                    var financialInfoObj = {};
                    financialInfoObj.SequenceNo = ++maxId;
                    financialInfoObj.Flag = 'C';
                    financialInfoObj.IsFIFullAccountingYear = true;
                    financialInfoObj.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingyearBeginningDate;
                    financialInfoObj.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingyearEndingDate;
                    financialInfoObj.BeginingGrossAssets = $scope.currentFinancialObj.BeginingGrossAssets;
                    financialInfoObj.GrantContributionsProgramService = $scope.currentFinancialObj.GrantContributionsProgramService;
                    financialInfoObj.TotalRevenue = $scope.currentFinancialObj.TotalRevenue;
                    financialInfoObj.EndingGrossAssets = $scope.currentFinancialObj.EndingGrossAssets;
                    financialInfoObj.Compensation = $scope.currentFinancialObj.Compensation;
                    financialInfoObj.TotalExpenses = $scope.currentFinancialObj.TotalExpenses;
                    financialInfoObj.IRSHisDocumentId = $scope.currentFinancialObj.IRSHisDocumentId;
                    financialInfoObj.FinancialIRSDocumentList = $scope.currentFinancialObj.FinancialIRSDocumentList;
                    financialInfoObj.Status = principalStatus.INSERT;
                    $scope.financialInfoData.CFTFinancialHistoryList.push(financialInfoObj);

                    $scope.financialInfoData.CFTFinancialHistoryList.sort(function (a, b) {
                        a = new Date(a.AccountingyearEndingDate);
                        b = new Date(b.AccountingyearEndingDate);
                        return a > b ? -1 : a < b ? 1 : 0;
                    });

                    $scope.financialInfoData.LastAccountingYearEndDate = financialInfoObj.AccountingyearEndingDate;
                    $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                    $scope.clearFinancialInfo();
                }

                $scope.financialInfoData.NewFinCount = 0;
                angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (value) {
                    if (value.Flag == 'C') {
                        $scope.financialInfoData.NewFinCount++;
                    }
                });
            };

            $scope.UpdateFinancialInfo = function () {

                var endDate = $scope.financialInfoData.AccountingyearEndingDate;
                if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                    if (isEndDateMore) {
                        // Folder Name: app Folder
                        // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js
                        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                        return false;
                    }
                }

                if ($scope.currentFinancialObj.IsFIFullAccountingYear) {
                    if ($scope.currentFinancialObj.AccountingyearBeginningDate != "" || $scope.currentFinancialObj.AccountingyearBeginningDate != null) {
                        var histotyBegDate = new Date($scope.currentFinancialObj.AccountingyearBeginningDate);
                        var histotyEndDate = new Date($scope.currentFinancialObj.AccountingyearEndingDate);
                        if (typeof ($scope.financialInfoData.AccountingyearBeginningDate) != typeof (undefined) && $scope.financialInfoData.AccountingyearBeginningDate != null) {
                            var curretnDate = new Date($scope.financialInfoData.AccountingyearBeginningDate);
                            var curretnEndDate = new Date($scope.financialInfoData.AccountingyearEndingDate);
                            //if (histotyBegDate > curretnDate && histotyBegDate > curretnEndDate) {
                            if (histotyBegDate >= curretnDate) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                wacorpService.alertDialog("Accounting Year Beginning Date cannot be greater than current Accounting Year");
                                return false;
                            }
                        }
                        else {
                            var curretnDate = new Date();
                            var histotyEndDate = new Date($scope.currentFinancialObj.AccountingyearEndingDate);
                            if (histotyEndDate >= curretnDate) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                wacorpService.alertDialog("Accounting Year End Date cannot be greater than current date");
                                return false;
                            }
                        }
                    }
                    $scope.showForHistoryErrorMessage = true;
                    var isDatesValid = ((new Date($scope.currentFinancialObj.AccountingyearEndingDate) > new Date($scope.currentFinancialObj.AccountingyearBeginningDate)) ? true : false);
                    if ($scope.trustFinancialInfoForm.divFinHistory.$valid && isDatesValid && $scope.currentFinancialObj.IRSHisDocumentId != 0 && $scope.currentFinancialObj.FinancialIRSDocumentList.length != 0) {
                        $scope.showForHistoryErrorMessage = false;
                        angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (financialInfoItem) {
                            if (financialInfoItem.SequenceNo == $scope.currentFinancialObj.FinancialSeqNo) {
                                financialInfoItem.IsFIFullAccountingYear = true;
                                financialInfoItem.AccountingyearBeginningDate = $scope.currentFinancialObj.AccountingyearBeginningDate;
                                financialInfoItem.AccountingyearEndingDate = $scope.currentFinancialObj.AccountingyearEndingDate;
                                financialInfoItem.BeginingGrossAssets = $scope.currentFinancialObj.BeginingGrossAssets;
                                financialInfoItem.GrantContributionsProgramService = $scope.currentFinancialObj.GrantContributionsProgramService;
                                financialInfoItem.TotalRevenue = $scope.currentFinancialObj.TotalRevenue;
                                financialInfoItem.EndingGrossAssets = $scope.currentFinancialObj.EndingGrossAssets;
                                financialInfoItem.Compensation = $scope.currentFinancialObj.Compensation;
                                financialInfoItem.TotalExpenses = $scope.currentFinancialObj.TotalExpenses;
                                financialInfoItem.IRSHisDocumentId = $scope.currentFinancialObj.IRSHisDocumentId;
                                financialInfoItem.FinancialIRSDocumentList = $scope.currentFinancialObj.FinancialIRSDocumentList;
                                $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                                financialInfoItem.Status = principalStatus.UPDATE;
                            }
                        });
                        $scope.financialInfoData.CFTFinancialHistoryList.sort(function (a, b) {
                            a = new Date(a.AccountingyearEndingDate);
                            b = new Date(b.AccountingyearEndingDate);
                            return a > b ? -1 : a < b ? 1 : 0;
                        });
                        $rootScope.isGlobalEdited = false;
                        $scope.financialInfoData.isUpdated = true;
                        $scope.clearFinancialInfo(); // clearFinancialInfo method is available in this file only
                    }
                }
                else {
                    $scope.showForHistoryErrorMessage = true;
                    if ($scope.trustFinancialInfoForm.divFinHistory.$valid) {
                        $scope.showForHistoryErrorMessage = false;
                        angular.forEach($scope.financialInfoData.CFTFinancialHistoryList, function (financialInfoItem) {
                            if (financialInfoItem.SequenceNo == $scope.currentFinancialObj.FinancialSeqNo) {
                                financialInfoItem.IsFIFullAccountingYear = false;
                                financialInfoItem.FirstAccountingyearEndDate = $scope.currentFinancialObj.FirstAccountingyearEndDate;
                                financialInfoItem.BeginingGrossAssets = $scope.currentFinancialObj.BeginingGrossAssets;
                                financialInfoItem.Status = principalStatus.UPDATE;
                            }
                        });
                        $rootScope.isGlobalEdited = false;
                        $scope.financialInfoData.isUpdated = true;
                        $scope.clearFinancialInfo(); // clearFinancialInfo method is available in this file only
                    }
                }
            };

            // Clear all controls data
            $scope.clearFinancialInfo = function () {
                $scope.currentFinancialObj.AccountingyearBeginningDate = null;
                $scope.currentFinancialObj.AccountingyearEndingDate = null;
                $scope.currentFinancialObj.FirstAccountingyearEndDate = null;
                $scope.currentFinancialObj.BeginingGrossAssets = null;
                $scope.currentFinancialObj.GrantContributionsProgramService = null;
                $scope.currentFinancialObj.TotalRevenue = null;
                $scope.currentFinancialObj.EndingGrossAssets = null;
                $scope.currentFinancialObj.Compensation = null;
                $scope.currentFinancialObj.TotalExpenses = null;
                $scope.currentFinancialObj.IRSHisDocumentId = 0;
                $scope.currentFinancialObj.FinancialIRSDocumentList = [];
                $rootScope.isGlobalEdited = false
                $scope.currentFinancialObj.AccEndDateLessThanCurrentYear = false;
                $scope.isNewFinInfo = false;
            };

            $scope.$watch("financialInfoData.AccountingyearEndingDate", function () {
                if (typeof ($scope.financialInfoData.AccountingyearEndingDate) != typeof (undefined) && $scope.financialInfoData.AccountingyearEndingDate != null && $scope.financialInfoData.AccountingyearEndingDate != "") {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.accDate = wacorpService.checkAccYearEndDateForReg($scope.financialInfoData.AccountingyearEndingDate, true);
                }
            });

            $scope.AddNewFinInfo = function () {
                $scope.isNewFinInfo = true;
                $scope.currentFinancialObj.IsFIFullAccountingYear = true;
                if ($scope.financialInfoData.CFTFinancialHistoryList.length > 0) {
                    var latestFinancialData = $scope.financialInfoData.CFTFinancialHistoryList[0];
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    if (latestFinancialData.IsFIFullAccountingYear) {
                        $scope.currentFinancialObj.AccountingyearBeginningDate = wacorpService.addDaysToGivenDate(latestFinancialData.AccountingyearEndingDate, 1);
                    }
                    else {
                        $scope.currentFinancialObj.AccountingyearBeginningDate = wacorpService.addDaysToGivenDate(latestFinancialData.AccountingyearEndingDateForFAY, 1);
                    }
                }
            };
        },
    };
});

wacorpApp.directive('commonEntityInformation', function () {
    return {
        templateUrl: 'ng-app/directives/EntityInformation/EntityInformation.html',
        restrict: 'A',
        scope: {
            entityData: '=?entityData',
            isReview: '=?isReview',
            sectionName: '=?sectionName',
            isStatementOfWithdrawal: '=?isStatementOfWithdrawal',
        },
        controller: function ($scope, wacorpService, $rootScope) {
            var businessInformationScope = {
                UBINumber: null,
                BusinessName: null,
                BusinessNameSearch: null,
                NewBusinessName: null,
                BusinessID: null,
                BusinessIDs: null,
                DBABusinessName: null,
                NewDBABusinessName: null,
                BusinessType: null,
                AmendedBusinessType: null,
                AmendedBusinessTypeDesc: null,
                BusinessCategoryID: null,
                BusinessCategory: null,
                BusinessTypeID: null,
                DurationType: null,
                DurationYears: null,
                IsPerpetual: false,
                DurationExpireDate: null,
                NextARDueDate:null,
                EffectiveDate: null,
                EffectiveDateType: null,
                AvailableStatus: null,
                FilingDate: null,
                Jurisdiction: null,
                JurisdictionDesc: null,
                OldJurisdictionDesc: null,
                BusinessStatusID: null,
                NewBusinessStatusID: null,
                BusinessStatus: null,
                JurisdictionState: null,
                JurisdictionCountry: null,
                JurisdictionStateDesc: null,
                JurisdictionCountryDesc: null,
                JurisdictionCategory: null,
                InActiveDate: null,
                BINAICSCode:null,
                BINAICSCodeDesc :null,
                BIOtherDescription: null,
                IsHostHome:null,
                IsPublicBenefitNonProfit:null,
                IsCharitableNonProfit:null,
                IsGrossRevenueNonProfit:null,
                HasMemberNonProfit:null,
                FEINNo: null,
                ExistingIsHostHome: null,
                ExistingIsPublicBenefitNonProfit: null,
                ExistingIsCharitableNonProfit: null,
                ExistingIsGrossRevenueNonProfit: null,
                ExistingHasMemberNonProfit: null,
                PrincipalMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
                PrincipalStreetAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                    }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                }, IsSameAsMailingAddress: false, BusinessID: constant.ZERO, Status: null, MemberOrManager: constant.ZERO, IsPrincipalOfficeNotInWa: false,
            };
            $scope.entityData = $scope.entityData ? angular.extend(businessInformationScope, $scope.entityData) : angular.copy(businessInformationScope);
        },
    }
});
wacorpApp.directive('ubiNumber', function () {
    return {
        templateUrl: 'ng-app/directives/UBINumber/UBINumber.html',
        restrict: 'A',
        transclude: true,
        scope: {
            entityModal: '=?entityModal',
            showErrorMessage: '=showErrorMessage',
            isForeign: '=?isForeign',
            isDomestic:'=?isDomestic'

        },
        controller: function ($scope, wacorpService, $rootScope, $timeout) {
            $scope.entityModal.OnlineIsUBIChecked = false;
            $scope.isForeign = $scope.isForeign || false;
            $scope.isDomestic = $scope.isDomestic || false;
            $scope.businessName = "";
            $scope.dbaBusinessame = "";
            $scope.showHideSection = function () {
                var flag = $scope.ubiModel && $scope.ubiModel == 'Y';
                
                if (!flag) {
                    $scope.entityModal.entityList = '';
                    //$scope.validateUbiNumber = true;
                    $rootScope.isLookUpClicked = false;
                    $rootScope.isUseClicked = false;
                }
                else {
                    if (flag && ($scope.entityModal.UBINumber == undefined || $scope.entityModal.UBINumber == null || $scope.entityModal.UBINumber == ""))
                    {
                        $scope.entityModal.validateUbiNumber = false;
                        $rootScope.isLookUpClicked = false;
                        $scope.isUseClicked = false;
                    }
                }
                //else
                //    $scope.validateUbiNumber = true;
                $scope.entityModal.isValidUBI = flag;
                $scope.entityModal.OnlineIsUBIChecked = false;
                $scope.entityModal.IsDomesticUBI = false;
                $scope.entityModal.UBINumber = null;
                $scope.entityModal.OnlineLookupUBINo = "";
            }
            $scope.entityModal.entityList = [];
            $scope.messages = messages;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.entityModal.UBIBusinessType = '';
            $scope.ubiModel = ($scope.entityModal.UBINumber == null || $scope.entityModal.UBINumber == '' || $scope.entityModal.UBINumber == undefined ? 'N' : 'Y');
            //var ubi = $scope.entityModal.UBINumber ? $scope.entityModal.UBINumber.replace(/ /g, ''): $scope.entityModal.UBINumber;
            $scope.entityModal.IsnotValidUBI = false;
            $scope.searchUBINumber = function () {
                $timeout($scope.searchUBINumbercall);
            };
            $scope.searchUBINumbercall = function () {
               
                $scope.entityModal.IsnotValidUBI = false;
                $scope.entityModal.OnlineIsUBIChecked = false;
                $scope.entityModal.IsDomesticUBI = false;
                $scope.entityModal.DisableUBI = false;
                $scope.entityModal.UBIBusinessTypeID = 0;
                //$scope.showErrorMessage = true;
                $scope.entityModal.entityList = [];
                if ($scope.entityModal.UBINumber == null || $scope.entityModal.UBINumber.length < 9) {
                    $scope.entityModal.IsnotValidUBI = true;
                    $scope.showErrorMessage = true;
                    return false;
                }
                if ($scope.entityModal.UBINumber != typeof (undefined) && $scope.entityModal.UBINumber != null && $scope.entityModal.UBINumber != '') {
                    //$scope.showErrorMessage = false;
                        $scope.entityModal.OnlineLookupUBINo = $scope.entityModal.UBINumber;
                        var config = {
                            params: { UBINumber: $scope.entityModal.UBINumber }
                        };
                    // GetUBINUmber method is available in constants.js
                        wacorpService.get(webservices.Common.GetUBINUmber, config, function (response) {
                            $scope.entityModal.entityList = response.data;
                            if ($scope.entityModal.entityList.length > 0)
                            {
                                angular.forEach($scope.entityModal.entityList, function (value, key) {
                                    $scope.entityModal.UBIBusinessType = value.UBIBusinessType;
                                    $scope.entityModal.BusinessCategoryID = value.BusinessCategoryID;
                                    $scope.entityModal.UBIBusinessTypeID = value.BusinessTypeID;
                                    $scope.businessName = value.BusinessName;
                                    $scope.dbaBusinessame = value.DBABusinessName;
                                    $rootScope.isLookUpClicked = false;
                                    $rootScope.isUseClicked = true;
                                    $scope.entityModal.validateUbiNumber = false;
                                    $scope.isUseClicked = true;
                                })
                            }
                            else {
                                $rootScope.isLookUpClicked = false;
                                $rootScope.isUseClicked = false;
                                $scope.entityModal.validateUbiNumber = false;
                            }
                            
                            //$scope.entityModal.BusinessName = "";
                            //$scope.entityModal.UBINumber = '';
                        }, function (response) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog(response.data.Message);
                        });
                    }
            }
            $scope.bindUBIToEntityName = function (buisnessname, ubi, ubiBusinessType, UBIBusinessTypeID, businessStatusID) {
                if ($scope.entityModal.BusinessType != '' && $scope.entityModal.BusinessType.indexOf('WA ') > -1) {
                    // here UBIBusinessTypeID = 101 is Unregistered Corporations
                    if (UBIBusinessTypeID == 101)
                    {
                        // return true;
                        //no need of any validation
                        $scope.entityModal.DisableUBI = true;
                        $scope.isUseClicked = false;
                        $rootScope.isUseClicked = false;
                    }
                    else
                    {
                        // Folder Name: app Folder
                        // Alert Name: DomesticUBI method is available in alertMessages.js 
                        wacorpService.alertDialog(messages.DomesticUBI);
                        $rootScope.isLookUpClicked = true;
                        $rootScope.isUseClicked = true;
                        $scope.entityModal.validateUbiNumber = true;
                            $scope.entityModal.DisableUBI = false;
                        return false;
                    }
                }
                else
                {
                    // here BusinessCategoryID = 5 is FOREIGN ENTITY
                    if (UBIBusinessTypeID || $scope.entityModal.BusinessCategoryID == 5) {
                        //return true;
                        //no need of any validation
                        if (UBIBusinessTypeID == 101 || businessStatusID == 11) {
                            $scope.entityModal.DisableUBI = true;
                            $scope.isUseClicked = false;
                            $rootScope.isUseClicked = false;
                        }
                        else {
                            // Folder Name: app Folder
                            // Alert Name: ForeignUBI method is available in alertMessages.js 
                            wacorpService.alertDialog(messages.DomesticUBI);
                            $rootScope.isLookUpClicked = true;
                            $rootScope.isUseClicked = true;
                            $scope.entityModal.validateUbiNumber = true;
                                $scope.entityModal.DisableUBI = false;

                            //wacorpService.alertDialog('The given UBI number is associated with a domestic business. Please provide foreign UBI number.');
                            return false;
                        }
                    }
                    else {
                        // Folder Name: app Folder
                        // Alert Name: ForeignUBI method is available in alertMessages.js 
                        wacorpService.alertDialog(messages.DomesticUBI);
                        $scope.entityModal.DisableUBI = false;
                        //wacorpService.alertDialog('The given UBI number is associated with a domestic business. Please provide foreign UBI number.');
                        return false;
                    }
                }
                $scope.entityModal.BusinessName = buisnessname;
                $scope.entityModal.DBABusinessName = $scope.dbaBusinessame;
                $scope.entityModal.UBINumber = ubi.replace(/ /g,'');
                $scope.entityModal.UBIBusinessType = ubiBusinessType;
                $scope.isUBIDisable = true;
                $scope.clicked = true;

                $timeout(function () { 
                    if (!$scope.clicked) {
                        return;
                    }
                    var flag = "";
                    if ($scope.entityModal.DBABusinessName != undefined && $scope.entityModal.DBABusinessName != null && $scope.entityModal.DBABusinessName != "")
                         flag = true;
                    else if ($scope.entityModal.BusinessName != undefined && $scope.entityModal.BusinessName != null && $scope.entityModal.BusinessName!="")
                        flag = false;

                    $rootScope.$broadcast("InvokeBusinessNameLookUp",flag);
                    //$("#id-txtBusiessName").trigger("blur");
                })
            }

            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    //$scope.UBINumber = pastedText;
                    $scope.entityModal.UBINumber  = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        //$scope.UBINumber = pastedText;
                        $scope.entityModal.UBINumber  = pastedText;
                    });
                }
            };

            $scope.setUBILength = function (e) {
                //if (e.currentTarget.value.length >= 9) {
                //    e.preventDefault();
                //}
                if ($scope.entityModal.UBINumber != undefined && $scope.entityModal.UBINumber != null && $scope.entityModal.UBINumber!="" && $scope.entityModal.UBINumber.length >= 9) {
                    // Allow: backspace, delete, tab, escape, enter and .
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                        // Allow: Ctrl+A, Command+A
                        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                        // Allow: home, end, left, right, down, up
                        (e.keyCode >= 35 && e.keyCode <= 40)) {
                        // let it happen, don't do anything
                        return;
                    }
                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                    }
                    e.preventDefault();
                }
            };

            $scope.checkIsLooKUp = function (data) {
                 
                if (data != undefined && data != null && data != "") {
                $rootScope.isLookUpClicked = true;
                $rootScope.isUseClicked = true;
                    $scope.entityModal.validateUbiNumber = true;
            }
                else {
                    $rootScope.isLookUpClicked = false;
                    $rootScope.isUseClicked = false;
                    $scope.entityModal.validateUbiNumber = false;
                }
                
            }

            var checkUBIUsage = $rootScope.$on("checkUBIUse", function (evnt,data) {
                if (!$rootScope.isLookUpClicked && !$rootScope.isUseClicked)
                      $rootScope.isLookUpClicked = true;
                //if (!$rootScope.isUseClicked)
                //      $rootScope.isUseClicked = true;
                if(data!=undefined && data!=null && data!="")
                    $scope.entityModal.validateUbiNumber = true; 
            });

            $scope.$on('$destroy', function () {

                checkUBIUsage(); 
            });
        }
    }
});
wacorpApp.directive('globalUpload', function ($http) {
    return {
        templateUrl: 'ng-app/directives/GlobalUpload/globalUpload.html',
        restrict: 'A',
        scope: {
            modalName: '=?modalName',
            sectionName: '=?sectionName',
            isReview: '=?isReview',
            uploadList: '=?uploadList',
            uploadData: '=?uploadData',
            showErrorMessage: '=?showErrorMessage',
            fileSize: '=?fileSize',
            fileType: '=?fileType',
            validateFileType: '=?validateFileType',
            validateFileSize: '=?validateFileSize',
            isCorporation: '=?isCorporation',
            note: '=?note',
        },
        controller: function ($scope, $http, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.modalName = $scope.modalName || '';
            $scope.sectionName = $scope.sectionName || '';
            $scope.isReview = $scope.isReview || false;
            $scope.uploadList = $scope.uploadList || [];
            $scope.uploadData = $scope.uploadData || {};
            $scope.uploadData.IsAdditionalDocumentsExist = angular.isNullorEmpty($scope.uploadData.IsAdditionalDocumentsExist) ? true : $scope.uploadData.IsAdditionalDocumentsExist;
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.note = angular.isNullorEmpty($scope.note) ? "" : $scope.note;
            $scope.fileSize = angular.isNullorEmpty($scope.fileSize) ? uploadedFiles.FILESIZE : $scope.fileSize;
            $scope.fileType = angular.isNullorEmpty($scope.fileType) ? uploadedFiles.FILETYPES : $scope.fileType;
            $scope.validateFileType = angular.isNullorEmpty($scope.validateFileType) ? true : $scope.validateFileType;
            $scope.validateFileSize = angular.isNullorEmpty($scope.validateFileSize) ? true : $scope.validateFileSize;
            $scope.fileSizeMessage = $scope.messages.UploadFiles.fileSizeNote.replace('{0}', ($scope.fileSize / (uploadedFiles.FILESIZEMB)));
            $scope.fileTypeMessage = ($scope.fileType.toString() == 'NONE' || $scope.fileType.toString() == '') ? "" : $scope.messages.UploadFiles.fileTypeNote.replace('{0}', $scope.fileType.toString());
            $scope.DocumentTypes = [];
            $scope.DocumentType = $scope.DocumentType || "";
            $scope.DocumentTypeId = $scope.DocumentTypeId || "";
            $scope.isCorporation = angular.isNullorEmpty($scope.isCorporation) ? true : $scope.isCorporation;

            //$scope.selectedDocumentType = function (items, selectedVal) {
            //    var result = "";
            //    angular.forEach(items, function (item) {
            //        if (selectedVal == item.Key) {
            //            result = item.Value;
            //        }
            //    });
            //    return result;
            //}
           
            //if ($scope.isCorporation) {
            //    var lookupDocumentParams = { params: { name: 'UploadDocumentType' } };
            //    wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupDocumentParams, function (response) {
            //        $scope.DocumentTypes = response.data;
            //    }, function (response) {
            //    });

            //    $scope.changeDocumentType = function (DocumentTypeId) {
            //        $scope.DocumentType = $scope.selectedDocumentType($scope.DocumentTypes, DocumentTypeId);
            //        $scope.DocumentTypeId = DocumentTypeId;
            //    };
            //} else {
            //    var lookupDocumentParams = { params: { name: 'CharityUploadDocumentType' } };
            //    wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupDocumentParams, function (response) {
            //        $scope.DocumentTypes = response.data;
            //    }, function (response) {
            //    });

            //    $scope.changeDocumentType = function (DocumentTypeId) {
            //        $scope.DocumentType = $scope.selectedDocumentType($scope.DocumentTypes, DocumentTypeId);
            //        $scope.DocumentTypeId = DocumentTypeId;
            //    };
            //}

            $scope.$watch(function () {

                $scope.UploadLableText = $scope.sectionName.replace($scope.sectionName.split(' ')[0], '').trim();

                $scope.uploadConfirmation = $scope.messages.UploadFiles.uploadFilesSectionConfirmation.replace('{0}', $scope.sectionName != "" && $scope.sectionName.indexOf("Upload") >= 0 ? $scope.sectionName.slice(6) : $scope.sectionName);
                $scope.uploadText = "";
                if ($scope.modalName == uploadedFiles.ARTICLESOFINCORPORATIONMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.articleUploadText;
                else if ($scope.modalName == uploadedFiles.CERTIFICATEOFFORMATIONMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.certificateofFormationUploadText;
                else if ($scope.modalName == uploadedFiles.CLEARANCECERTIFICATEMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.clearanceCertificateUploadText;
                else if ($scope.modalName == uploadedFiles.CERTIFICATEOFEXISTENCEMODAL)
                    $scope.uploadText = $scope.messages.UploadFiles.certificateOfExistenceUploadText;
                else
                    $scope.uploadText = $scope.sectionName;
            });

            // NOW UPLOAD THE FILES.
            $scope.upload = function (e) {
                var validFormats = $scope.fileType;
                $scope.files = [];
                $scope.$apply(function () {
                    for (var i = constant.ZERO; i < e.files.length; i++) {
                        $scope.files.push(e.files[i])
                    }
                });
                var data = new FormData();
                var selectedFiles = [];
                for (var i in $scope.files) {
                    data.append("uploadedFile", $scope.files[i]);

                    var value = $scope.files[i];
                    if (value.name != "") {
                        var fileInfo = {
                            extenstion: value.name.substring(value.name.lastIndexOf('.') + constant.ONE).toLowerCase(),
                            size: value.size,
                        };
                        selectedFiles.push(fileInfo);
                    }
                }
                angular.forEach(selectedFiles, function (file) {
                    var fileTypeindex = constant.ZERO, filesizeValid = true, formatValid = false;
                    if ($scope.validateFileType) {
                        angular.forEach(validFormats, function (item) {
                            if (item.replace(/\s/g, '') == file.extenstion) {
                                formatValid = true;
                            }
                        });
                        fileTypeindex = formatValid ? 1 : -1;
                    }
                    if ($scope.validateFileSize)
                        filesizeValid = file.size <= $scope.fileSize;
                    if (fileTypeindex > constant.NEGATIVE && filesizeValid) {
                        if ($rootScope.repository.loggedUser != undefined)
                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                        var uri = webservices.Common.fileUpload + '?DocumentType=' + $scope.DocumentType + '&DocumentTypeId=' + $scope.DocumentTypeId + '&FullUserName=' + ($rootScope.repository.loggedUser != undefined ? $rootScope.repository.loggedUser.FullUserName : '');
                        $http({
                            url: uri,
                            method: "POST",
                            cache: false,
                            data: data,
                            transformRequest: angular.identity,
                            headers: {
                                'Content-Type': undefined
                            }
                        }).success(function (result) {
                            $scope.uploadList.push(result[constant.ZERO]);
                            
                            //for (i = 0; i < $scope.uploadList.length; i++)
                            //{
                            //    var number = parseInt(i) + parseInt(1);
                            //    $scope.uploadList[i].UploadFileName = $scope.uploadData.BusinessFiling != undefined ? $scope.uploadData.BusinessFiling.FilingTypeName : $scope.uploadData.FilingType + " " + number;
                            //}

                            //angular.forEach($scope.DocumentTypes, function (item) {
                            //    if ($scope.DocumentType == item.Value) {
                            //        $scope.DocumentTypeId = "";
                            //    }
                            //});
                            //$scope.DocumentTypeId = "";


                        }).error(function (result, status) {
                            // Folder Name: app Folder
                            // Alert Name: uploadFailed method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.uploadFailed);
                        });
                        $scope.filenotSupported = "";
                    }
                    else {
                        if (fileTypeindex == constant.NEGATIVE)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (fileTypeindex == constant.NEGATIVE && file.size > $scope.fileSize)
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileNotSupport.replace('{0}', validFormats.toString());
                        else if (file.size > $scope.fileSize) {
                            var size = ($scope.fileSize / (uploadedFiles.FILESIZEMB));
                            $scope.filenotSupported = $scope.messages.UploadFiles.fileSizeNotSupport.replace('{0}', size);
                        }
                    }
                });

                angular.element(e).val(null);
            }

            $scope.deleteFile = function (file, index) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                    // deleteUploadedFile method is avialable in constants.js
                    wacorpService.post(webservices.Common.deleteUploadedFile, file,
                        function (response) {
                            //var index = $scope.uploadList.indexOf(response);
                            $scope.uploadList.splice(index, constant.ONE);
                            // Folder Name: app Folder
                            // Alert Name: fileDelete method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDelete);
                            if ($scope.uploadList.length == 0) {
                                $scope.uploadList = [];
                            }
                        },
                        function (response) {
                            // Folder Name: app Folder
                            // Alert Name: fileDeleteFailed method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.UploadFiles.fileDeleteFailed);
                        }
                    );
                });
            };

            $scope.deleteGlobalAllFiles = function (files) {
                if (files.length > 0) {
                    //files[constant.ZERO].TempFileLocation = "";
                    if (files.length > constant.ZERO) {
                        var fileList = { files: files }
                        // Folder Name: app Folder
                        // Alert Name: filesDeleteConfirm method is available in alertMessages.js 
                        wacorpService.confirmDialog($scope.messages.UploadFiles.filesDeleteConfirm, function () {
                            // deleteAllUploadedFiles method is available in constants.js
                            wacorpService.post(webservices.Common.deleteAllUploadedFiles, files,
                                function (response) {
                                    $scope.uploadList = [];
                                },
                                function (response) {
                                }
                            );
                        },
                        function () {
                            $scope.uploadData.IsAdditionalDocumentsExist = true;
                        });
                    }
                }
            };

            $scope.globalUploadClick = function () {
                var uploadID = $scope.modalName + '_UploadGlobalFile';
                $('#' + uploadID).trigger('click');
            };

        },

    };
});
wacorpApp.directive('cftfinancialhistory', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/CFTFinancialHistory/_CFTFinancialHistory.html',
        restrict: 'A',
        scope: {
            isHistory: '=?isHistory',
            financialData: '=?financialData',
            currentData: '=?currentData'
            //isEdited: '=?isEdited',
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.isHistory = $scope.isHistory || false;
            $scope.financialData.CFTFinancialHistoryList = $scope.financialData.CFTFinancialHistoryList || [];
            //$scope.isEdited = $scope.isEdited || false;

            var FinancialInfoScope = {
                IsFIFullAccountingYear: false,
                AccountingyearBeginningDate: null,
                AccountingyearEndingDate: null,
                FirstAccountingyearEndDate: null,
                BeginingGrossAssets: null,
                RevenueGDfromSolicitations: null,
                RevenueGDRevenueAllOtherSources: null,
                TotalDollarValueofGrossReceipts: null,
                ExpensesGDExpendituresProgramServices: null,
                ExpensesGDValueofAllExpenditures: null,
                EndingGrossAssets: null,
                PercentToProgramServices: null,
                Comments: null,
                CFTFinancialHistoryList: []
            };

            //$scope.financialData = $scope.financialData ? angular.extend(FinancialInfoScope, $scope.financialData) : angular.copy(FinancialInfoScope);
            $scope.financialData = $scope.financialData ;

            $scope.$watch('financialData.CFTFinancialHistoryList', function () {
                angular.forEach($scope.financialData.CFTFinancialHistoryList, function (fiscalInfo) {
                    //fiscalInfo.AccountingyearBeginningDate = wacorpService.dateFormatService(fiscalInfo.AccountingyearEndingDate);
                    //fiscalInfo.AccountingyearEndingDate = wacorpService.dateFormatService(fiscalInfo.AccountingyearEndingDate);
                });

            }, true);

            //Edit fundraiser Financial Info
            $scope.editFinancialInfo = function (financialItem) {
                $scope.currentData.FinancialSeqNo = financialItem.SequenceNo;
                $scope.currentData.FinancialId = financialItem.FinancialId;
                $scope.currentData.IsFIFullAccountingYear = financialItem.IsFIFullAccountingYear;
                $scope.currentData.AccountingyearBeginningDate = wacorpService.dateFormatService(financialItem.AccountingyearBeginningDate);
                $scope.currentData.AccountingyearEndingDate = wacorpService.dateFormatService(financialItem.AccountingyearEndingDate);
                $scope.currentData.BeginingGrossAssets = financialItem.BeginingGrossAssets;
                $scope.currentData.RevenueGDfromSolicitations = financialItem.RevenueGDfromSolicitations;
                $scope.currentData.RevenueGDRevenueAllOtherSources = financialItem.RevenueGDRevenueAllOtherSources;
                $scope.currentData.TotalDollarValueofGrossReceipts = financialItem.TotalDollarValueofGrossReceipts;
                $scope.currentData.EndingGrossAssets = financialItem.EndingGrossAssets;
                $scope.currentData.ExpensesGDExpendituresProgramServices = financialItem.ExpensesGDExpendituresProgramServices;
                $scope.currentData.ExpensesGDValueofAllExpenditures = financialItem.ExpensesGDValueofAllExpenditures;
                $scope.currentData.PercentToProgramServices = financialItem.PercentToProgramServices;
                $scope.currentData.Status = principalStatus.UPDATE;
                $scope.financialData.IsAmendEditable = true;
                //$scope.btnName = "Update Financial Information";
                $rootScope.isGlobalEdited = true;
            };

            //Delete fundraiser financial Info
            $scope.deleteFinancialInfo = function (financialItem) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    var index = $scope.financialData.CFTFinancialHistoryList.indexOf(financialItem);
                    $scope.financialData.CFTFinancialHistoryList.splice(index, 1);
                    $scope.financialData.NewFinCount = 0;
                    angular.forEach($scope.financialData.CFTFinancialHistoryList, function (value) {
                        if (value.Flag == 'C') {
                            $scope.financialData.NewFinCount++;
                        }
                    });
                });
            };

        },
    };
});
wacorpApp.directive('commercialFundraiserServiceContract', function () {

    return {
        templateUrl: 'ng-app/directives/CFT/CommercialFundraiserServiceContract/_CommercialFundraiserServiceContract.html',
        restrict: 'A',
        scope: {
            subcontractor: '=?subcontractor',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage',
            isAmendfsc:'=?isAmendfsc'
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.showFundraiserSearchValidationSC = false;
            $scope.showFRAddValidationSC = false;
            $scope.isReview = $scope.isReview || false;
            $scope.isAmendfsc = $scope.isAmendfsc || false;
            $scope.messages = messages;
            $scope.addHideFundraiserSC = "Add New Fundraiser";
            $scope.showNewFundraiserSection = false;
            $scope.search = getFundraiserList;
            $scope.isButtonSerach = false;
            var criteria = null;

            //$scope.subcontractor.FundraiserSubContractorList = $scope.subcontractor.FundraiserSubContractorList || [];

            //$scope.subcontractor.IsCommercialFundraisersContributionsInWA = $scope.subcontractor.IsCommercialFundraisersContributionsInWA||false;

            $scope.fundRaiserSC = {
                CFTID: constant.ZERO, FundRaiserID: constant.ZERO, FEINNumber: "", RegistrationNumber: "", UBINumber: "", EntityName: "", IsNewCFTFundraiser: false, Status: '',CFTStatus:'',StatusId:'',
                EntityMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }, ContributionServicesTypeId: null, ContributionServicesOtherComments: null, ContributionServicesTypes: null, OfficersHighPayList: [], ResponsiblePersonFirstName: null, ResponsiblePersonLastName: null
            }

            var fundRaiserScopeData = {
                CFTID: constant.ZERO, FundRaiserID: constant.ZERO, FEINNumber: "", UBINumber: "", EntityName: "", IsNewCFTFundraiser: false, Status: '',
                EntityMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }, ContributionServicesTypeId: null, ContributionServicesOtherComments: null, ContributionServicesTypes: null, OfficersHighPayList: [], ResponsiblePersonFirstName: null, ResponsiblePersonLastName: null
            }

            var fundRaiserResetScope = {
                CFTID: constant.ZERO, FundRaiserID: constant.ZERO, FEINNumber: "", UBINumber: "", EntityName: "", IsNewCFTFundraiser: false, Status: '',
                EntityMailingAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                        FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0,
                        ModifiedIPAddress: null
                    }, FullAddress: "", ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
                    Zip5: null, Zip4: null, PostalCode: null, County: null,
                }, ContributionServicesTypeId: null, ContributionServicesOtherComments: null, ContributionServicesTypes: null, OfficersHighPayList: [], ResponsiblePersonFirstName: null, ResponsiblePersonLastName: null
            }
            $scope.fundraiserSearchCriteriaSubcontract = { FundraiserName: "", FundraiserID: "", FEINNo: "", UBINumber: "", RegistrationNumber: "", Type: "", PageID: constant.ONE, PageCount: constant.TEN, ID: "" };
            $scope.fundraiserSearchCriteriaSubcontract.Type = "FundOrgNameSubcontract";
            $scope.AddFundraiser = function () {
                $("#divFundraisersListSC").modal('toggle');
                $scope.IsAddNewFundraiserSubcontract = true;
            }

            //Search Fundraiser -- start
            $scope.searchFundraiserSubcontract = function (searchSubcontractForm) {
                $scope.showFundraiserSearchValidationSC = true;
                if ($scope.fundraisersSubcontractForm.searchSubcontractForm.$valid) {
                    $scope.showFundraiserSearchValidationSC = false;
                    $scope.selectedFundraiser = undefined;
                    $scope.isButtonSerach = false;
                    getFundraiserList(constant.ZERO); // getFundraiserList method is available in this file only
                    $("#divFundraisersListSC").modal('toggle');
                }
            };

            $scope.setPastedUBI = function (e) {
                var pastedText = "";
                if (typeof e.originalEvent.clipboardData !== "undefined") {
                    pastedText = e.originalEvent.clipboardData.getData('text/plain');
                    pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                    $scope.fundraiserSearchCriteriaSubcontract.UBINumber = pastedText;
                    e.preventDefault();
                } else {
                    $timeout(function () {
                        pastedText = angular.element(e.currentTarget).val();
                        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                        $scope.fundraiserSearchCriteriaSubcontract.UBINumber = pastedText;
                    });
                }
            };

            $scope.$watch('fundraiserInfoSC', function () {
                if ($scope.fundraiserInfoSC == undefined)
                    return;
                if ($scope.fundraiserInfoSC.length == constant.ZERO) {
                    $scope.totalCount = constant.ZERO;
                    $scope.pagesCount = constant.ZERO;
                    $scope.totalCount = constant.ZERO;
                    $scope.page = constant.ZERO;
                }
            }, true);

            function getFundraiserList(page) {
                page = page || constant.ZERO;
                $scope.setCriteria($scope.fundraiserSearchCriteriaSubcontract.Type);

                $scope.fundraiserSearchCriteriaSubcontract.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
                var data = angular.copy($scope.fundraiserSearchCriteriaSubcontract);
                $scope.isButtonSerach = page == 0;
                data.ID = angular.copy($scope.isButtonSerach ? ($scope.fundraiserSearchCriteriaSubcontract.RegistrationNumber || $scope.fundraiserSearchCriteriaSubcontract.FEINNo
                                                                || $scope.fundraiserSearchCriteriaSubcontract.UBINumber || $scope.fundraiserSearchCriteriaSubcontract.FundraiserName) : $scope.searchval);
                if (criteria == null) {
                    criteria = {};
                    criteria.SearchCriteria = $scope.fundraiserSearchCriteriaSubcontract.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.fundraiserSearchCriteriaSubcontract.PageID;
                    criteria.PageCount = 10;
                    criteria.CharityId = $scope.subcontractor.CFTId;
                }
                else {
                    criteria.SearchCriteria = $scope.fundraiserSearchCriteriaSubcontract.Type;
                    criteria.SearchValue = data.ID;
                    criteria.PageID = $scope.fundraiserSearchCriteriaSubcontract.PageID;
                    criteria.PageCount = 10;
                    criteria.CharityId = $scope.subcontractor.CFTId;
                }

                if (criteria.SearchCriteria == "FundRegNumberSubcontract") {
                    criteria.RegistrationNumber = criteria.SearchValue;
                    criteria.FEINNo = null;
                    criteria.UBINumber = null;
                    criteria.EntityName = null;
                }
                else if (criteria.SearchCriteria == "FundFEINNoSubcontract") {
                    criteria.FEINNo = criteria.SearchValue;
                    criteria.UBINumber = null;
                    criteria.RegistrationNumber = null;
                    criteria.EntityName = null;
                }
                else if (criteria.SearchCriteria == "FundUBINoSubcontract") {
                    criteria.UBINumber = criteria.SearchValue;
                    criteria.FEINNo = null;
                    criteria.RegistrationNumber = null;
                    criteria.EntityName = null;
                } else {
                    criteria.EntityName = criteria.SearchValue;
                    criteria.FEINNo = null;
                    criteria.UBINumber = null;
                    criteria.RegistrationNumber = null;
                }

                //var criteria = {
                //    SearchCriteria: $scope.fundraiserSearchCriteriaSubcontract.Type,
                //    RegistrationNumber: $scope.fundraiserSearchCriteriaSubcontract.RegistrationNumber,
                //    FEINNo: $scope.fundraiserSearchCriteriaSubcontract.FEINNo,
                //    UBINumber: $scope.fundraiserSearchCriteriaSubcontract.UBINumber,
                //    EntityName: $scope.fundraiserSearchCriteriaSubcontract.FundraiserName,
                //    //SearchValue: $scope.fundraiserSearchCriteriaSubcontract.FundraiserName != null && $scope.fundraiserSearchCriteriaSubcontract.FundraiserName !=""?
                //    //    $scope.fundraiserSearchCriteriaSubcontract.FundraiserName : ($scope.fundraiserSearchCriteriaSubcontract.FundraiserID != null && $scope.fundraiserSearchCriteriaSubcontract.FundraiserID != "" ? $scope.fundraiserSearchCriteriaSubcontract.FundraiserID : ($scope.fundraiserSearchCriteriaSubcontract.RegistrationNumber != null && $scope.fundraiserSearchCriteriaSubcontract.RegistrationNumber != "" ? $scope.fundraiserSearchCriteriaSubcontract.RegistrationNumber : "")),
                //    PageID: page == constant.ZERO ? constant.ONE : page + constant.ONE, PageCount: constant.TEN
                //};
                // FundraiserSearchForCharitiesOFC method is available in constants.js
                wacorpService.post(webservices.CFT.FundraiserSearchForCharitiesOFC, criteria,
                    function (response) {
                        if (response.data != null) {
                            $scope.fundraiserInfoSC = angular.copy(response.data);
                            //$scope.clearSearch();
                            if ($scope.isButtonSerach && response.data.length > 0) {
                                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                                $scope.pagesCount = response.data.length < $scope.fundraiserSearchCriteriaSubcontract.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                                $scope.totalCount = totalcount;
                                $scope.searchval = criteria.SearchValue;
                                $scope.SearchCriteria = criteria.SearchCriteria;
                                criteria = response.data[constant.ZERO].Criteria;
                            }
                            $scope.page = page;
                        }
                        else
                            // Folder Name: app Folder
                            // Alert Name: noDataFound method is available in alertMessages.js
                            wacorpService.alertDialog($scope.messages.noDataFound);
                        //$scope.clearSearch();
                    },
                    function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    }
                );
            }

            $scope.setCriteria = function (value) {
                switch (value) {
                    case "FundOrgNameSubcontract":
                        $scope.fundraiserSearchCriteriaSubcontract.RegistrationNumber = null;
                        $scope.fundraiserSearchCriteriaSubcontract.FEINNo = null;
                        $scope.fundraiserSearchCriteriaSubcontract.UBINumber = null;
                        break;
                    case "FundFEINNoSubcontract":
                        $scope.fundraiserSearchCriteriaSubcontract.UBINumber = null;
                        $scope.fundraiserSearchCriteriaSubcontract.RegistrationNumber = null;
                        $scope.fundraiserSearchCriteriaSubcontract.FundraiserName = null;
                        break;
                    case "FundUBINoSubcontract":
                        $scope.fundraiserSearchCriteriaSubcontract.RegistrationNumber = null;
                        $scope.fundraiserSearchCriteriaSubcontract.FEINNo = null;
                        $scope.fundraiserSearchCriteriaSubcontract.FundraiserName = null;
                        break;
                    case "FundRegNumberSubcontract":
                        $scope.fundraiserSearchCriteriaSubcontract.UBINumber = null;
                        $scope.fundraiserSearchCriteriaSubcontract.FEINNo = null;
                        $scope.fundraiserSearchCriteriaSubcontract.FundraiserName = null;
                        break;

                }
            };

            $scope.clearSearch = function () {
                $scope.fundraiserSearchCriteriaSubcontract.FundraiserName = "";
                $scope.fundraiserSearchCriteriaSubcontract.FEINNo = "";
                $scope.fundraiserSearchCriteriaSubcontract.UBINumber = "";
                $scope.fundraiserSearchCriteriaSubcontract.RegistrationNumber = "";
            }
            //On select fundraiser from fundraisers list
            $scope.onSelectFundraiserSC = function (selectFundraiser) {
                $scope.selectedFundraiser = undefined;
                $scope.selectedFundraiser = selectFundraiser;
            };

            //Add Search Fundraiser
            $scope.addsearchFundraiserSubcontract = function () {
                if ($scope.selectedFundraiser && $scope.selectedFundraiser.FundraiserID != constant.ZERO) {
                    $("#divFundraisersListSC").modal('toggle');
                    $scope.fundRaiserSC.FundRaiserID = $scope.selectedFundraiser.FundRaiserID;
                    $scope.fundRaiserSC.FEINNumber = $scope.selectedFundraiser.FEINNumber;
                    $scope.fundRaiserSC.RegistrationNumber = $scope.selectedFundraiser.RegistrationNumber;
                    $scope.fundRaiserSC.UBINumber = $scope.selectedFundraiser.UBINumber;
                    $scope.fundRaiserSC.EntityName = $scope.selectedFundraiser.EntityName;
                    $scope.fundRaiserSC.EntityMailingAddress = $scope.selectedFundraiser.EntityMailingAddress;
                    $scope.fundRaiserSC.Status = principalStatus.INSERT;
                    $scope.fundRaiserSC.CFTType = "F";
                    $scope.fundRaiserSC.StatusId = $scope.selectedFundraiser.StatusId;
                    $scope.fundRaiserSC.CFTStatus = $scope.selectedFundraiser.Status;
                    $scope.fundRaiserSC.IsNewCFTFundraiser = false;
                    $scope.fundRaiserSC.IsSubContractorUnRegistered = $scope.selectedFundraiser.IsSubContractorUnRegistered;
                    $scope.subcontractor.FundraiserSubContractorList.push($scope.fundRaiserSC);
                    $scope.showNewFundraiserSection = false;
                    $scope.resetFundraiser(); // resetFundraiser method is available in this file only
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: selectFundraiser method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.FundraiserSearch.selectFundraiser);
                }
            };

            //Search Fundraiser -- End

            ///Add/Edit/Delete New Fundraiser - Start
            //Reset the fundraiser charitable organization
            $scope.resetFundraiser = function () {
                $scope.fundRaiserSC = angular.copy(fundRaiserScopeData);
                $scope.showErrorMessage = false;
                $scope.addHideFundraiserSC = "Add New Fundraiser";
            };

            $scope.ShowHideAddNewFundraiser = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsAddNewFundraiserSubcontract = $scope.IsAddNewFundraiserSubcontract ? false : true;
                $scope.addHideFundraiserSC = $scope.IsAddNewFundraiserSubcontract ? "Add New Fundraiser" : "Cancel Fundraiser";
            }
            $scope.AddNewFundraiserSC = function (fundraiserFormSC) {
                $scope.showFRAddValidationSC = true;

                $scope.fundRaiserSC.EntityMailingAddress.StreetAddress1 = (($scope.fundRaiserSC.EntityMailingAddress.StreetAddress1 != null && $scope.fundRaiserSC.EntityMailingAddress.StreetAddress1.trim() == "" || $scope.fundRaiserSC.EntityMailingAddress.StreetAddress1 == undefined) ? $scope.fundRaiserSC.EntityMailingAddress.StreetAddress1 = null : $scope.fundRaiserSC.EntityMailingAddress.StreetAddress1.trim());
                if (!$scope.fundRaiserSC.EntityMailingAddress.StreetAddress1) {
                    $scope.fundraisersSubcontractForm.fundraiserFormSC.CFTAddress.StreetAddress1.$setValidity("text", false);
                }
                else {
                    $scope.fundraisersSubcontractForm.fundraiserFormSC.CFTAddress.StreetAddress1.$setValidity("text", true);
                }

                var isCollectedContributions = ($scope.fundRaiserSC.ContributionServicesTypeId == null || $scope.fundRaiserSC.ContributionServicesTypeId == undefined || $scope.fundRaiserSC.ContributionServicesTypeId == "") ? false : true;
                if ($scope.fundraisersSubcontractForm[fundraiserFormSC].$valid && isCollectedContributions) {
                    $scope.showFRAddValidationSC = false;
                    if ($scope.fundRaiserSC.FundRaiserID != "") {
                        angular.forEach($scope.subcontractor.FundraiserSubContractorList, function (fundraiser) {
                            if (fundraiser.FundRaiserID == $scope.fundRaiserSC.FundRaiserID) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                $scope.fundRaiserSC.EntityMailingAddress.FullAddress = wacorpService.fullAddressService($scope.fundRaiserSC.EntityMailingAddress);
                                var respPersonUpdate = $scope.fundRaiserSC.OfficersHighPayList[0];
                                if (respPersonUpdate != null) {
                                    respPersonUpdate.FirstName = $scope.fundRaiserSC.ResponsiblePersonFirstName;
                                    respPersonUpdate.LastName = $scope.fundRaiserSC.ResponsiblePersonLastName;

                                    $scope.fundRaiserSC.OfficersHighPayList.push(respPersonUpdate);
                                }

                                angular.copy($scope.fundRaiserSC, fundraiser);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.subcontractor.FundraiserSubContractorList, function (fundraiser) {
                            if (maxId == constant.ZERO || fundraiser.FundRaiserID > maxId)
                                maxId = fundraiser.FundRaiserID;
                        });
                        $scope.fundRaiserSC.FundRaiserID = ++maxId;
                        $scope.fundRaiserSC.IsNewCFTFundraiser = true;
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.fundRaiserSC.EntityMailingAddress.FullAddress = wacorpService.fullAddressService($scope.fundRaiserSC.EntityMailingAddress);
                        $scope.fundRaiserSC.Status = principalStatus.INSERT;
                        $scope.fundRaiserSC.IsSubContractorUnRegistered = true;

                        var respPerson = {};
                        respPerson.FirstName = $scope.fundRaiserSC.ResponsiblePersonFirstName;
                        respPerson.LastName = $scope.fundRaiserSC.ResponsiblePersonLastName;

                        $scope.fundRaiserSC.OfficersHighPayList.push(respPerson);
                        $scope.subcontractor.FundraiserSubContractorList.push($scope.fundRaiserSC);
                    }
                    $scope.resetFundraiser();
                    $scope.IsAddNewFundraiserSubcontract = false;
                }
                $scope.showNewFundraiserSection = false;
            }

            //Edit fundraiser charitable organization data
            $scope.editCFTFundRaiserSC = function (fundraiserData) {
                $scope.IsAddNewFundraiserSubcontract = true;
                fundraiserData.EntityMailingAddress.Country = fundraiserData.EntityMailingAddress.Country || codes.USA;
                fundraiserData.EntityMailingAddress.State = fundraiserData.EntityMailingAddress.State || codes.USA;
                if (fundraiserData.Status != principalStatus.INSERT)
                    fundraiserData.Status = principalStatus.UPDATE;
                $scope.fundRaiserSC = angular.copy(fundraiserData);
                var respPerson = $scope.fundRaiserSC.OfficersHighPayList[0];
                if (respPerson != null) {
                    $scope.fundRaiserSC.ResponsiblePersonFirstName = respPerson.FirstName;
                    $scope.fundRaiserSC.ResponsiblePersonLastName = respPerson.LastName;
                }
                $scope.addHideFundraiserSC = "Update Fundraiser";
                $scope.showNewFundraiserSection = true;
            };

            //Delete fundraiser charitable organization data
            $scope.deleteCFTFundRaiserSC = function (fundraiserData) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js 
                wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
                    var index = $scope.subcontractor.FundraiserSubContractorList.indexOf(fundraiserData);
                    $scope.subcontractor.FundraiserSubContractorList.splice(index, 1);
                    $scope.resetFundraiser();
                    $scope.showNewFundraiserSection = true;
                    $scope.IsAddNewFundraiserSubcontract =false;
                });
            };

            //Clear new the Fundraiser Information
            $scope.clearFRDetailsSC = function () {
                $scope.fundRaiserSC = angular.copy(fundRaiserResetScope);
                $scope.selectedFundraiser = angular.copy(fundRaiserResetScope);

                $scope.IsAddNewFundraiserSubcontract = false;
            };
        },
    };
});
wacorpApp.directive('fundraiserServiceContractTermDates', function () {

    return {
        templateUrl: 'ng-app/directives/CFT/ServiceContractTermDates/_FundraiserServiceContractTermDates.html',
        restrict: 'A',
        scope: {
            contract: '=?contract',
            isReview: '=?isReview',
            showErrorMessage: '=?showErrorMessage'
        },
        controller: function ($scope, wacorpService, $rootScope) {
            $scope.showErrorMessage = $scope.showErrorMessage || false;
            $scope.isReview = $scope.isReview || false;
            $scope.messages = messages;
            $scope.isEndDateGreater = false;
            $scope.isServiceEndDateGreater = false;

            
            $scope.validateContractDate = function () {
                if ($scope.contract.ContractTermBeginDate != null && $scope.contract.ContractTermEndDate != null && $scope.contract.ContractTermBeginDate != undefined && $scope.contract.ContractTermEndDate != undefined && $scope.contract.ContractTermBeginDate != "" && $scope.contract.ContractTermEndDate != "") {
                    if (new Date($scope.contract.ContractTermEndDate) < new Date($scope.contract.ContractTermBeginDate)) {
                        $scope.isEndDateGreater = true;
                    } else {
                        $scope.isEndDateGreater = false;
                    }
                } else {
                    $scope.isEndDateGreater = false;
                }
            };

            $scope.validateServiceDate = function () {
                if ($scope.contract.DateServiceBeginDate != null && $scope.contract.DateServiceEndDate != null && $scope.contract.DateServiceBeginDate != undefined && $scope.contract.DateServiceEndDate != undefined && $scope.contract.DateServiceBeginDate != "" && $scope.contract.DateServiceEndDate != "") {
                    if (new Date($scope.contract.DateServiceEndDate) < new Date($scope.contract.DateServiceBeginDate)) {
                        $scope.isServiceEndDateGreater = true;
                    } else {
                        $scope.isServiceEndDateGreater = false;
                    }
                } else {
                    $scope.isServiceEndDateGreater = false;
                }
            };

        },
    };
});
wacorpApp.directive('newTrustBeneficaries', function () {
    return {
        templateUrl: 'ng-app/directives/CFT/TrustBeneficiaries/_newTrustBeneficaries.html',
        restrict: 'A',
        scope: {
            isReview: '=?isReview',
            isRequired: '=?isRequired',
            cftBeneficaryList: '=?cftBeneficaryList',
        },
        controller: function ($scope, lookupService, wacorpService, $rootScope) {
            $scope.messages = messages;
            $scope.addbuttonName = "Add New Charity"
            $scope.showStreetAddress = $scope.showStreetAddress || false;
            $scope.isReview = $scope.isReview || false;
            $scope.isRequired = $scope.isRequired || true;
            $scope.ValidateErrorMessageForTrust = $scope.ValidateErrorMessageForTrust || false;
            $scope.showTrustErrorMessage = $scope.showTrustErrorMessage || false;
            $scope.cftBeneficaryList = $scope.cftBeneficaryList || [];

            angular.element(function () {
                $('[name="cftBeneficaries"] .hideTrustBen').hide();
                $('[name="cftBeneficaries"] .hideTrustBenTxt').hide();
            });

            $scope.cftBeneficary = {
                CFTBeneficaryNameAddressOfTrust: null, CFTBeneficaryID: constant.ZERO, SequenceNo: "",Status:"",
                cftBeneficaryAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
            };

            var cftBeneficaryScope = {
                CFTBeneficaryNameAddressOfTrust: null, CFTBeneficaryID: constant.ZERO, SequenceNo: "", Status: "",
                cftBeneficaryAddress: {
                    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                    FullAddress: null, FullAddressWithoutCounty: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                },
            };

            $scope.$watch('cftBeneficary.cftBeneficaryAddress.StreetAddress1', function () {
                if ($scope.cftBeneficary.cftBeneficaryAddress.StreetAddress1) {
                    $('[name="cftBeneficaries"] .hideTrustBen').show();
                    if ($scope.ValidateErrorMessageForTrust ==false) {
                        $('[name="cftBeneficaries"] .hideTrustBenTxt').show();
                    }
                }
                else {
                    $('[name="cftBeneficaries"] .hideTrustBen').hide();
                    $('[name="cftBeneficaries"] .hideTrustBenTxt').hide();
                }
            });

            $scope.$watch('cftBeneficary.cftBeneficaryAddress.Country', function (newVal,oldVal) {
                if (newVal != oldVal) {
                    //$scope.cftBeneficary.cftBeneficaryAddress.StreetAddress1 =null;
                    //$scope.cftBeneficary.cftBeneficaryAddress.StreetAddress2 =null;
                    //$scope.cftBeneficary.cftBeneficaryAddress.City =null;
                    //$scope.cftBeneficary.cftBeneficaryAddress.OtherState =null;
                    //$scope.cftBeneficary.cftBeneficaryAddress.Zip5 =null;
                    //$scope.cftBeneficary.cftBeneficaryAddress.Zip4 =null;
                    //$scope.cftBeneficary.cftBeneficaryAddress.PostalCode =null;
                    $('[name="cftBeneficaries"] .hideTrustBen').hide();
                    $('[name="cftBeneficaries"] .hideTrustBenTxt').hide();
                }
            });

            $scope.resetCFTBeneficaryScope = function (){

                $scope.cftBeneficary = angular.copy(cftBeneficaryScope);
                $scope.addbuttonName = "Add New Charity";
                $scope.ValidateErrorMessageForTrust = false;
                $('[name="cftBeneficaries"] .hideTrustBen').hide();
                $('[name="cftBeneficaries"] .hideTrustBenTxt').hide();


                //$scope.showTrustErrorMessage = false;
                //$rootScope.$broadcast('onTrustBeneficiaryClearClicked');

                //cftBeneficaryAddress: {
                //    ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
                //    baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
                //    FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                //    State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
                //},
            };


            $scope.cftBeneficaryData = $scope.cftBeneficaryData ? angular.extend(cftBeneficaryScope, $scope.cftBeneficaryData) : angular.copy(cftBeneficaryScope);


            //Add Beneficary data
            $scope.AddCFTBeneficaries = function (cftBeneficaries) {
                $scope.ValidateErrorMessageForTrust = true;
                $('[name="cftBeneficaries"] .hideTrustBenTxt').hide();

                $scope.cftBeneficary.cftBeneficaryAddress.StreetAddress1 = (($scope.cftBeneficary.cftBeneficaryAddress.StreetAddress1 != null && $scope.cftBeneficary.cftBeneficaryAddress.StreetAddress1.trim() == "" || $scope.cftBeneficary.cftBeneficaryAddress.StreetAddress1 == undefined) ? $scope.cftBeneficary.cftBeneficaryAddress.StreetAddress1 = null : $scope.cftBeneficary.cftBeneficaryAddress.StreetAddress1.trim());
                if (!$scope.cftBeneficary.cftBeneficaryAddress.StreetAddress1) {
                    $scope.cftBeneficaries.CFTAddress.StreetAddress1.$setValidity("text", false);
                }
                else {
                    $scope.cftBeneficaries.CFTAddress.StreetAddress1.$setValidity("text", true);
                }

                if ($scope[cftBeneficaries].$valid) {
                    $scope.ValidateErrorMessageForTrust = false;
                    if ($scope.cftBeneficary.SequenceNo != "") {
                        angular.forEach($scope.cftBeneficaryList, function (beneficary) {
                            if (beneficary.SequenceNo == $scope.cftBeneficary.SequenceNo) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                $scope.cftBeneficary.cftBeneficaryAddress.FullAddress = wacorpService.fullAddressService($scope.cftBeneficary.cftBeneficaryAddress);
                                angular.copy($scope.cftBeneficary, beneficary);
                            }
                        });
                    }
                    else {
                        var maxId = constant.ZERO;
                        angular.forEach($scope.cftBeneficaryList, function (beneficary) {
                            if (maxId == constant.ZERO || beneficary.SequenceNo > maxId)
                                maxId = beneficary.SequenceNo;
                        });
                        $scope.cftBeneficary.SequenceNo = ++maxId;
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.cftBeneficary.cftBeneficaryAddress.FullAddress = wacorpService.fullAddressService($scope.cftBeneficary.cftBeneficaryAddress);
                        $scope.cftBeneficary.Status = principalStatus.INSERT;
                        $scope.cftBeneficaryList.push($scope.cftBeneficary);
                    }
                    $scope.resetCFTBeneficaryScope(); // resetCFTBeneficaryScope method is available in this file only
                }
            };


            $scope.editCFTBeneficaries = function (beneficaries) {
                //principaldata.PrincipalStreetAddress.Country = principaldata.PrincipalStreetAddress.Country || codes.USA;
                //principaldata.PrincipalStreetAddress.State = principaldata.PrincipalStreetAddress.State || codes.USA;
                $scope.cftBeneficary = angular.copy(beneficaries);
                $scope.cftBeneficary.Status = $scope.cftBeneficary.CFTBeneficaryID == 0 ? principalStatus.INSERT : principalStatus.UPDATE;
                $scope.addbuttonName = "Update Charity"
            };

            // Clear all controls data
            $scope.clearCFTBeneficaries = function () {
                $scope.resetCFTBeneficaryScope(); // resetCFTBeneficaryScope method is available in this file only
            };

            //Delete principal data
            $scope.deleteCFTBeneficaries = function (beneficaries) {
                // Folder Name: app Folder
                // Alert Name: ConfirmMessage method is available in alertMessages.js
                wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
                    if (beneficaries.Status == "N") {
                        var index = $scope.cftBeneficaryList.indexOf(beneficaries);
                        $scope.cftBeneficaryList.splice(index, 1);
                    }
                    else {
                        beneficaries.Status = principalStatus.DELETE;
                    }
                    $scope.resetCFTBeneficaryScope(); // resetCFTBeneficaryScope method is available in this file only
                });
            };

        },
    };
});

wacorpApp.directive('backButton', function () {
    return {
        templateUrl: 'ng-app/directives/FormationBackButton/BackButton.html',
        scope: {
            businessModel: '=?businessModel',
            businesstype: '=?businesstype',
            businessModelEntity: '=?businessModelEntity'
        },
        controller: function ($scope, wacorpService, $timeout, lookupService, $rootScope, $cookieStore, $location) {

            $scope.back = function () {
                
                $scope.businessModel = $cookieStore.get('formationSearch');
                $scope.businesstype = $cookieStore.get('formationSearchBusinessType');
                $scope.businessModelEntity = $cookieStore.get('formationSearchCheckedType');
                $cookieStore.put('formationSearch', $scope.businessModel);
                $cookieStore.put('formationSearchBusinessType', $scope.businesstype);
                $cookieStore.put('formationSearchCheckedType', $scope.businessModelEntity);
                $location.path("/Formations/businessFormationIndex");
            };

        }
    };
   
});
wacorpApp.controller('rootController', function ($scope,
    $route,
    $window,
    $rootScope,
    $location,
    $cookieStore,
    lookupService,
    membershipService,
    wacorpService,
    dataService) {
    $scope.userData = {};

    //initialization
    $scope.rootInit = function () {
        $scope.userData.displayUserInfo();
        $scope.quickLinks();
        $scope.messages = messages;
        $scope.TestBannerDisplay = 1;
        $window.onbeforeunload = $scope.onExit;
    };

    $scope.$on('$viewContentLoaded',
        function () {
            $(window).scrollTop(0);
        });

    $scope.onExit = function (event) {
        //$scope.userData.isUserLoggedIn = membershipService.isUserLoggedIn();
        //if ($scope.userData.isUserLoggedIn) {
        //    $scope.logout();
        //}
    };
    //$scope.quickLinks = loadquickLinks;
    $scope.quickLinks = function () {
        wacorpService.get(webservices.Home.getQuickLinks,
            null,
            function (result) {
                // $scope.quickLinks = $filter('orderBy')(result.data, 'Order')
                $scope.quickLinks = _.groupBy(result.data, "DisplayText");
            },
            function () {
                // wacorpService.alertDialog("Failed to load Quick Links.");
            });

        //Access-Control-Allow-Headers: x-my-custom-header
        //Access-Control-Allow-Methods: PUT
        // $.ajax({
        //     type: "GET",
        //     url:webservices.Home.getQuickLinks,
        //     headers: { 'Access-Control-Allow-Headers': 'x-my-custom-header', 'Access-Control-Allow-Methods': 'GET' },
        //     success: function (result) {
        //         $scope.quickLinks = _.groupBy(result.data, "DisplayText");
        //     }, error: function (error) {
        //         notificationService.displayError("failed to load quickLinks");
        //     },

        // });

    };

    $scope.masterLayout = function () {
        if ($rootScope.repository.loggedUser != null || $rootScope.repository.loggedUser != undefined)
            return "/ng-app/view/layout/adminLayout.html";
        return "/ng-app/view/layout/publicLayout.html";
    };

    $scope.logout = function () {
        membershipService.removeCredentials();
        $scope.userData.displayUserInfo();
        $location.path('/');
        $scope.$on('$routeChangeSuccess',
            function ($event, next, current) {
                window.location.reload(false);
            });
    };

    //to redirect to dashboard if user is logged in
    $scope.redirect = function () {
        if ($scope.userData.isUserLoggedIn) {
            $scope.navDashboard();
        } else {
            $scope.navHome();
        }
    };

    $scope.userData.displayUserInfo = function () {
        $scope.userData.isUserLoggedIn = membershipService.isUserLoggedIn();
        if ($scope.userData.isUserLoggedIn) {
            $scope.username = $rootScope.repository.loggedUser.firstname;
        } else {
            $scope.username = '';
        }
    };

    $scope.CAmenu = function () {
        if ($rootScope.repository.loggedUser != null)
            return $rootScope.repository.loggedUser.filerTypeId == filerType.CommercialRegisteredAgent &&
                $rootScope.repository.loggedUser.agentid != 0;
    };

    $scope.RAmenu = function () {
        if ($rootScope.repository.loggedUser != null)
            return $rootScope.repository.loggedUser.filerTypeId == filerType.NonCommercialRegisteredAgent ||
                $rootScope.repository.loggedUser.filerTypeId == filerType.Filer;
    };

    // navigation to views
    $scope.navHome = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/Home");
    };

    //Account Maintenance
    $scope.navAccountMaintenance = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/AccountMaintenance");
    };

    //User Registration
    $scope.navUserRegistration = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/UserRegistration");
    };

    //***** added 10/10/2019, KK *****
    //Add Authorized User (to CRA Account)
    //$scope.navAddAuthUser = function () {
    //    $rootScope.modal = null;
    //    $rootScope.TransactionID = null;
    //    $rootScope.searchCriteria = null;
    //    $location.path("/AddAuthUser");
    //};

    //Forgot Password
    //$scope.navForogtPassword = function () { !!!***** Corrected sp error below - KK, 10/29/2019 *****
    $scope.navForgotPassword = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/ForgotPassword");
    };

    //Forgot User
    $scope.navForgotUser = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/ForgotUser");
    };

    //Change Password
    $scope.navChangePassword = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/ChangePassword");
    };

    //Business Search
    $scope.navBusinessSearch = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $rootScope.searchList = null;
        $location.path("/BusinessSearch");
    };

    //Advanced (Business) Search
    $scope.navAdvancedSearch = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/AdvancedSearch");
    };

    //Business Information
    $scope.navBusinessInformation = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/BusinessSearch/BusinessInformation");
    };

    //Business Filings
    $scope.navBusinessFilings = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/BusinessSearch/BusinessFilings");
    };

    //Business Name History
    $scope.navBusinessNameHistory = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/BusinessSearch/BusinessNameHistory");
    };

    //Dashboard
    $scope.navDashboard = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/Dashboard");
    };

    //Account Maintenance
    $scope.navChangeAccount = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/AccountMaintenance");
    };

    //Annual Report
    $scope.navAnnualReport = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/AnnualReport/BusinessSearch");
    };

    //Annual Report Review
    $scope.navAnnualReportReview = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/AnnualReportReview");
    };

    //Amended Report
    $scope.navAmendedAnnualReport = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/AmendedAnnualReport/BusinessSearch");
    };

    //Initial Report
    $scope.navInitialReport = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/InitialReport/SearchBusiness");
    };

    //Statement of change
    $scope.navStatementofChange = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/StatementofChangeIndex");
    };

    //Reinstatement
    $scope.navReinstatement = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $rootScope.requalificationModal = null;
        $location.path("/ReinstatementIndex"); // navigation
    };

    //Reinstatement Review
    $scope.navReinstatementReview = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $location.path("/ReinstatementReview");
    };

    //Amendment of Foreign Registration
    $scope.navAmendmentOfForiegnRegistrationStatement = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/AmendmentofForiegnRegistrationStatement/BusinessSearch");
    };

    //Certificate Of Dissolution
    $scope.navCertificateOfDissolution = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/CertificateOfDissolutionIndex");
    };

    //Articles Of Dissolution
    $scope.navArticlesOfDissolution = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/ArticlesOfDissolutionIndex");
    };

    //Statement of withdrawal
    $scope.navStatementofWithdrawal = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $rootScope.statementOfWithdrawalModal = null;
        $rootScope.voluntaryTerminationModal = null;
        $rootScope.certificateOfDissolutionModel = null;
        $rootScope.articlesOfDissolutionModel = null;
        $location.path("/StatementofWithdrawalIndex");
    };

    //Voluntary Termination
    $scope.navVoluntaryTermination = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/VoluntaryTerminationIndex");
    };

    //Commercial Statement of change
    $scope.navCommercialStatementofChange = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $rootScope.commercialStatementofChangeModal = null;
        $location.path("/CommercialStatementofChange");
    };

    //Commercial Statement of Termination
    $scope.navStatementofTermination = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/StatementofTerminationIndex");
    };

    //Statement of Termination
    $scope.navcommercialStatementofTermination = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $rootScope.commercialStatementofTerminationModal = null;
        $location.path("/CommercialStatementofTerminationIndex");
    };

    //Commercial Listing Statement
    $scope.navcommercialListingStatement = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $rootScope.commercialListingStatementModal = null;
        $location.path("/CommercialListingStatement");
    };

    //Business Amendment
    $scope.navBusinessAmendment = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/BusinessAmendmentIndex");
    };

    //BusinessSearch
    $scope.navCopyRequest = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/CopyRequest/BusinessSearch");
    };

    //CorporationSearch
    $scope.navCorporationSearch = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/CorporationSearch");
    };

    ////!!! Commented out - already exists at ln.137 - KK, 10/29/2019
    ////ChangePassword
    //$scope.navChangePassword = function () {
    //    $rootScope.modal = null;
    //    $rootScope.transactionID = null;
    //    $rootScope.searchCriteria = null;
    //    $location.path("/ChangePassword");
    //};

    //Charities Registration
    //$scope.navCharityRegistration = function () { localStorage.setItem('isOptional', false); $rootScope.modal = null; $rootScope.transactionID = null; $rootScope.IsShoppingCart = false; $rootScope.searchCriteria = null; $location.path("/charitiesRegistration"); };

    $scope.navExpressPDFCertificate = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/ExpressPDFCertificate/BusinessSearch");
    }; //BusinessSearch

    $scope.navCharityRegistration = function () {
        localStorage.setItem('isOptional', false);
        $rootScope.isRenewal = false;
        $rootScope.isOptionalReg = false;
        $rootScope.isOptionalAmendment = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";

        $location.path("/charitiesRegistration");
    };

    $scope.navCharityOptionalRegistration = function () {
        localStorage.setItem('isOptional', true);
        $rootScope.isOptionalReg = true;
        $rootScope.OptionalData = null;
        $rootScope.isOptionalAmendment = false;
        $rootScope.isRenewal = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";
        $location.path("/charitiesOptionalQualifier");
    };

    //Charities Optional Registration
    $scope.navCharityOptionalRenewal = function () {
        localStorage.setItem('isOptional', true);
        $rootScope.isRenewal = true;
        $rootScope.isOptionalReg = false;
        $rootScope.isOptionalAmendment = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";
        $location.path("/charitiesSearch/OptionalRenewal");
    };

    //Charities Optional Amendment
    $scope.navCharityOptionalAmendment = function () {
        localStorage.setItem('isOptional', true);
        $rootScope.isOptionalAmendment = true;
        $rootScope.isOptionalReg = false;
        $rootScope.isRenewal = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";
        $location.path("/charitiesSearch/OptionalAmendment");
    };

    //Charities Optional Closure
    $scope.navCharityOptionalClosure = function () {
        localStorage.setItem('isOptional', true);
        $rootScope.isOptionalReg = false;
        $rootScope.isRenewal = false;
        $rootScope.isOptionalAmendment = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";
        $location.path("/charitiesSearch/OptionalClosure");
    };

    //Charities Renewal
    $scope.navCharityRenewal = function () {
        localStorage.setItem('isOptional', false);
        $rootScope.isOptionalAmendment = false;
        $rootScope.isOptionalReg = false;
        $rootScope.isRenewal = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";
        $location.path('/charitiesSearch/Renewal');
    };

    //Charities Close
    $scope.navCharityClose = function () {
        localStorage.setItem('isOptional', false);
        $rootScope.isOptionalAmendment = false;
        $rootScope.isOptionalReg = false;
        $rootScope.isRenewal = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";
        $location.path('/charitiesSearch/Closure');
    };

    //Charities Amendment
    $scope.navCharityAmendment = function () {
        localStorage.setItem('isOptional', false);
        $rootScope.isOptionalAmendment = false;
        $rootScope.isOptionalReg = false;
        $rootScope.isRenewal = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";
        $location.path('/charitiesSearch/Amendment');
    };

    //Fundraising Service Contract Registration
    $scope.navFundraiserServiceContractReg = function () {
        localStorage.setItem('isOptional', false);
        $rootScope.isOptionalAmendment = false;
        $rootScope.isOptionalReg = false;
        $rootScope.isRenewal = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $rootScope.IsShoppingCart = false;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";
        $location.path('/charitiesSearch/FundraiserServiceContract');
    };

    //Fundraising Service Contract Amendment
    $scope.navFundraiserServiceContractAmendment = function () {
        localStorage.setItem('isOptional', false);
        $rootScope.isOptionalAmendment = false;
        $rootScope.isOptionalReg = false;
        $rootScope.isRenewal = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $rootScope.IsShoppingCart = false;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        //Remove Re-Registration Flags -- 2792
        $rootScope.isOptionalReRegistration = false;
        localStorage.getItem("isOptionalReRegistration") == "false";
        $location.path('/charitiesSearch/FundraiserServiceContractAmendment');
    };

    //CFT ReRegistration
    $scope.navReRegistration = function () {
        localStorage.setItem('isOptional', false);
        $rootScope.isOptionalAmendment = false;
        $rootScope.isOptionalReg = false;
        $rootScope.isRenewal = false;
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        $location.path("/cftReRegistration");
    };

    //Charities optional Update
    $scope.navCharityOptionalUpdate = function () {
        localStorage.setItem('isOptional', true);
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.isOptionalAmendment = false;
        $rootScope.searchCriteria = null;
        $location.path('/charitiesOptionalSearch/OptionalRegistration');
    };

    //Fundraiser Registration
    $scope.navFundraiserRegistration = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        $location.path("/fundraiserRegistration");
    };

    //Fundraiser Renewal
    $scope.navFundraiserRenewal = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        $location.path("/fundraiserSearch/Renewal");
        $rootScope.IsShoppingCart = false;
    };

    //Fundraiser Amendment
    $scope.navFundraiserAmendment = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        $location.path("/fundraiserSearch/Amendment");
        $rootScope.IsShoppingCart = false;
    };

    //Fundraiser Close
    $scope.navFundraiserClose = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        $location.path("/fundraiserSearch/Closure");
        $rootScope.IsShoppingCart = false;
    };

    //Trustee Renewal
    $scope.navTrusteeRenewal = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        //Ticket-3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isSearchNavClicked = true;
        }
        $location.path("/trusteeRenewalSearch");
        $rootScope.IsShoppingCart = false;
    };

    //CFT Search
    $scope.navCFTSearch = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        //Ticket -- 3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isInitialSearch = false;
            $rootScope.isCftOrganizationSearchBack = false;
            $rootScope.data = null;
        }
        $location.path("/cftSearch");
        $rootScope.clearCFTSearchResults();
    };

    //new CFT Search
    $scope.navNewCFTSearch = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        //Ticket -- 3167
        if (!$rootScope.isCFTBackButtonPressed) {
            $rootScope.isInitialSearch = false;
            $rootScope.isCftOrganizationSearchBack = false;
            $rootScope.data = null;
        }
        $location.path("/cftSearch");
    };

    //Trademark Search
    $scope.navTrademarkSearch = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        //Ticket -- 3167
        if (!$rootScope.isTrademarkBackButtonPressed) {
            $rootScope.data = null;
        }
        $location.path("/trademarkSearch");
        $rootScope.clearTrademarkSearchResults();
    };

    //Charity Foundation Organization
    $scope.navCharityFoundationOrganization = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/organization");
    };

    //cftOrgBusinessDetails
    $scope.navCFTOrgBusinessDetails = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/cftBusinessDetails");
    };

    //cftOrgBusinessSearch
    $scope.navCFTBusinessSearch = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/cftBusinessSearch");
    };

    //Organization Filling
    $scope.navCFTSearchOrganizationFilings = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/CFTSearch/cftSearchOrganizationFilings");
    };

    //Organization History
    $scope.navCFTSearchOrganizationNameHistory = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/CFTSearch/cftSearchOrganizationNameHistory");
    };

    //Trust Close
    $scope.navTrustClose = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.IsShoppingCart = false;
        $rootScope.searchCriteria = null;
        $rootScope.isSearchNavClicked = true;
        $rootScope.data = null;
        $location.path("/trusteeSearch/Closure");
        $rootScope.IsShoppingCart = false;
    };

    //Requalification
    $scope.navRequalification = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $rootScope.searchCriteria = null;
        $location.path("/RequalificationIndex");
    };

    //Requalification Review
    $scope.navRequalificationReview = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $location.path("/RequalificationReview");
    };

    //CommercialRegisteredAgents
    $scope.CommercialRegisteredAgentsList = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $location.path("/CommercialRegisteredAgents");
    };

    $scope.navMenu = function (obj, filingTypeID) {
        $cookieStore.remove('formationSearch');
        $cookieStore.remove('formationSearchBusinessType');
        $cookieStore.remove('formationSearchCheckedType');
        $rootScope.isLookUpClicked = false;
        $rootScope.isUseClicked = false;
        $rootScope.FilingTypeID = filingTypeID;
        $location.path("/" + obj);
    };

    // functions
    function searchResultsLoading(flag) {
        if (flag == true)
            $scope.loadingText = "Processing ...";
        else
            $scope.loadingText = "Search";
    }

    $scope.viewTransactionDocuments = function getTransactionDocumentsList(Transactionid) {
        var criteria = {
            ID: Transactionid
        };
        //webservices.WorkOrder.GetTransactionDocuments -- OSOS ID--2984
        wacorpService.get(webservices.WorkOrder.GetTransactionDocumentsAfterPaymentSuccess,
            { params: { transactionID: Transactionid } },
            function (response) {
                if (response.data != null) {
                    $scope.transactionDocumentsList = angular.copy(response.data);
                    $("#divSearchResult").modal('toggle');
                } else
                    wacorpService.alertDialog($scope.messages.noDataFound);
            },
            function (response) {
                wacorpService.alertDialog(response.data.Message);
            }
        );
    }

    $scope.date = new Date();

    $scope.isNullorEmpty = function (val) {
        return angular.isUndefined(val) || val === null || val === '';
    }

    $scope.convertObjectToString = function (obj) {
        return angular.isNullorEmpty(obj) ? "" : obj.length == 0 ? "" : obj.join(",");
    }

    $scope.convertStringToObject = function (obj) {
        return angular.isNullorEmpty(obj) ? [] : obj.split(',');
    }

    // TFS 2921 DEV 1181 Change logo IE to Edge
    $scope.showBrowserCompality = function () {
    var img1 = '<img src="../../../images/Edge_Logo_2019.svg" width="21px" height="21px" alt="Edge Browser Logo" /> <a target="_blank" href="https://www.microsoft.com/en-us/edge/download">Microsoft Edge</a>';
    var img2 =
        '<img src="../../../images/chrome.svg" width="21px" height="21px" alt="Chrome Browser Logo" /> <a target="_blank" href="https://www.google.com/chrome/">Google Chrome</a>';
    var message =
        ("<div style='margin-bottom: 10px;'>" +
            "<b>CCFS Web Browser Support</b>" +
            "</div>" +
            "<p> We recommend using " +
            img1 +
            " or " +
            img2 +
            " (Mac and Windows) " +
            "for the best user experience with our Corporations and Charities Filing System (CCFS). " +
            "<u>For security reasons we do not support any versions of Internet Explorer.</u>" +
            "</p>"
        ).fontcolor("green");
        wacorpService.customAlertDialog(message);
    };
    // TFS 2921 DEV 1181 Change logo IE to Edge

    // TFS 2921 DEV 1181 Org Code
    //$scope.showBrowserCompality = function () {
    //    var img2 = '<img src="../../../images/ie.svg" width="21px" height="21px" alt="IE Browser Logo" />';
    //    var img1 =
    //        '<img src="../../../images/chrome.svg" width="21px" height="21px" alt="Chrome Browser Logo" /> <a target="_blank" href="https://www.google.com/chrome/">Google Chrome</a>';
    //    var message =
    //    ("<div style='margin-bottom: 10px;'><b>CCFS Web Browser Support</b></div><p> We recommend using " +
    //        img1 +
    //        " (Mac and Windows) or " +
    //        img2 +
    //        " Microsoft Internet Explorer versions 9, 10, and 11 (Windows only) for the best user experience with our Corporations and Charities Filing System (CCFS). For security reasons we do not support any versions of Internet Explorer below version 9.</p>"
    //    ).fontcolor("green");
    //    wacorpService.customAlertDialog(message);
    //};
    // TFS 2921 DEV 1181 Org Code
});
/*
Author      : Kishore Penugonda
File        : accountController.js
Description : business logic for login,forgot password,forgot user and change password screens 
*/

wacorpApp.controller('accountController', function accountController($scope, membershipService, $rootScope, wacorpService, focus, $location, $cookies) {

    $scope.user = {};
    $scope.filer = {};
    //$scope.user.Username = 'Admin@1234';
    //$scope.user.Password = 'Admin@12345';
    $scope.messages = messages;
    $scope.selection = "";
    $scope.validateErrorMsg = false;
    $scope.isPassowrdRequired = false;
    $scope.key = {};
    var showPasswordUpdateRequiedMessage = true; //TFS 2803 Force Password Reset, flag so only shows the pop-up once

    // ************************************************************************Login Functionality****************************************************************************//

    // login initialization
    $scope.InitLogin = function () {
        // TFS id OSOS ID--2577 (27635)
        var rememberObj = $cookies.get('rememberme');
        if (rememberObj != undefined) {
            var userObj = JSON.parse(rememberObj);
            if (userObj.Username) {
                $scope.rememberme = true;
                $scope.user.Username = userObj.Username;
                //$scope.user.Password = userObj.Password;
            }
        }

        var queryPrams = $location.search();
        var key = queryPrams.key;
        // $scope.user.ActivationKey = encodeURI(queryPrams.key);
        $scope.user.ActivationKey = queryPrams.key;
        if (key) {
            //  $scope.verifyEmail(key);          
            $scope.verifyEmail();// verifyEmail method is available in this controller only.
        }
        else {
            focus('txtUsername');
        }
    };

    // check login
    $scope.login = function (loginForm) {
        // TFS id OSOS ID--2577 (27635)
        if ($scope.rememberme) {
            var now = new Date();
            var exp = new Date(now.getFullYear(), now.getMonth() + 6, now.getDate());
            $cookies.put('rememberme', JSON.stringify($scope.user), { expires: exp });
        }
        else {
            $cookies.remove('rememberme');
        }

        $scope.isShow = false;
        $scope.validateErrorMsg = true;
        if ($scope[loginForm].$valid) {
            $scope.validateErrorMsg = false;
            // getLogin method is available in constants.js
            wacorpService.post(webservices.UserAccount.getLogin, $scope.user, function (response) {
                var result = response.data;
                $scope.filer = response.data;
                if (result.IsSucess && result.IsEmailVerified) {
                    $scope.user = result.Result;
                    // Service Folder: services
                    // File Name: membershipService.js (you can search with file name in solution explorer)
                    membershipService.saveCredentials($scope.user);
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)
                    $scope.userData.displayUserInfo();
                    // Folder Name: controller
                    // Controller Name: rootController.js (you can search with file name in solution explorer)    

                    $rootScope.repository.loggedUser.IsTempPassword = $scope.user.IsTempPassword;  //TFS 2803 Force Password Reset

                    $scope.navDashboard();

                } else if (result.IsEmailVerified && !result.IsSucess) {
                    $('.modal').css('display', 'none');
                    wacorpService.alertDialog(result.Message.Text);
                } else if (result.IsSucess && !result.IsEmailVerified) {
                    $('.modal').css('display', 'block');
                }
                else {
                    $('.modal').css('display', 'none');
                    // Folder Name: services
                    // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(result.Message.Text);
                }

            }, function (error) {
                // Folder Name: services
                // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(error.data);
            });
        }
    };



    // ************************************************************************Email Resend  Functionality****************************************************************************//


    // Resend Email verification to filer
    $scope.resendEmail = function () {
        $scope.isShow = false;
        $scope.validateErrorMsg = true;
        // resendEmail method is available in constants.js
        wacorpService.post(webservices.UserAccount.resendEmail, $scope.filer.Result, function (response) {
            var result = response.data;
            if (result == "true") {
                $('.modal').css('display', 'none');
                var message = ("A verification email is sent to your registered email ID successfully. Please click on the link provided in the email to activate your account.").fontcolor("green");
                // Folder Name: services
                // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(message);
            }
            else {
                // Folder Name: services
                // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog("Please try again.");
            }
        }, function (error) {
            // Folder Name: services
            // Controller Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });
    };

    $scope.closepopup = function () {
        $('.modal').css('display', 'none');
    };





    // ************************************************************************verifying Email Functionality****************************************************************************//


    //   email verification activation  
    $scope.verifyEmail = function () {
        // verifyEmail method is available in constants.js
        wacorpService.post(webservices.UserAccount.verifyEmail, $scope.user, function (response) {

            var result = response.data;
            // If flag = 2 account is activated successfully.
            if (result.Result.Flag == 2) {
                var message = ("Your account " + result.Result.Username.bold() + " is activated successfully. You may now login into your account.").fontcolor("green");
                // Folder Name: services
                // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(message);
                $location.search('key', null);
            }
            // If flag = 1 account is already activated.
            else if (result.Result.Flag == 1) {
                var message = ("Your account " + result.Result.Username.bold() + " is already activated. You can directly login into your account.").fontcolor("green");
                // Folder Name: services
                // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(message);
                $location.search('key', null);
            } else {
                var message = ("Please try again.").fontcolor("green");
                // Folder Name: services
                // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(message);
            }
        }, function (error) {
            // Folder Name: services
            // Controller Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data.MessageDetail);
        });
    };





    // ************************************************************************Forgot Password Functionality****************************************************************************//

    // forgot password
    $scope.resetPassword = function (forgotpwdform) {
        $scope.validateErrorMsg = true;
        if ($scope[forgotpwdform].$valid) {
            // resetPassword method is available in constants.js
            wacorpService.post(webservices.UserAccount.resetPassword, $scope.user, function (response) {
                $scope.validateErrorMsg = false;
                $scope.isErrors = false;
                if (response.data.IsSucess == true) {
                    $scope.user.FirstName = response.data.Result.FirstName;
                    $scope.user.LastName = response.data.Result.LastName;
                    $scope.showSuccessAlert = true;
                    $scope.successTextAlert = $scope.messages.ChangePassword.passwordReset;
                    $scope.selection = ResultStatus.SUCCESS;
                }
                else
                    // Folder Name: services
                    // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data.Message.Text);
            }, function (error) {
                // Folder Name: services
                // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.serverError);
            });
        }
    };


    // ************************************************************************Forgot User Functionality********************************************************************//
    // forgot user
    $scope.sendUserId = function (forgotuserform) {
        $scope.validateErrorMsg = true;
        if ($scope[forgotuserform].$valid) {
            $scope.validateErrorMsg = false;
            // sendUserId method is available in constants.js
            wacorpService.post(webservices.UserAccount.sendUserId, $scope.user, function (response) {
                if (response.data.Result) {
                    $scope.showSuccessAlert = true;
                    $scope.successTextAlert = $scope.messages.Account.userSentEmail.replace('{0}', $scope.user.EmailID);
                    $scope.selection = ResultStatus.SUCCESS;
                }
                else
                    // Folder Name: services
                    // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.ForgotUser.invalidEmail);
            }, function (error) {
                // Folder Name: services
                // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.serverError);
            });
        }
    };


    // *************************************************************************Change Password Functionality*********************************//
    //check the current password validation
    $scope.checkOldPassword = function () {
        var config = { params: { userid: $rootScope.repository.loggedUser.membershipid, password: $scope.user.Password } };
        if (config.params.password != null) {
            $scope.isPassowrdRequired = false;
            // isExistsPassword method is available in constants.js
            wacorpService.get(webservices.UserAccount.isExistsPassword, config, function (response) {
                $scope.invalidPasswordMsg = response.data == ResultStatus.TRUE ? "" : $scope.messages.ChangePassword.oldPassword;
            }, function (response) {
                // Folder Name: services
                // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.serverError);
            });
        }
        else {
            $scope.isPassowrdRequired = true;
        }

    }

    // update the password
    $scope.updatePassword = function (changePasswordForm) {
        var user = {
            MemberShipID: $rootScope.repository.loggedUser.membershipid,
            Username: $rootScope.repository.loggedUser.username,
            Password: $scope.user.Password,
            NewPassword: $scope.user.NewPassword
        };
        $scope.showChangePasswordErrorMessages = true;

        if ($scope.invalidPasswordMsg == "" || $scope.invalidPasswordMsg == undefined) {
            if ($scope[changePasswordForm].$valid) {
                $scope.showChangePasswordErrorMessages = false;
                // changePassword method is available in constants.js
                wacorpService.post(webservices.UserAccount.changePassword, user, function (response) {
                    if (response.data == ResultStatus.TRUE) {
                        wacorpService.alertDialog($scope.messages.ChangePassword.passwordUpdate);
                        // Folder Name: controller
                        // Controller Name: rootController.js (you can search with file name in solution explorer) 

                        //TFS 2803 Force Password Reset
                        $scope.user.IsTempPassword = false;
                        $rootScope.repository.loggedUser.IsTempPassword = $scope.user.IsTempPassword;
                        //TFS 2803 Force Password Reset

                        $scope.navDashboard();
                    }
                    else
                        // Folder Name: services
                        // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog($scope.messages.ChangePassword.passwordUpdateFailed);
                }, function (response) {
                    // Folder Name: services
                    // Controller Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.serverError);
                });
            }
        }
    }

    $scope.Init = function () {
        $scope.user.Username = $rootScope.repository.loggedUser.username;
        $scope.user.Password = null;
        focus('txtOldPassword');

        var url = $location.absUrl().split('?')[0];
    };


    //TFS 2803 Force Password Reset
    $(document).ready(function () {
        //TFS 2803 Force Password Reset
        if (($rootScope.repository.loggedUser != null && $rootScope.repository.loggedUser.IsTempPassword)
            || ($rootScope.repository.loggedUser != null && $rootScope.repository.loggedUser.IsTempPassword == null)
            || ($rootScope.repository.loggedUser != null && $rootScope.repository.loggedUser.IsTempPassword == "undefined")) {
            $scope.ForcePasswordReset();
            if (showPasswordUpdateRequiedMessage) {
                wacorpService.alertDialog("Password Update is Required.");
                showPasswordUpdateRequiedMessage = false;
            };
        };
        //TFS 2803 Force Password Reset
    });

    $scope.ForcePasswordReset = function () {
        if ($rootScope.repository.loggedUser) {
            //wacorpService.alertDialog($rootScope.repository.loggedUser.IsTempPassword);
            if ($rootScope.repository.loggedUser.IsTempPassword != "undefined") {
                if (!$rootScope.repository.loggedUser.IsTempPassword
                    && $rootScope.repository.loggedUser.IsTempPassword != null) {
                    $scope.navDashboard();
                } else {
                    $scope.navChangePassword();
                };
            } else {
                $scope.logout();
            };
        }
        
    };
    //TFS 2803 Force Password Reset

    //TFS 2803 Force Password Reset
    $scope.$on('$destroy', function LeavePasswordPage() {
        // After Login or on attempt to change page
        $scope.ForcePasswordReset();
    });
    //TFS 2803 Force Password Reset
});

/*
Author      : Kishore Penugonda
File        : registerController.js
Description : user registration, update user details
*/
wacorpApp.controller('registerController', function ($scope, $location, $rootScope, wacorpService, focus, $timeout) {

    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.searchType = $scope.searchType || "";
    $scope.businessSearchCriteria = { Type: searchTypes.BUSINESSNO, ID: "", IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, BusinessTypeId: constant.ZERO, IsOnline: true, SearchType: "CRARepresentedEntities", isSearchClick: false };
    $scope.selectedBusiness = null;
    $scope.search = loadbusinessList;
    $scope.searchval = '';
    $scope.isButtonSerach = false;
    $scope.sectionName = $scope.sectionName || '';
    focus("searchField");
    $scope.CRABusinessList = [];
    $scope.isRepresentedShowErrorFlag = false;


    $scope.user = {};
    $scope.user.Agent = {};
    $scope.user.UserPayment = {};
    $scope.user.AuthorizedPerson = {};
    $scope.user.BusinessList = [];
    var isUserAgent = false;
    $scope.filerTypes = filerType;
    $scope.isUserExistsMsg = "";
    $scope.selection = 'stage1';
    $scope.class1 = ResultStatus.COMPLETED;
    $scope.class2 = $scope.class3 = $scope.class4 = $scope.class5 = $scope.class6 = "";
    $scope.showSecurityErrorMessages = $scope.showLoginErrorMessages = $scope.showContactErrorMessages = false;
    $scope.header = "User Registration";
    $scope.WorkOrderNumber = ""; // work order number
    $scope.CountriesList = [];
    $scope.StatesList = [];
    $scope.businessTypes = [];
    $scope.isCRACountValidate = false;
    $scope.isLookupClicked = false;
    $scope.craNameAvailableMsg = false;
    $scope.unitedstates = "UNITED STATES";

    var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
    // GetLookUpData method is available in constants.js
    wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
        $scope.CountriesList = response.data;
    }, function (response) {
    });

    var lookupStatesParams = { params: { name: 'JurisdictionStates' } };
    // GetLookUpData method is available in constants.js
    wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
        $scope.StatesList = response.data;
    }, function (response) {
    });

    var config = { params: { name: 'AdvancedBusinessType' } };
    // GetLookUpData method is available in constants.js
    wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.businessTypes = response.data; });

    // next step
    $scope.gotoStep = function (nextStage, num) {
        //OSOS ID--3135
        $scope.showSecurityErrorMessages = false;
        $scope.showLoginErrorMessages = false;
        $scope.showContactErrorMessages = false;
        $scope.showErrorMsg = false;
        $scope.selection = nextStage;
        $scope.activeClass(num);
    };

    $scope.backFromPayment = function () {
        $scope.isPaymentZone = false;
        $scope.gotoStep('stage4', constant.FOUR);
    };


    // back to prev step
    $scope.backTo = function (stage) {
        $scope.selection = stage;
    };

    // active the current step class
    $scope.activeClass = function (num) {
        for (var i = constant.ONE; i <= constant.FIVE; i++) {
            $scope["class" + i] = (i <= num) ? ResultStatus.COMPLETED : "";
        }
    }

    //select the account type
    $scope.submitAccountType = function (type) {       
        $scope.user.FilerTypeId = type;
        switch (type) {
            case "RA":
                $scope.header = userRegistrationHeaders.FI;
               // $scope.Url = "RA";
                //$scope.UrlDesc = " (RCW 23.95.415)";
                isUserAgent = true;
                break;
            case "CA":
                $scope.header = userRegistrationHeaders.CA;
                $scope.Url = "http://app.leg.wa.gov/RCW/supdefault.aspx?cite=23.95.420";
                $scope.UrlDesc = " (RCW 23.95.420)";
                isUserAgent = true;
                $scope.user.FilingType = filerType.CommercialListingStatement;
                $scope.user.IsAdditionalDocumentsExist = false;
                $scope.user.AuthorizedPerson = {};
                $scope.user.AuthorizedPerson.PersonType = "I";
                $scope.user.Agent = {};
                $scope.user.Agent.JurisdictionCountry = usaCode;

                //Filing Fee for CRA
                data = { params: {} };
                // GetRegistrationCRAFeeDetails method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.GetRegistrationCRAFeeDetails, data, function (response) {
                    $rootScope.Transaction = response.data;
                }, function (response) { });
                break;
            case "FI":
                //$scope.header = userRegistrationHeaders.FI;
                $scope.header = "User Registration";
                $scope.Url = "FI";
                isUserAgent = false;
                break;
            default:
                $scope.header = "User Registration";
                isUserAgent = false;
                break;
        }
        //if (type === $scope.filerTypes.Filer) {
        //    $scope.gotoStep('stage2', constant.TWO);
        //    focus('txtFirstName');
        //}
        //else
        $("#divAgentType").modal('toggle');
    };

    //select the agent type
    $scope.selectAgentType = function () {
        $scope.showErrorMsg = true;
        if ($scope["AgentTypeForm"].$valid) {
            $("#divAgentType").modal('toggle');
            $scope.gotoStep('stage2', constant.TWO);
            focus('txtFirstName');
        }
    };

    //Continue registration
    $scope.continueRegistration = function (form) {        
        switch (form) {
            case "userSecurityForm":
                $scope.showSecurityErrorMessages = true;

                if ($scope.user.FilerTypeId == 'CA') {
                    $scope.user.Agent.BusinessType = $scope.selectedJurisdiction($scope.businessTypes, $scope.user.Agent.BusinessTypeID);
                    var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.user.Agent.JurisdictionCountry);
                    if (countryDesc == $scope.unitedstates) {
                        var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.user.Agent.JurisdictionState);
                        $scope.user.Agent.Jurisdiction = angular.copy($scope.user.Agent.JurisdictionState);
                        $scope.user.Agent.JurisdictionDesc = angular.copy(stateDesc);
                        $scope.user.Agent.JurisdictionStateDesc = angular.copy(stateDesc);
                        $scope.user.Agent.JurisdictionCountryDesc = angular.copy(countryDesc);
                        $scope.user.Agent.JurisdictionCategory = 'S';
                    }
                    else {
                        $scope.user.Agent.Jurisdiction = angular.copy($scope.user.Agent.JurisdictionCountry);
                        $scope.user.Agent.JurisdictionDesc = angular.copy(countryDesc);
                        $scope.user.Agent.JurisdictionCountryDesc = angular.copy(countryDesc);
                        $scope.user.Agent.JurisdictionStateDesc = null;
                        $scope.user.Agent.JurisdictionCategory = 'C';
                    }

                    $scope.isRepresentedShowErrorFlag = false;

                    //Upload Additional Documents
                    var isAdditionalUploadValid = $scope.user.IsAdditionalDocumentsExist ? ($scope.user.IsAdditionalDocumentsExist && $scope.user.UploadDocumentsList != null && $scope.user.UploadDocumentsList.length > constant.ZERO) : true;

                    var isJurisdictionFormValid = ($scope.user.Agent.AgentType == 'E' ? $scope[form].JurisdictionForm.$valid : true);

                    var isBusinessTypeFormValid = ($scope.user.Agent.AgentType == 'E' ? $scope[form].BusinessTypeForm.$valid : true);

                    var craNameValid = !$scope.isCRACountValidate;

                    var craLookupValid = $scope.isLookupClicked;

                    var isRegisteredAgentValid = $scope[form].registerAgentForm.$valid;

                    var isAuthorizedPersonValid = $scope[form].AuthorizedPersonForm.$valid;

                    if ($scope[form].$valid && isJurisdictionFormValid && isBusinessTypeFormValid && craNameValid && craLookupValid && isAdditionalUploadValid
                        && isRegisteredAgentValid && isAuthorizedPersonValid) {
                        $scope.showSecurityErrorMessages = false;
                        $scope.craNameAvailableMsg = false;
                        $scope.gotoStep('stage4', constant.FOUR);
                        focus('txtUserID');
                    }
                    else
                        // Folder Name: app Folder
                        // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
                        wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
                }
                else {
                    if ($scope[form].$valid) {
                        $scope.showSecurityErrorMessages = false;
                        $scope.gotoStep('stage4', constant.FOUR);
                        focus('txtUserID');
                    }
                }
                break;
            case "userLoginForm":
                $scope.showLoginErrorMessages = true;
                if ($scope[form].$valid) {
                    $scope.showLoginErrorMessages = false;
                    isExistsUser(); // isExistsUser method available in this controller only.
                }
                break;
            case "userContactForm":
                $scope.showContactErrorMessages = true;
                //$rootScope.$broadcast("InvokeMethod");
                if ($scope.user.FilerTypeId == 'CA') {
                    $scope.registerUser(); // registerUser method is available in this controller only.
                }
                else {
                    $scope.user.Address.isUserNonCommercialRegisteredAgent = isUserAgent;
                    $scope.user.AltAddress.isUserNonCommercialRegisteredAgent = isUserAgent;

                    if ($scope[form].$valid) {
                        $scope.showContactErrorMessages = false;

                        var successInnerFunction = function (data) {
                            $scope.user.AltAddress.IsValidAddress = false;
                            if (!$scope.user.Address.IsValidAddress) {
                                $scope.registerUser(); // registerUser method is available in this controller only.
                            }
                        };
                        var failureInnerFunction = function (error) {
                            $scope.user.AltAddress.IsValidAddress = true;
                        };

                        var successFunction = function (data) {
                            $scope.user.Address.IsValidAddress = false;
                            if (!angular.isNullorEmpty($scope.user.AltAddress.StreetAddress1) && !angular.isNullorEmpty($scope.user.AltAddress.Zip5)) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                var resultAltAddress = wacorpService.validateAddressOnRegister($scope.user.AltAddress);
                                resultAltAddress.then(successInnerFunction, failureInnerFunction);
                            }
                            else {
                                if ($scope.user.AltAddress.IsValidAddress) {
                                    $scope.user.AltAddress.IsValidAddress = false;
                                }
                                $scope.registerUser();  // registerUser method is available in this controller only.
                            }
                        };
                        var failureFunction = function (error) {
                            $scope.user.Address.IsValidAddress = true;
                            if (!angular.isNullorEmpty($scope.user.AltAddress.StreetAddress1) && !angular.isNullorEmpty($scope.user.AltAddress.Zip5)) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                var resultAltAddress = wacorpService.validateAddressOnRegister($scope.user.AltAddress);
                                resultAltAddress.then(successInnerFunction, failureInnerFunction);
                            }
                            else {
                                if ($scope.user.AltAddress.IsValidAddress) {
                                    $scope.user.AltAddress.IsValidAddress = false;
                                }
                            }
                        };
                        if ($scope.user.Address != null) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            var result = wacorpService.validateAddressOnRegister($scope.user.Address);
                            result.then(successFunction, failureFunction);
                        }
                    }
                }
                break;
            default:
        }
    };

    // trim the mobile
    function trimMobile() {
        $scope.user.PhoneNumber = angular.isNullorEmpty($scope.user.PhoneNumber) ? null : $scope.user.PhoneNumber.replace(/-/g, '');
        $scope.user.BusinessNumber = angular.isNullorEmpty($scope.user.BusinessNumber) ? null : $scope.user.BusinessNumber.replace(/-/g, '');
        $scope.user.CellPhoneNumber = angular.isNullorEmpty($scope.user.CellPhoneNumber) ? null : $scope.user.CellPhoneNumber.replace(/-/g, '');
    }

    //register the user
    $scope.registerUser = function () {
        $scope.user.IsOnline = true;
        $scope.user.SecurityQuestionId = constant.ONE;
        $scope.user.CreatedBy = constant.ONE;
        trimMobile();
         
        // get review HTML
        var $reviewHTML = $(".craReview");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.user.ReviewHTML = $reviewHTML.html() == undefined ? '' : $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");

        $scope.user.isIndividual = $scope.user.Agent.AgentType != 'E' ? true : false;
       // $scope.user.Agent.AgentType = $scope.user.FilerTypeId == filerType.Filer ? ResultStatus.INDIVIDUAL : $scope.user.Agent.AgentType;
        $scope.user.Agent.IsNonCommercial = ($scope.user.FilerTypeId == filerType.NonCommercialRegisteredAgent)
                                            || ($scope.user.FilerTypeId == filerType.Filer);
        $scope.user.Agent.CreatedBy = $scope.user.CreatedBy;
        if ($scope.user.FilerTypeId == filerType.CommercialRegisteredAgent) {
            $scope.user.FirstName = $scope.user.Agent.FirstName;
            $scope.user.LastName = $scope.user.Agent.LastName;
            $scope.user.EntityName = $scope.user.Agent.EntityName;
            

            $scope.user.EmailID = $scope.user.Agent.EmailAddress;
            $scope.user.ConfirmEmailAddress = $scope.user.Agent.EmailAddress;
            $scope.user.CRABusinessList = $scope.CRABusinessList;

            $scope.user.RegistrationFee = $rootScope.Transaction.FilingFee;
            $scope.user.FilingType = filerType.CommercialListingStatement;
            $scope.user.FilingTypeId = filingTypeIDs.COMMERCIALLISTINGSTATEMENT;
            $scope.user.BusinessTypeID = businessTypeIDs.COMMERCIALREGISTEREDAGENT;
            $rootScope.payment = {};
            $rootScope.payment.cartItems = angular.copy($scope.user);
            $rootScope.payment.Amount = $rootScope.Transaction.FilingFee;
            $rootScope.payment.isUserPayment = true;
            $scope.isPaymentZone = true;
        }
        else
            $scope.saveUser();  // saveUser method is available in this controller only.
    };

    $scope.saveUser = function () {
        
        $scope.user.Address.State = (!angular.isNullorEmpty($scope.user.Address.OtherState) ? "" : $scope.user.Address.State ? $scope.user.Address.State : codes.WA);
        $scope.user.AltAddress.State = (!angular.isNullorEmpty($scope.user.AltAddress.OtherState) ? "" : $scope.user.AltAddress.State ? $scope.user.AltAddress.State: codes.WA);
      
        // saveUserRegistration method is available in constants.js
        wacorpService.post(webservices.UserAccount.saveUserRegistration, $scope.user, function (response) {
            
            if (response.data.Result !=undefined && response.data.Result.ID > constant.ZERO) {
                $scope.gotoStep('stage5', constant.FIVE);
                var message = ("A verification email has been sent to the email address provided.  Please click on the link provided in the email to activate your account.").fontcolor("green");
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(message);
            }
            else if (response != null && response.data != null && response.data.Message != null && response.data.Message.Text != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data.Message.Text);
            }
            else
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);

        }, function (error) {
            $scope.isexception = true;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });
    };

    $scope.makeUserPayment = function (paymentModel) {

        $scope.user.UserPayment = paymentModel;
        // work order number
        $scope.user.UserPayment.WorkOrderNumber = $scope.WorkOrderNumber;

        $scope.user.UserPayment.BusinessTransactions[0].DocumentsList = $rootScope.Transaction.DocumentsList
       
        wacorpService.post(webservices.UserAccount.saveUserRegistration, $scope.user, function (regResponse) {
            // work order number
            $scope.WorkOrderNumber = regResponse.data.Result.UserPayment.WorkOrderNumber
            
            if ($scope.user.FilerTypeId == 'CA') {
                if (regResponse.data.IsSucess) {
                    $scope.isPaymentZone = false;
                    $scope.user = regResponse.data.Result;
                    $scope.gotoStep('stage5', constant.FIVE);
                }
                else {
                    // Payment Amount Mismatched
                    $rootScope.isPlaceYourOrderButtonDisable = false;
                    // If statusMode = 1 is Payment Amount MisMatch
                    if (regResponse.data.Message.StatusMode == 1) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog($scope.messages.ShoppingCart.PaymentAmountMisMatch);
                    }
                    else if (regResponse.data.Message.Text == null || regResponse.data.Message.Text == "" || regResponse.data.Message.Text == "<br/>") {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog($scope.messages.ShoppingCart.payment);
                    } else {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(regResponse.data.Message.Text);
                    }
                }
            }
            else {
                if (regResponse.data.Result.ID > constant.ZERO) {
                    $scope.isPaymentZone = false;
                    $scope.gotoStep('stage5', constant.FIVE);
                    var message = ("A verification email has been sent to the email address provided.  Please click on the link provided in the email to activate your account.").fontcolor("green");
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(message);

                }
                else {
                    if (regResponse.data.Message.Text == null || regResponse.data.Message.Text == "" || regResponse.data.Message.Text == "<br/>") {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog($scope.messages.ShoppingCart.payment);
                    } else {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(regResponse.data.Message.Text);
                    }
                }
            }
        }, function (error) {
            $rootScope.isPlaceYourOrderButtonDisable = false;
            $scope.isexception = true;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });
    }

    // cancel the registration
    $scope.cancelRegistration = function () {
        $scope.user = {};
        $scope.gotoStep('stage1', constant.ONE);
    };

    //clear contact information
    $scope.clearContactInformation = function () {
        $scope.user.FirstName = "";
        $scope.user.LastName = "";
        $scope.user.EmailID = "";
        $scope.user.ConfirmEmailAddress = "";
        $scope.user.PhoneNumber = "";
        $scope.user.BusinessNumber = "";
        $scope.user.PhoneNumberExt = ""; // Issue 18002 
        $scope.user.BusinessNumberExt = "";
        $scope.user.CellPhoneNumber = "";
        $scope.user.EntityName = "";
        $scope.user.Agent.EntityName = "";
    };

    // Return to Home
    $scope.gotoHome = function () {
        //wacorpService.confirmDialog($scope.messages.Register.goHomeConfirmation, function () {
        $location.path('/public/Home');
        //});
    };

    // check the user exists or not
    function isExistsUser() {
        var result = false;
        $rootScope.RegisteredUserName = '';
        $rootScope.RegisteredUserName = $scope.user.Username;
        var config = { params: { username: $scope.user.Username, } };
        // isUserExists method is available in constants.js
        wacorpService.get(webservices.UserAccount.isUserExists, config, function (response) {
            result = response.data == ResultStatus.TRUE ? true : false;
            if (result) {
                $scope.isUserExistsMsg = $scope.messages.Register.userExists;
            }
            else {
                $scope.showLoginErrorMessages = false;
                $scope.isUserExistsMsg = "";
                $scope.gotoStep('stage3', constant.THREE);
            }

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            return result;
        });
        return result;
    }

    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
    //$scope.setPastedUBI = function (e) {
    //    var pastedText = "";
    //    if (typeof e.originalEvent.clipboardData !== "undefined") {
    //        pastedText = e.originalEvent.clipboardData.getData('text/plain');
    //        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
    //        $scope.user.Agent.UBINumber = pastedText;
    //        e.preventDefault();
    //    } else {
    //        $timeout(function () {
    //            pastedText = angular.element(e.currentTarget).val();
    //            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
    //            $scope.user.Agent.UBINumber = pastedText;
    //        });
    //    }
    //};
    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036

    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
    //$scope.setUBILength = function (e) {
    //    if ($scope.user.Agent.UBINumber.length != undefined && $scope.user.Agent.UBINumber.length != "" && $scope.user.Agent.UBINumber.length!=null && $scope.user.Agent.UBINumber.length >= 9) {
    //        // Allow: backspace, delete, tab, escape, enter and .
    //        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
    //            // Allow: Ctrl+A, Command+A
    //            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
    //            // Allow: home, end, left, right, down, up
    //            (e.keyCode >= 35 && e.keyCode <= 40)) {
    //            // let it happen, don't do anything
    //            return;
    //        }
    //        // Ensure that it is a number and stop the keypress
    //        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    //            e.preventDefault();
    //        }
    //        e.preventDefault();
    //    }

    //};
    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036

    $scope.isLookupValid = false;

    $scope.searchCommercialAgents = function searchCommercialAgents(registerAgentForm) {
      
        $scope.isCRACountValidate = false;
        $scope.isLookupClicked = true;
        
        if ($scope.user.Agent.AgentType) {

            if ($scope.user.Agent.AgentType == 'E' && $scope.user.Agent.EntityName == undefined) {
                $scope.isLookupValid = true;
                return false;
            }
            else if ($scope.user.Agent.AgentType == 'I' && ($scope.user.Agent.FirstName == undefined || $scope.user.Agent.LastName == undefined)) {
                $scope.isLookupValid = true;
                return false;
            }
            else {
                $scope.isLookupValid = false;
                var criteria = {
                    FirstName: ($scope.user.Agent.AgentType == 'E' ? '' : $scope.user.Agent.FirstName || ''), LastName: ($scope.user.Agent.AgentType == 'E' ? '' : $scope.user.Agent.LastName || ''), BusinessName: ($scope.user.Agent.AgentType == 'E' ? $scope.user.Agent.EntityName || '' : ''),
                };
                wacorpService.post(webservices.Common.getCommercialAgentAvailableOrNot, criteria,
                    function (response) {
                        if (response.data != null) {
                            $scope.user.Agent.TotalCount = angular.copy(response.data);

                            if ($scope.user.Agent.TotalCount != '0' && $scope.user.Agent.TotalCount != undefined) {
                                $scope.isCRACountValidate = true;
                                $scope.craNameAvailableMsg = false;
                            }
                            else {
                                $scope.isCRACountValidate = false;
                                $scope.craNameAvailableMsg = true;
                            }
                        }
                        else// Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog($scope.messages.noDataFound);
                    },
                    function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    }
                );
            }
        }

    }

    $scope.enableIndividualLookup = function () {
        if ($scope.user.Agent.AgentType == "I") {
            $scope.isLookupClicked = false;
            $scope.craNameAvailableMsg = false;
            $scope.isCRACountValidate = false;
        }
    }

    $scope.enableEntityLookup = function () {
        if ($scope.user.Agent.AgentType == "E" && $scope.user.Agent.EntityName != "") {
            $scope.isLookupClicked = false;
            $scope.craNameAvailableMsg = false;
            $scope.isCRACountValidate = false;
        }
    }

    var agentResetScope = {
        AgentID: constant.ZERO, EntityName: null, FirstName: null, LastName: null, IsNonCommercial: false, EmailAddress: null,
        ConfirmEmailAddress: null, AgentType: ResultStatus.INDIVIDUAL, AgentTypeID: constant.ZERO,
        StreetAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
            baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null, State: codes.WA, OtherState: null,
            Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        MailingAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
            baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null, State: codes.WA, OtherState: null,
            Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        IsUserRegisteredAgent: false, PhoneNumber: null, IsRegisteredAgentConsent: true , Title: null, IsSameAsMailingAddress: false,//TFS 1143 original -> IsRegisteredAgentConsent: false
        CreatedBy: null, AgentCreatdDate: null, AgentCreatdIP: null, IsNewAgent: false
    };

    //Copy the Street  address to  Mailing Address
    $scope.CopyAgentMailingFromStreet = function () {
        if ($scope.user.Agent.IsSameAsMailingAddress)
            angular.copy($scope.user.Agent.StreetAddress, $scope.user.Agent.MailingAddress);
        else
            angular.copy(agentResetScope.MailingAddress, $scope.user.Agent.MailingAddress);

        if ($scope.user.Agent.IsSameAsMailingAddress)
            $scope.$broadcast("IsMailingRAAddress", true);
        else if (!$scope.user.Agent.IsSameAsMailingAddress)
            $scope.$broadcast("IsMailingRAAddress", false);
    };

    $scope.selectedJurisdiction = function (items, selectedVal) {
        var result = "";
        angular.forEach(items, function (item) {
            if (selectedVal == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }


    // Business Search

    // search business list
    $scope.searchBusiness = function () {
        if ($scope.businessSearchCriteria.ID == "" || $scope.businessSearchCriteria.ID == null) {
            $scope.isRepresentedShowErrorFlag = true;
            return false;
        }
        else {
            //if ($scope[userSecurityForm].searchform.$valid) {
                $scope.businessSearchCriteria.isSearchClick = true;
                $scope.isButtonSerach = true;
                $scope.selectedBusiness = null;
                $rootScope.selectedBusiness = null;
                $rootScope.selectedBusinessID = constant.ZERO;
                $scope.selectedBusinessID = constant.ZERO;
                loadbusinessList(constant.ZERO); // loadbusinessList method is available in this controller only. 
            //}
        }
    };
    //clear text on selecting radio button
    $scope.cleartext = function () {
        $scope.businessSearchCriteria.ID = null;
    };

    // clear fields
    $scope.clearFun = function () {
        $scope.businessSearchCriteria.ID = "";
        $scope.businessSearchCriteria.isSearchClick = false;
        $scope.isRepresentedShowErrorFlag = false;
    };

    // cancel popup
    $scope.cancelFun = function () {
        $("#divSearchResult").modal('toggle');
        $scope.selectedBusiness = null;
        $rootScope.selectedBusiness = null;
        $rootScope.selectedBusinessID = constant.ZERO;
        $scope.selectedBusinessID = constant.ZERO;
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
        $scope.selectedBusinessID = business.BusinessID;
        $rootScope.selectedBusinessID = $scope.selectedBusinessID;
        $rootScope.selectedBusiness = $scope.selectedBusiness;
    };

    $scope.submitBusiness = function () {
        $scope.isRepresentedShowErrorFlag = false;
        if ($scope.selectedBusiness && $scope.selectedBusiness.BusinessID != constant.ZERO) {
            if ($scope.CRABusinessList.length == constant.ZERO) {
                $scope.CRABusinessList.push($scope.selectedBusiness);
                $("#divSearchResult").modal('toggle');
            }
            else {
                var k = 0;
                $scope.CRABusinessList.forEach(function (element) {
                    if (element.BusinessID == $scope.selectedBusiness.BusinessID) {
                        k = k + 1;
                    }
                });

                if (k > 0) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.representedEntityExists);
                    return false;
                }
                else {
                    $scope.CRABusinessList.push($scope.selectedBusiness);
                    $("#divSearchResult").modal('toggle');
                    k = 0;
                }
            }
        }
    };

    //Delete business
    $scope.deleteBusiness = function (selectedBusiness) {
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
            var index = $scope.CRABusinessList.indexOf(selectedBusiness);
            $scope.CRABusinessList.splice(index, 1);
        });
    };

    // get business list data from server
    function loadbusinessList(page) {
        $scope.isRepresentedShowErrorFlag = false;
        page = page || constant.ZERO;
        $scope.businessSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        $scope.selectedBusiness = null;
        var data = angular.copy($scope.businessSearchCriteria);
        $scope.isButtonSerach = page == 0;
        data.ID = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID : $scope.searchval);
        // getBusinessNames method is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.selectedBusiness = null;

            $rootScope.searchCriteria = {
                searList: response, page: page,
                searchType: $scope.businessSearchCriteria.Type,
                searchValue: $scope.businessSearchCriteria.ID,
                pagesCount: $scope.pagesCount,

            };

            loadList($rootScope.searchCriteria);
            if (page == constant.ZERO)
                $("#divSearchResult").modal('toggle');
        }, function (response) {
            $scope.selectedBusiness = null;
            $scope.selectedBusinessID = constant.ZERO;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);           
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });

    }

    // select search type
    $scope.selectSearchType = function () {
        $scope.businessSearchCriteria.ID = "";
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == constant.ZERO) {
            $scope.totalCount = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.page = constant.ZERO;
        }
    }, true);

    $scope.setPastedUBISearch = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.businessSearchCriteria.ID = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.businessSearchCriteria.ID = pastedText;
            });
        }
    };

    function loadList(responseData, flag) {

        var response = responseData.searList;
        var page = responseData.page;
        if (flag) {
            $scope.businessSearchCriteria.Type = responseData.searchType;
            $scope.businessSearchCriteria.ID = responseData.searchValue;
        }

        $scope.BusinessList = response.data;
        if ($scope.isButtonSerach && response.data.length > 0) {
            var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
            var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                        ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
            $scope.pagesCount = response.data.length < $scope.businessSearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
            $scope.totalCount = totalcount;
            $scope.searchval = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID : $scope.searchval);

            //Putting all the code in rootscope for Back Button Purpose
            $rootScope.pagesCount = $scope.pagesCount;
            $rootScope.totalCount = $scope.totalCount;
            $rootScope.businessSearchCriteria = $scope.businessSearchCriteria;
            $rootScope.searchval = $scope.searchval
        }
        //Getting Data from rootscope for Back Button Purpose
        if (response.data.length > 0) {
            $scope.totalCount = $rootScope.totalCount;
            $scope.pagesCount = $rootScope.pagesCount;
            $scope.businessSearchCriteria = $rootScope.businessSearchCriteria;
            $scope.searchval = $rootScope.searchval;
        }

        $scope.selectedBusinessID = $rootScope.selectedBusinessID;
        $scope.selectedBusiness = $rootScope.selectedBusiness;
        $scope.page = page;
        $scope.BusinessListProgressBar = false;
        focus("tblBusinessSearch");
    }


    if ($rootScope.searchCriteria) {
        // $scope.isButtonSerach = true;
        // loadList method is available in this controller only.
        loadList($rootScope.searchCriteria, true);
        //  $scope.isButtonSerach = false;
        $scope.businessSearchCriteria.isSearchClick = true;
    }

    $scope.setUBILengthSearch = function (e) {
        //if ($scope.businessSearchCriteria.ID.length >= 9) {
        //    e.preventDefault();
        if ($scope.businessSearchCriteria.ID.length = undefined && $scope.businessSearchCriteria.ID.length != null && $scope.businessSearchCriteria.ID.length != "" && $scope.businessSearchCriteria.ID.length >= 9)
        {
            if (e.which != 97) {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                    // Allow: Ctrl+A, Command+A
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right, down, up
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
                e.preventDefault();
            }
        }
    };

    //select the agent type Individual
    $scope.selectAgentTypeIndividual = function () {
        $scope.user.Agent.EntityName = "";
    };

    //to clear RA mailing Address when Street address is modified:12/09/2018
    var clearUserRAStreetAddressOnChange = $scope.$on("clearUserRAStreetAddressOnChange", function (evt, data) {
        if ($scope.user.Agent.IsSameAsMailingAddress) {
            if (wacorpService.compareAddress($scope.user.Agent.StreetAddress, $scope.user.Agent.MailingAddress))
            {
                $scope.user.Agent.IsSameAsMailingAddress = false;
                $scope.CopyAgentMailingFromStreet();
            }
        }
        evt.defaultPrevented = true;
    });
    $scope.$on('$destroy', clearUserRAStreetAddressOnChange);

});

/*
Author      : Kishore Penugonda
File        : accountMaintenanceController.js
Description : user registration, update user details
*/

wacorpApp.controller('accountMaintenanceController', function ($scope, $rootScope, membershipService, wacorpService) {
    $scope.validateErrorMsg = false;
    $scope.messages = messages;
    $scope.user = {};
    $scope.masteruser = {};


    // *********Account Maintenance Functionality*************//
    $scope.initAccountMaintenance = function () {
        getUser();
    };

    // get logined user details
    function getUser() {

        var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
        // getUserDetails method is available in constants.js
        wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
            $scope.user = response.data;

            $scope.user.Agent.EntityName = response.data.FilerTypeId == "FI" ? response.data.Agent.OrganizationName : response.data.Agent.EntityName;
            $scope.user.Agent.AgentType = (response.data.FilerTypeId == "FI" ? ($scope.user.isIndividual == false ? "E" : "I") : response.data.Agent.AgentType);
            $scope.user.BusinessNumberExt = $scope.user.BusinessNumberExt.trim();
            $scope.user.PhoneNumberExt = $scope.user.PhoneNumberExt.trim();
            $scope.masteruser = angular.copy($scope.user);
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    // update the user
    $scope.updateUserAccount = function (userMaintenanceForm) {
        
        $scope.showErrorMessages = true;
        $scope.user.IsOnline = true;
        $scope.user.ConfirmEmailAddress = $scope.user.EmailID;
        $scope.user.ConfirmPassword = $scope.user.Password;
        $scope.user.SecurityQuestionId = constant.ONE;
        $scope.user.PhoneNumber = angular.isNullorEmpty($scope.user.PhoneNumber) ? null : $scope.user.PhoneNumber.replace(/-/g, '');
        $scope.user.BusinessNumber = angular.isNullorEmpty($scope.user.BusinessNumber) ? null : $scope.user.BusinessNumber.replace(/-/g, '');
        $scope.user.CellPhoneNumber = angular.isNullorEmpty($scope.user.CellPhoneNumber) ? null : $scope.user.CellPhoneNumber.replace(/-/g, '');
        $scope.user.CreatedBy = $rootScope.repository.loggedUser.membershipid;
        $scope.user.Agent.EntityName = $scope.user.FilerTypeId == "FI" ? $scope.user.Agent.EntityName : $scope.user.Agent.EntityName;
        if ($scope[userMaintenanceForm].$valid) {
            $scope.showErrorMessages = false;
            // updateAccount method is available in constants.js
            wacorpService.post(webservices.UserAccount.updateAccount, $scope.user, function (response) {
                if (response.data === ResultStatus.TRUE) {
                    $rootScope.repository.loggedUser.firstname = $scope.user.FirstName;
                    $rootScope.repository.loggedUser.lastname = $scope.user.LastName;
                    $rootScope.repository.loggedUser.FullUserName =  $scope.user.Agent.AgentType == "E" ? $scope.user.Agent.EntityName : $scope.user.FirstName + " " + $scope.user.LastName;
                    $rootScope.repository.loggedUser.userfullname = $scope.user.FirstName + ", " + $scope.user.LastName;
                    // Service Folder: services
                    // File Name: membershipService.js (you can search with file name in solution explorer)
                    membershipService.updateRepository();
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.Account.accountUpdate);
                }
                else {
                    $scope.isexception = true;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.Account.accountUpdateFailed);
                }
            }, function (response) {
                $scope.isexception = true;
                $scope.submission.errorMessages = response.data;
            });
        }
    };

    // cancel the update
    $scope.cancelUpdate = function () {
        $scope.user = angular.copy($scope.masteruser);
    };

});

wacorpApp.controller('accountActivationController', function accountActivationController($scope) {
    $scope.isActiveUser = true;

    $scope.Init = function () {

    }
});

/*
Author      : Kishore Penugonda
File        : inhouseAgentController.js
Description : user registration, update user details
*/
wacorpApp.controller('inhouseAgentController', function ($scope, $routeParams, $location, wacorpService) {
        
    $scope.user = {};
    $scope.user.Agent = {};
    $scope.user.UserPayment = {};
    $scope.filerTypes = filerType;
    $scope.isUserExistsMsg = "";
    $scope.selection = 'stage1';
    $scope.class1 = ResultStatus.COMPLETED;
    $scope.class2 = $scope.class3 = $scope.class4 = $scope.class5 = $scope.class6 = "";
    $scope.showSecurityErrorMessages = $scope.showLoginErrorMessages = $scope.showContactErrorMessages = false;

    $scope.initAgentRegistration = function () {
        var filerid = $routeParams.id;
        if (filerid > constant.ZERO)
            $scope.getFiler(filerid);
        else
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)           
            $scope.navHome();
    };

    // get filer details
    $scope.getFiler = function (id) {
        var data = { params: { filerid: id } };
        wacorpService.get(webservices.UserAccount.getFilerDetails, data, function (response) {
            if (response.data.MemberShipID > 0) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.Account.agentAlreadyCreated);
                // Folder Name: controller
                // Controller Name: rootController.js (you can search with file name in solution explorer)
                $scope.navHome();
                //wacorpService.alertDialog($scope.messages.Account.agentAlreadyCreated);
                //$scope.navHome();
            }
            else {
                $scope.user = response.data;
                $scope.user.BusinessNumberExt = $scope.user.BusinessNumberExt.trim();
                $scope.masteruser = angular.copy($scope.user);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    // next step
    $scope.gotoStep = function (nextStage, num) {
        $scope.selection = nextStage;
        $scope.activeClass(num);
    };

    // back to prev step
    $scope.backTo = function (stage) {
        $scope.selection = stage;
    };

    // active the current step class
    $scope.activeClass = function (num) {
        for (var i = constant.ONE; i <= constant.FOUR; i++) {
            if (i <= num)
                $scope["class" + i] = ResultStatus.COMPLETED;
            else
                $scope["class" + i] = "";
        }
    }


    //Continue registration
    $scope.continueRegistration = function (form) {
        switch (form) {
            case "userSecurityForm":
                $scope.showSecurityErrorMessages = true;
                if ($scope[form].$valid) {
                    $scope.showSecurityErrorMessages = false;
                    $scope.gotoStep('stage3', constant.THREE);
                }
                break;
            case "userLoginForm":
                $scope.showLoginErrorMessages = true;
                if ($scope[form].$valid) {
                    $scope.showLoginErrorMessages = false;
                    isExistsUser();
                }
                break;
            case "userContactForm":
                $scope.showContactErrorMessages = true;
                if ($scope[form].$valid) {
                    $scope.showContactErrorMessages = false;
                    $scope.registerUser();
                }
                break;
            default:
        }
    };

    // trim the mobile
    function trimMobile() {
        $scope.user.PhoneNumber = angular.isNullorEmpty($scope.user.PhoneNumber) ? null : $scope.user.PhoneNumber.replace(/-/g, '');
        $scope.user.BusinessNumber = angular.isNullorEmpty($scope.user.BusinessNumber) ? null : $scope.user.BusinessNumber.replace(/-/g, '');
        $scope.user.CellPhoneNumber = angular.isNullorEmpty($scope.user.CellPhoneNumber) ? null : $scope.user.CellPhoneNumber.replace(/-/g, '');
    }

    //register the user
    $scope.registerUser = function () {
        $scope.user.IsOnline = true;
        $scope.user.SecurityQuestionId = constant.ONE;
        $scope.user.CreatedBy = constant.ONE;
        trimMobile();
        $scope.saveUser();
    };

    $scope.saveUser = function () {
        // createAgentAccount method is available in constants.js
        wacorpService.post(webservices.UserAccount.createAgentAccount, $scope.user, function (response) {
            if (response.data.Result.ID > constant.ZERO) {
                $scope.gotoStep('stage4', constant.FOUR);
            }
            else
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);

        }, function (error) {
            $scope.isexception = true;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });
    };


    // cancel the registration
    $scope.cancelRegistration = function () {
        $scope.user = {};
        $scope.gotoStep('stage1', constant.ONE);
    };

     //clear contact information
    $scope.clearInfo =function () {
        $scope.user.FirstName = '';
        $scope.user.LastName = '';
        $scope.user.ConfirmEmailAddress = '';
        $scope.user.PhoneNumber = '';
        $scope.user.BusinessNumber = '';
        $scope.user.BusinessNumberExt = '';
        $scope.user.CellPhoneNumber = '';
    }
    // Return to Home
    $scope.gotoHome = function () {        
        wacorpService.confirmDialog($scope.messages.Register.goHomeConfirmation, function () {
            $location.path('/public/Home');
        });
    };

    // check the user exists or not
    function isExistsUser() {
        var result = false;
        var config = { params: { username: $scope.user.Username, } };
        // isUserExists method is available in constants.js
        wacorpService.get(webservices.UserAccount.isUserExists, config, function (response) {
            result = response.data == ResultStatus.TRUE ? true : false;
            if (result) {
                $scope.isUserExistsMsg = $scope.messages.Register.userExists;
            }
            else {
                $scope.showLoginErrorMessages = false;
                $scope.isUserExistsMsg = "";
                $scope.gotoStep('stage2', constant.TWO);
            }

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            return result;
        });
        return result;
    }

});

/*
Author      : Kishore Penugonda
File        : businessSearchController.js
Description : display business search results, business information, filing history and name changed history
*/
wacorpApp.controller('businessSearchController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    // variable initialization

    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
    $scope.businesssearchcriteria = {};
    $scope.transactionDocumentsList = [];

    //scope initialization
    $scope.initBusinessSearch = function () {
         
        $scope.businesssearchType = $cookieStore.get('businesssearchType');
        $scope.businesssearchcriteria = $cookieStore.get('businesssearchcriteria');
        $cookieStore.remove('cftSearchcriteria');
        $cookieStore.remove('cftAdvanceSearchcriteria');
        execCurrentPath(); // execCurrentPath method is availbale in this controller only.
    };

    function execCurrentPath() {
        
        if ($location.path() == "/BusinessSearch") {
            $scope.search = loadbusinessList;
            loadbusinessList($scope.page); // loadbusinessList method is availbale in this controller only.
        }
        if ($location.path() == "/BusinessSearch/BusinessInformation")
            $scope.businessInfo();
        if ($location.path() == "/BusinessSearch/BusinessFilings")
            $scope.businessFilings();
        if ($location.path() == "/BusinessSearch/BusinessNameHistory")
            $scope.businessNameHistoryList();
        if ($location.path() == "/BusinessSearch/AdvancedSearch") {
            $scope.businessStatusList();
        }
    }

    // display search results
    function loadbusinessList(page, sortBy) {
         
        page = page || 0;
        var criteria = null;
        if (sortBy != undefined) {
            if ($scope.businesssearchcriteria.SortBy == sortBy) {
                if ($scope.businesssearchcriteria.SortType == 'ASC') {
                    $scope.businesssearchcriteria.SortType = 'DESC';
                }
                else {
                    $scope.businesssearchcriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.businesssearchcriteria.SortBy = sortBy;
                $scope.businesssearchcriteria.SortType = 'ASC';
            }
        }
        else {
            if ($scope.businesssearchcriteria.searchtype == "BusinessName") {
                if ($scope.businesssearchcriteria.SortBy == null || $scope.businesssearchcriteria.SortBy == "" || $scope.businesssearchcriteria.SortBy == undefined)
                    $scope.businesssearchcriteria.SortBy = "Entity Name";
                if ($scope.businesssearchcriteria.SortType == null || $scope.businesssearchcriteria.SortType == "" || $scope.businesssearchcriteria.SortType==undefined)
                $scope.businesssearchcriteria.SortType = 'ASC';
            }
            else if ($scope.businesssearchcriteria.searchtype == "UBINumber") {
                if ($scope.businesssearchcriteria.SortBy == null || $scope.businesssearchcriteria.SortBy == "" || $scope.businesssearchcriteria.SortBy==undefined)
                    $scope.businesssearchcriteria.SortBy = "UBI #";
                if ($scope.businesssearchcriteria.SortType == null || $scope.businesssearchcriteria.SortType == "" || $scope.businesssearchcriteria.SortType==undefined)
                     $scope.businesssearchcriteria.SortType = 'ASC';
            }
        }
        var searchinfo = $scope.businesssearchcriteria;

        if ($scope.businesssearchType == "AdvancedSearch") {
            searchinfo.PageID = page == 0 ? 1 : page + 1;
            searchinfo.PageCount = 25;
            // getAdvanceBusinessSearchList is available in constants.js
            wacorpService.post(webservices.BusinessSearch.getAdvanceBusinessSearchList, searchinfo, function (response) {

                $scope.businessList = response.data;

                //TFS 2330 toggle display FEIN Column 
                $scope.IsFEINEnabled = false;
                angular.forEach(response.data, function (value, key) {
                    if (value.FEINNo != null && value.FEINNo != "") {
                        //wacorpService.alertDialog(value.FEINNo);
                        //wacorpService.alertDialog(key + ': ' + value);
                        $scope.IsFEINEnabled = true;
                    }
                });
                //TFS 2330

                if ($scope.totalCount == 0) {
                    var totalcount = response.data.length > 0 ? response.data[constant.ZERO].Criteria.TotalRowCount : 0;
                    if (totalcount != 0) {
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                        $scope.pagesCount = response.data.length < searchinfo.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                        $scope.totalCount = totalcount;
                        $scope.rowsperPage = 25;
                    }
                }
                //$scope.businesssearchcriteria.SearchValue = searchinfo.searchval;
                //$scope.businesssearchcriteria.Type = searchinfo.searchtype;
                $scope.page = page;
                $scope.BusinessListProgressBar = false;
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                searchResultsLoading(false);
            });
        }
        else {
            criteria = { Type: searchinfo.searchtype, SearchType: searchinfo.searchtype, SearchEntityName: searchinfo.searchval, SortType: searchinfo.SortType, SortBy: searchinfo.SortBy, SearchValue: searchinfo.searchval, SearchCriteria: searchinfo.searchcriteria, IsSearch: true, PageID: page == 0 ? 1 : page + 1, PageCount: 25 };
            // getBusinessSearchList is available in constants.js
            wacorpService.post(webservices.BusinessSearch.getBusinessSearchList, criteria, function (response) {
                $scope.businessList = response.data;

                //TFS 2330 toggle display FEIN Column 
                $scope.IsFEINEnabled = false;
                angular.forEach(response.data, function (value, key) {
                    if (value.FEINNo != null && value.FEINNo != "") {
                        //wacorpService.alertDialog(value.FEINNo);
                        //wacorpService.alertDialog(key + ': ' + value);
                        $scope.IsFEINEnabled = true;
                    }
                });
                //TFS 2330

                if ($scope.totalCount == 0) {
                    var totalcount = response.data.length > 0 ? response.data[constant.ZERO].Criteria.TotalRowCount : 0;
                    if (totalcount != 0) {
                        var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                    ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                        $scope.pagesCount = response.data.length < searchinfo.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                        $scope.totalCount = totalcount;
                        $scope.rowsperPage = 25;
                    }
                }
                $scope.businesssearchcriteria.SearchValue = searchinfo.searchval;
                $scope.businesssearchcriteria.Type = searchinfo.searchtype;
                $scope.page = page;
                $scope.BusinessListProgressBar = false;
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                searchResultsLoading(false);
            });
        }
    }

    // display business information 
    $scope.businessInfo = function () {
        
        var config = { params: { businessID: $scope.businesssearchcriteria.businessid } };
        var data = { params: { ReservationID: $scope.businesssearchcriteria.businessid } };
        if ($scope.businesssearchcriteria.businesstype != "Name Reservation")
            // getbusinessInformation is available in constants.js
            wacorpService.get(webservices.BusinessSearch.getbusinessInformation, config, function (response) {
                if (response.data != null) {
                    $scope.businessInfo = response.data;
                    $scope.businesssearchcriteria.businessname = $scope.businessInfo.BusinessName;
                    $scope.businesssearchcriteria.DBABusinessName = $scope.businessInfo.DBABusinessName;
                    $scope.businesssearchcriteria.ubinumber = $scope.businessInfo.UBINumber;
                    $scope.businessInfo.JurisdictionDesc = angular.isNullorEmpty($scope.businessInfo.JurisdictionDesc) ? "WASHINGTON" : $scope.businessInfo.JurisdictionDesc;
                    $scope.businessInfo.BINAICSCodeDesc = angular.isNullorEmpty($scope.businessInfo.BINAICSCodeDesc) ? "" : $scope.businessInfo.BINAICSCodeDesc.replace(/&amp;/g, "&");
                    $cookieStore.put('businesssearchcriteria', $scope.businesssearchcriteria);

                    angular.forEach($scope.businessInfo.PrincipalsList, function (value, key) {
                        $scope.executorCount = (value.PrincipalBaseType.toUpperCase() == "EXECUTOR")
                        $scope.governingPersonCount = (value.PrincipalBaseType.toUpperCase() == "GOVERNINGPERSON")
                        $scope.generalPartnerCount = (value.PrincipalBaseType.toUpperCase() == "GENERALPARTNER")
                        $scope.incorporatorCount = (value.PrincipalBaseType.toUpperCase() == "INCORPORATOR")
                        $scope.initialBoardOfDirectorCount = (value.PrincipalBaseType.toUpperCase() == "INITIALBOARDOFDIRECTOR")
                    });
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: noDataFound method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(messages.noDataFound);
                }
            }, function (response) { wacorpService.alertDialog(response.data); });
        else
            // getNameReservation_businessInformation is available in constants.js
            wacorpService.get(webservices.BusinessSearch.getNameReservation_businessInformation, data, function (response) {
                if (response.data != null) {
                    $scope.businessInfo = response.data;
                    $scope.businesssearchcriteria.businessname = $scope.businessInfo.BusinessName;
                    $scope.businesssearchcriteria.ubinumber = $scope.businessInfo.UBINumber;
                    $cookieStore.put('businesssearchcriteria', $scope.businesssearchcriteria);

                    angular.forEach($scope.businessInfo.PrincipalsList, function (value, key) {
                        $scope.executorCount = (value.PrincipalBaseType.toUpperCase() == "EXECUTOR")
                        $scope.governingPersonCount = (value.PrincipalBaseType.toUpperCase() == "GOVERNINGPERSON")
                        $scope.generalPartnerCount = (value.PrincipalBaseType.toUpperCase() == "GENERALPARTNER")
                        $scope.incorporatorCount = (value.PrincipalBaseType.toUpperCase() == "INCORPORATOR")
                        $scope.initialBoardOfDirectorCount = (value.PrincipalBaseType.toUpperCase() == "INITIALBOARDOFDIRECTOR")
                    });
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: noDataFound method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(messages.noDataFound);
                }
            }, function (response) { wacorpService.alertDialog(response.data); });

    };

    // get the principle header title
    $scope.getprincipalheaderTitle = function () {
        var config = { params: { BusinessTypeId: $scope.businessInfo.BusinessTypeID } };
        // PrincipalHeaderTitle method is available in constants.js
        wacorpService.get(webservices.Common.PrincipalHeaderTitle, config, function (response) {
            $scope.principalHeaderTitle = response.data;
        });
    };

    // display business filings
    $scope.businessFilings = function () {
        var businesstype = $scope.businesssearchcriteria.businesstype;
        var config = { params: { businessId: $scope.businesssearchcriteria.businessid, IsOnline: true } };
        if (businesstype != "Name Reservation")
            // getBusinessFilingList is available in constants.js
            wacorpService.get(webservices.BusinessSearch.getBusinessFilingList, config, function (response) {
                if (response.data != null) {
                    $scope.businessFilings = response.data;
                }
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
    };

    // display business names history list
    $scope.businessNameHistoryList = function () {
        var config = { params: { businessId: $scope.businesssearchcriteria.businessid } };
        // getBusinessNameHistoryList is available in constants.js
        wacorpService.get(webservices.BusinessSearch.getBusinessNameHistoryList, config, function success(response) {
            if (response.data.length > 0) {
                $scope.businessNameHistoryList = response.data;
            }
        }, function failed(response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data)
        });
    }


    $scope.exportCSVServer = function () {
        var criteria = null;
        var searchinfo = angular.copy($scope.businesssearchcriteria);
        if ($scope.businesssearchType == "AdvancedSearch") {
            searchinfo.PageID = 1;
            searchinfo.PageCount = 9999999;
            // getAdvanceBusinessSearchList method is availble in constants.js
            wacorpService.post(webservices.BusinessSearch.getAdvanceBusinessSearchList, searchinfo, function (response) {
                var result = [];
                result = response.data;         
                $rootScope.exportToCSV(result)

            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);

            });
        }
        else {
            searchinfo.PageID = 1;
            searchinfo.PageCount = 9999999;
            criteria = { Type: searchinfo.searchtype, SearchType: searchinfo.searchtype, SearchEntityName: searchinfo.searchval, SearchValue: searchinfo.searchval, SearchCriteria: searchinfo.searchcriteria, IsSearch: true, PageID: searchinfo.PageID, PageCount: 9999999 };
            // getBusinessSearchList method is available in constants.js
            wacorpService.post(webservices.BusinessSearch.getBusinessSearchList, criteria, function (response) {
                var result = [];
                result = response.data;                
                $rootScope.exportToCSV(result)
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);

            });
        }

    }

    //Export Data to CSV
    $rootScope.exportToCSV = function (exportData) {

        var arrData = typeof exportData != 'object' ? JSON.parse(exportData) : exportData;

        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
        });

        var CSV = '';
        var row = "";

        var rowData = "";
        //Preapring Candidate Data
        var arrData1 = [];
        candidateColumns = ["Business Name", "UBI#", "Business Type", "Principal Office Address", "Registered Agent Name", "Status", "FEIN"];  //TFS 2330
        $.each(arrData, function (index, element) {

            arrData1.push({
                "Business Name": element.BusinessName, "UBI#": element.UBINumber, "Business Type": element.BusinessType, "Principal Office Address": element.PrincipalOffice.PrincipalStreetAddress.FullAddress,
                "Registered Agent Name": element.AgentName, "Status": element.BusinessStatus, "FEIN": element.FEINNo  //TFS 2330

            })
        });
        $.each(arrData1, function (index, Data) {

            rowData = "";
            $.each(Data, function (headerName, Data) {
                if (candidateColumns.indexOf(headerName) != -1) {
                    if (index == 0) {
                        if (headerName == "Business Name") {
                            headerName = "Business Name";
                        }
                        else if (headerName == "UBI#") {
                            headerName = "UBI#";
                        }
                        else if (headerName == "Business Type") {
                            headerName = "Business Type";
                        }
                        else if (headerName == "Principal Office Address") {
                            headerName = "Principal Office Address";
                        }
                        else if (headerName == "Registered Agent Name") {
                            headerName = "Registered Agent Name";
                        }
                        else if (headerName == "Status") {
                            headerName = "Status";
                        }
                        //TFS 2330
                        else if (headerName == "FEIN") {  
                            headerName = "FEIN";
                        }
                        //TFS 2330

                        row += headerName + ',';
                    }
                    if (typeof Data === 'string') {
                        if (Data) {
                            if (Data.indexOf(',') != -1) {
                                Data = '"' + Data + '"';
                            }
                        }
                        //Data = Data.replace(/,/g, " ")
                    }

                    else {
                        if (!Data) {
                            Data = '';
                        }
                        else {
                            Data = Data;
                        }

                    }
                    if (headerName == 'Email' || headerName == 'Email') {
                        rowData = rowData + Data;
                    }
                    else {
                        rowData += Data + ",";
                    }


                }

            });

            if (index == 0) {
                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }
            rowData.slice(0, rowData.length - 1);

            //add a line break after each row
            CSV += rowData + '\r\n';
        });

        row = ""; csv = ""; rowData = "";

        //Generate a file name
        var fileName = "BusinessSearchList";


        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        if (navigator.msSaveBlob) {
            var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
            navigator.msSaveBlob(blob, "fileName.csv")

        } else {
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        //}
    }

    //navigate to business information
    $scope.showBusineInfo = function (id, businessType) {
        $rootScope.isBackButtonHide = false;
        $scope.businesssearchcriteria.businessid = id;
        $scope.businesssearchcriteria.businesstype = businessType;
        $cookieStore.put('businesssearchcriteria', $scope.businesssearchcriteria);
        $scope.navBusinessInformation();
    }

    //navigate to home
    $scope.gotoHome = function () {
        // ScopesData.removeByKey('businesssearchcriteria');
        $cookieStore.remove('cftSearchcriteria');
        $cookieStore.remove('cftAdvanceSearchcriteria');
        $scope.navHome();
    };

    $scope.getTransactionDocumentsList = function getTransactionDocumentsList(FilingNumber, Transactionid, filingTypeName) {

        FilingNumber = ((filingTypeName == 'COMMERCIAL STATEMENT OF CHANGE' || filingTypeName == 'COMMERCIAL TERMINATION STATEMENT') && Transactionid > 0 ? 0 : FilingNumber);
        var criteria = {
            ID: Transactionid, FilingNumber: FilingNumber
        };
        // getTransactionDocumentsList method is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getTransactionDocumentsList, criteria,
            function (response) {
                if (response.data != null) {
                    $scope.transactionDocumentsList = angular.copy(response.data);
                    $("#divSearchResult").modal('toggle');
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: noDataFound method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.noDataFound);
            },
            function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data.Message);
            }
        );
    }

    //navigate to business information
    $scope.showSubscriptionBusineInfo = function (id, businessType) {
        $rootScope.isBackButtonHide = true;
        $scope.businesssearchcriteria.businessid = id;
        $scope.businesssearchcriteria.businesstype = businessType;
        $cookieStore.put('businesssearchcriteria', $scope.businesssearchcriteria);
        $scope.navBusinessInformation();
    }

    //$scope.propertyName = 'FilingDate';
    //$scope.reverse = true;

    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };

    //TFS 2330

    $scope.seachFEINNo = function (FEINNo) {
        //clear cookies
        //$cookieStore.remove('businesssearchType');
        //$cookieStore.remove('businesssearchcriteria');
        $cookieStore.remove('cftSearchcriteria');
        $cookieStore.remove('cftAdvanceSearchcriteria');

        //TFS 2330
        $scope.businesssearchType = $cookieStore.get('businesssearchType');
        $scope.businesssearchcriteria = $cookieStore.get('businesssearchcriteria');
        $cookieStore.put('businesssearchcriteria', $scope.businesssearchcriteria);
        //TFS 2330

        //reset page variables
        $scope.page = 0;
        $scope.pagesCount = 0;
        $scope.totalCount = 0;

        //Building Search Citeria
        $scope.businesssearchcriteria = {
            Type: "Agent",
            searchtype: "feinnumber",   //TFS 2330
            searchval: FEINNo,          //TFS 2330
            IsSearch: true,
            AgentAddress: {
                StreetAddress1: null,
                StreetAddress2: null,
                City: null,
                State: "WA",
                PostalCode: null,
                Zip5: null,
                Zip4: null,
                County: null,
                OtherState: null,
            },
            PrincipalAddress: {
                StreetAddress1: null,
                StreetAddress2: null,
                City: null,
                State: null,
                Country: "USA",
                PostalCode: null,
                Zip5: null,
                Zip4: null,
                OtherState: null,
            },

            SearchEntityName: null,
            BusinessStatusID: null,
            BusinessTypeId: null,
            AgentName: null,
            PrincipalName : null,
            ExpirationDate: null,
            IsHostHomeSearch: null,
            IsPublicBenefitNonProfitSearch: null,
            IsCharitableNonProfitSearch: null,
            IsGrossRevenueNonProfitSearch: null,
            IsHasMembersSearch: null,

            IsHasFEINSearch: 'true',
            FEINNoSearch: FEINNo,

            StartDateOfIncorporation: null,
            EndDateOfIncorporation: null,

            SortBy: null,
            SortType: null,

            PageID: null,
            PageCount: null,
        };

        $scope.transactionDocumentsList = [];
        $scope.businesssearchType == "AdvancedSearch";
        //$location.path() == "/BusinessSearch/AdvancedSearch";
        $location.path() == "/BusinessSearch";
        //load page
        execCurrentPath();
        //loadbusinessList($scope.page);

    };
    //TFS 2330
});

wacorpApp.controller('trademarkHomeSearchController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, $window, lookupService, wacorpService, ScopesData) {

    // variable initilization
    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.trademarkSearch = {};
    $scope.isButtonSerach = false;
    $rootScope.isAdvanceSearch = false;
    $scope.cftOrganizationSearchType = false;
    $scope.IsType = false;
    $scope.TradeMarkList = [];

    $scope.criteria = { Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, IsSearch: true, SearchValue: "", SearchCriteria: "", RegistrationNumber: null };
    $scope.trademarkSearch = {
        Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, isCftOrganizationSearchBack: false,
        TradeMarkText: null, TradeMarkOwner: null, RegistrationNumber: null, UBINumber: null, Contains: searchTypes.Contains, isSearchClick: false,
        SearchCriteria: "", Selectiontype: searchTypes.Contains
    };
    $scope.trademarkSearch.Type = searchTypes.RegistrationNumber;


    $scope.hideOption = function (value) {
        $scope.IsType = false;
        $scope.trademarkSearch.Type = value;
        switch (value) {
            case "RegistrationNumber":
                $('#txtTrademarkNo').focus();
                $scope.trademarkSearch.TradeMarkOwner = null;
                $scope.trademarkSearch.TradeMarkText = null;
                $scope.trademarkSearch.UBINumber = null;
                $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                //$('#rdoTradeNo').prop('checked', true);
                $scope.trademarkSearch.Type = searchTypes.RegistrationNumber;
                break;
            case "TrademarkOwner":
                $scope.trademarkSearch.RegistrationNumber = null;
                $scope.trademarkSearch.TradeMarkText = null;
                $scope.trademarkSearch.UBINumber = null;
                if ($scope.trademarkSearch.Selectiontype == searchTypes.Contains)
                    $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                //$scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                $('#rdoTradename').prop('checked', true);
                $('#txtOwnerName').focus();
                $scope.IsType = true;
                break;
            case "TrademarkText":

                $scope.trademarkSearch.RegistrationNumber = null;
                $scope.trademarkSearch.TradeMarkOwner = null;
                $scope.trademarkSearch.UBINumber = null;
                if ($scope.trademarkSearch.Selectiontype == searchTypes.Contains)
                    $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                $('#rdoTradetext').prop('checked', true);
                $('#txtTradetext').focus();
                $scope.IsType = true;
                break;
            case "UBINumber":
                $scope.trademarkSearch.RegistrationNumber = null;
                $scope.trademarkSearch.TradeMarkOwner = null;
                $scope.trademarkSearch.TradeMarkText = null;
                $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                $('#rdoTradeUbi').prop('checked', true);
                $('#txtTradeUbi').focus();
                break;
            default:

        }
    };


    function setFocus() {
        $scope.hideOption($scope.trademarkSearch.Type);

    };
    // check form validation
    $scope.isformValid = function () {
       
        return ($scope.trademarkSearch.RegistrationNumber==null ||   $scope.trademarkSearch.RegistrationNumber == "") && ($scope.trademarkSearch.TradeMarkOwner==null ||  $scope.trademarkSearch.TradeMarkOwner == "") &&  ($scope.trademarkSearch.TradeMarkText==null ||$scope.trademarkSearch.TradeMarkText == "") &&  ($scope.trademarkSearch.UBINumber==null || $scope.trademarkSearch.UBINumber == "");
    }
    $scope.clearFun = function () {
        $scope.trademarkSearch.RegistrationNumber = null;
        $scope.trademarkSearch.TradeMarkOwner = null;
        $scope.trademarkSearch.TradeMarkText = null;
        $scope.trademarkSearch.UBINumber = null;
        $scope.trademarkSearch.isSearchClick = false;
        $scope.IsType = false;
        $scope.trademarkSearch.Type = searchTypes.RegistrationNumber;
        $('#txtTrademarkNo').focus();
    };

    $scope.setPastedTradeNum = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.RegistrationNumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.RegistrationNumber = pastedText;
            });
        }
    };


    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.UBINumber = pastedText;
            });
        }
    };

    $scope.searchTrade = function (Trademarksearchform) {
        $scope.isShowErrorFlag = true;
        if ($scope[Trademarksearchform].$valid) {
            $scope.isShowErrorFlag = false;
            $scope.isButtonSerach = true
            $scope.trademarkSearch.isSearchClick = true;
            $rootScope.isTradeBackSearch = false;
            loadTradeList(constant.ZERO); // loadTradeList method is available in this controller only.
        }
    };

    $scope.searchTradePagination = function (Trademarksearchform) {
        $scope.isButtonSerach = true
        $scope.trademarkSearch.isSearchClick = true;
        loadTradeList(Trademarksearchform); // loadTradeList method is available in this controller only.
    };


    //to get Trademark serach result list.
    function loadTradeList(page) {
        
        page = page || constant.ZERO;
        $scope.trademarkSearch.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        if ($scope.trademarkSearch.Type == "RegistrationNumber"  || $scope.trademarkSearch.Type == "UBINumber")
            $scope.criteria.SearchCriteria = "";
        else {
            if ($rootScope.isTradeBackSearch == true) {
                //$scope.trademarkSearch.SearchCriteria = $rootScope.data.SearchCriteria;
                $scope.criteria.SearchCriteria = $scope.trademarkSearch.SearchCriteria;
            }
            else {
                var value = $('input[name="trademarkType"]:checked').val();
                $scope.criteria.SearchCriteria = value;
                $scope.trademarkSearch.SearchCriteria = value;
            }

        }

        $scope.criteria.Type = $scope.trademarkSearch.Type;

        switch ($scope.trademarkSearch.Type) {

            case "RegistrationNumber":
                $scope.criteria.SearchValue = $scope.trademarkSearch.RegistrationNumber;
                break;
            case "TrademarkOwner":
                $scope.criteria.SearchValue = $scope.trademarkSearch.TradeMarkOwner;
                break;
            case "TrademarkText":
                $scope.criteria.SearchValue = $scope.trademarkSearch.TradeMarkText;
                break;
            case "UBINumber":
                $scope.criteria.SearchValue = $scope.trademarkSearch.UBINumber;
                break;
            default:
        }
        $scope.criteria.PageID = $scope.trademarkSearch.PageID;
        var data = angular.copy($scope.criteria);
        $scope.isButtonSerach = page == 0;
        $rootScope.data = $scope.criteria;
        $cookieStore.put('trademarkSearchCriteria', $scope.trademarkSearch);
        $location.path("/trademarkDetails");

    }

});
/*
Author      : Kishore Penugonda
File        : businessSearchController.js
Description : input search criteria for business search
*/
wacorpApp.controller('searchBusinessController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    // variables
    $scope.loadingText = "Search";
   
    //$scope.businesssearchcriteria = $cookieStore.get('businesssearchcriteria');
    //$scope.businessSearchEntity = {};

    $cookieStore.put('businesssearchcriteria', null);

    $scope.searchTypesList = [{ value: "Contains", key: "Contains" }, { value: "Exact Match", key: "ExactMatch" }, { value: "Starts With", key: "StartsWith" }];

    $scope.initSearchBusiness = function () {
        if ($scope.businesssearchcriteria == null) {
            $scope.businesssearchcriteria = { searchtype: "", searchval: "", ubinumber: "", businessname: "", businessid: "", businesstype: "" };
            $scope.businessSearchEntity = { SearchCriteria: "Contains", SearchType: "BusinessName", SearchValue: "", UBINumber: "", BusinessName: "", IsShowAdvanceSearch: false, DBABusinessName: "" };
        }
        else {
            $scope.businessSearchEntity = {
                SearchCriteria: $scope.businesssearchcriteria.searchcriteria, SearchType: $scope.businesssearchcriteria.searchtype,
                SearchValue: $scope.businesssearchcriteria.searchval, UBINumber: $scope.businesssearchcriteria.ubinumber,
                BusinessName: $scope.businesssearchcriteria.businessname, IsShowAdvanceSearch: false, DBABusinessName: ""
            };
        }
        loadingText(false); // loadingText method is available in this controller only
    }

    $scope.initLoginSearchBusiness = function () {
        if ($scope.businesssearchcriteria == null) {
            //$scope.showAdvancelgnSearch = false;
            $scope.businesssearchcriteria = { searchtype: "", searchval: "", ubinumber: "", businessname: "", businessid: "", businesstype: "" };
            $scope.businessSearchEntity = { SearchCriteria: "Contains", SearchType: searchTypes.UBINUMBER, SearchValue: "", UBINumber: "", BusinessName: "", IsShowAdvanceSearch: false, DBABusinessName: "" };
        }
        else {
            $scope.businessSearchEntity = {
                SearchCriteria: $scope.businesssearchcriteria.searchcriteria, SearchType: $scope.businesssearchcriteria.searchtype,
                SearchValue: $scope.businesssearchcriteria.searchval, UBINumber: $scope.businesssearchcriteria.ubinumber,
                BusinessName: $scope.businesssearchcriteria.businessname, IsShowAdvanceSearch: false, DBABusinessName: ""
            };
        }
    }

    //submit business search
    $scope.searchLoginBusiness = function (searchform) {
        $scope.isShowErrorFlag = true;
        if ($scope[searchform].$valid) {
            $scope.isShowErrorFlag = false;
            var searchval = $scope.businessSearchEntity.SearchValue;
            var searchtype = $scope.businessSearchEntity.SearchType == searchTypes.UBINUMBER ? "UBINumber" : "BusinessName";
            //if (searchtype == "BusinessName") {
            //    switch ($scope.businessSearchEntity.SearchCriteria) {
            //        case "StartsWith":
            //            searchval = searchval + "%";
            //            break;
            //        case "EndsWith":
            //            searchval = "%" + searchval;
            //            break;
            //        case "Contains":
            //            searchval = "%" + searchval + "%";
            //            break;
            //        default:

            //    };
            //}
            $scope.businesssearchcriteria.searchval = searchval;
            $scope.businesssearchcriteria.searchtype = searchtype;
            $scope.businesssearchcriteria.searchcriteria = $scope.businessSearchEntity.SearchCriteria;
            $cookieStore.put('businesssearchType', "BusinessSearch");
            $cookieStore.put('businesssearchcriteria', $scope.businesssearchcriteria);
            $scope.navBusinessSearch();
        }
    }


    $scope.searchBusiness = function () {
        loadingText(true);
        var searchval = $scope.businessSearchEntity.BusinessName == "" ? $scope.businessSearchEntity.UBINumber : $scope.businessSearchEntity.BusinessName;
        var searchtype = $scope.businessSearchEntity.BusinessName == "" ? "UBINumber" : "BusinessName";
        //if (searchtype == "BusinessName") {
        //    switch ($scope.businessSearchEntity.SearchCriteria) {
        //        case "StartsWith":
        //            searchval = searchval + "%";
        //            break;
        //        case "EndsWith":
        //            searchval = "%" + searchval;
        //            break;
        //        case "Contains":
        //            searchval = "%" + searchval + "%";
        //            break;
        //        default:

        //    };
        //}
        $scope.businesssearchcriteria.searchval = searchval;
        $scope.businesssearchcriteria.searchtype = searchtype;
        $scope.businesssearchcriteria.searchcriteria = $scope.businessSearchEntity.SearchCriteria;
        $cookieStore.put('businesssearchType', "BusinessSearch");
        $cookieStore.put('businesssearchcriteria', $scope.businesssearchcriteria);
        $scope.navBusinessSearch();
    };

    // check form validation
    $scope.isformValid = function () {
        return $scope.businessSearchEntity.UBINumber == "" && $scope.businessSearchEntity.BusinessName == "";
    }

    function loadingText(flag) {
        if (flag == true)
            $scope.loadingText = "Processing ...";
        else
            $scope.loadingText = "Search";
    }
    $scope.cleartext = function () {
        $scope.businessSearchEntity.SearchValue = null;
    };

    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.businessSearchEntity.SearchValue = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.businessSearchEntity.SearchValue = pastedText;
            });
        }
    };

    $scope.setUBILength = function (e) {
        //if ($scope.businessSearchEntity.SearchValue.length >= 9) {
        //    e.preventDefault();
        //}
        if ($scope.businessSearchEntity.SearchValue != undefined && $scope.businessSearchEntity.SearchValue != null && $scope.businessSearchEntity.SearchValue != "" && $scope.businessSearchEntity.SearchValue.length >= 9)
        {
            if (e.which != 97)
            {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                    // Allow: Ctrl+A, Command+A
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right, down, up
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
                e.preventDefault();
            }
        }
    };

    $scope.setPastedUBIHome = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.businessSearchEntity.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.businessSearchEntity.UBINumber = pastedText;
            });
        }
    };

    $scope.setUBILengthHome = function (e) {
        if ($scope.businessSearchEntity.UBINumber != undefined && $scope.businessSearchEntity.UBINumber != null && $scope.businessSearchEntity.UBINumber != "" && $scope.businessSearchEntity.UBINumber.length >= 9)
        {
            if (e.which != 97)
            {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                    // Allow: Ctrl+A, Command+A
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right, down, up
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
                e.preventDefault();
            }
        }
    };
});

wacorpApp.controller('advancedSearchController', function ($scope, $q, $timeout, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, membershipService) {
    $scope.advSearchTypes = { types: ['Agent', 'Principal'] }.types;
    $scope.search = {
        Type: "Agent", BusinessStatusID: "0", SearchEntityName: '', SearchType: '', BusinessTypeID: "0", AgentName: "", PrincipalName: "", StartDateOfIncorporation: null, EndDateOfIncorporation: null, ExpirationDate:null, IsSearch: true, IsShowAdvanceSearch: false, 
        AgentAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
            baseEntity: { FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null }, FullAddress: null,
            ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
            Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        PrincipalAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
            baseEntity: { FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null }, FullAddress: null,
            ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: '', OtherState: null, Country: 'USA',
            Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        IsHostHomeSearch: "",
        IsPublicBenefitNonProfitSearch: "",
        IsCharitableNonProfitSearch: "",
        IsGrossRevenueNonProfitSearch: "",
        IsHasMembersSearch: "",
        IsHasFEINSearch: "",
        NonProfit: {
            IsNonProfitEnabled: false,

            chkSearchByIsHostHome: false,
            chkSearchByIsPublicBenefitNonProfit: false,
            chkSearchByIsCharitableNonProfit: false,
            chkSearchByIsGrossRevenueNonProfit: false,
            chkSearchByIsHasMembers: false,
            chkSearchByIsHasFEIN: false,
            FEINNoSearch: "",

            chkIsHostHome: { none: false, yes: false, no: false },
            chkIsPublicBenefitNonProfit: { none: false, yes: false, no: false },
            chkIsCharitableNonProfit: { none: false, yes: false, no: false },
            chkIsGrossRevenueNonProfit: { none: false, yes: false, no: false },
            chkIsHasMembers: { none: false, yes: false, no: false },
            chkIsHasFEIN: { yes: false, no: false },
        },
    };
    $scope.tempSearch = {
        Type: "Agent", BusinessStatusID: "0", SearchEntityName: '', SearchType: '', BusinessTypeID: "0", AgentName: "", PrincipalName: "", StartDateOfIncorporation: null, EndDateOfIncorporation: null, ExpirationDate: null, IsSearch: true, IsShowAdvanceSearch: false,
        AgentAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
            baseEntity: { FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null }, FullAddress: null,
            ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: 'WA', OtherState: null, Country: 'USA',
            Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        PrincipalAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
            baseEntity: { FilerID: 0, UserID: 0, CreatedBy: 0, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null }, FullAddress: null,
            ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: '', OtherState: null, Country: 'USA',
            Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        IsHostHomeSearch: "",
        IsPublicBenefitNonProfitSearch: "",
        IsCharitableNonProfitSearch: "",
        IsGrossRevenueNonProfitSearch: "",
        IsHasMembersSearch: "",
        IsHasFEINSearch: "",
        NonProfit: {
            IsNonProfitEnabled: false,

            chkSearchByIsHostHome: false,
            chkSearchByIsPublicBenefitNonProfit: false,
            chkSearchByIsCharitableNonProfit: false,
            chkSearchByIsGrossRevenueNonProfit: false,
            chkSearchByIsHasMembers: false,
            chkSearchByIsHasFEIN: false,
            FEINNoSearch: "",

            chkIsHostHome: { none: false, yes: false, no: false },
            chkIsPublicBenefitNonProfit: { none: false, yes: false, no: false },
            chkIsCharitableNonProfit: { none: false, yes: false, no: false },
            chkIsGrossRevenueNonProfit: { none: false, yes: false, no: false },
            chkIsHasMembers: { none: false, yes: false, no: false },
            chkIsHasFEIN: { yes: false, no: false },
        },
    };
    $scope.initAdvSearch = function () {
        $scope.search.IsShowAdvanceSearch = true;
        $scope.businessTypes();
        $scope.businessStatusList();
        if ($rootScope.repository.loggedUser!=undefined)
            $scope.username = $rootScope.repository.loggedUser.firstname;

        //Checking Whether User Logged In Or not
        $scope.isUserLoggedIn = membershipService.isUserLoggedIn();
    };
    $scope.clearCriteria = function () {
        $scope.search = angular.copy($scope.tempSearch);
    };
    $scope.searchBusiness = function () {
        
        if ($scope.search.StartDateOfIncorporation != "" && $scope.search.EndDateOfIncorporation  != "") {
            if (new Date($scope.search.StartDateOfIncorporation) > new Date($scope.search.EndDateOfIncorporation)) {
                $scope.isValidDate = false;
                wacorpService.alertDialog('Start Date should be less than End Date.');
                return false;
            }
        }
        if ($scope.search.SearchEntityName != "" && $scope.search.SearchEntityName != null) {
            var value = $('#ddlSelection option:selected').text();

            $scope.search.SearchType = $('#ddlSelection option:selected').text();

            switch (value) {
                case "Starts With":
                    $scope.search.SearchEntityName = $scope.search.SearchEntityName + '%';
                    break;
                case "Contains":
                    $scope.search.SearchEntityName = '%' + $scope.search.SearchEntityName + '%';
                    break;
                case "Exact Match":
                    $scope.search.SearchEntityName = $scope.search.SearchEntityName;
                    break;
                default:
            }
        }
        else {
            $scope.search.SearchEntityName = "";
            $scope.search.SearchType = "";
        }
        
        $scope.GetNonProfitSearchValues(); //TFS 2330 Get NonProfit Search Values
        
        $scope.search.PrincipalAddress.State = '';
        $cookieStore.put('businesssearchcriteria', $scope.search);
        $cookieStore.put('businesssearchType', "AdvancedSearch");
        $scope.navBusinessSearch();
    };

    $scope.businessTypes = function () {
        var config = { params: { name: 'BusinessTypeIsPublic' } };
        // getLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) {  $scope.businessTypes = response.data; });
    };
    $scope.businessStatusList = function () {
        var config = { params: { name: 'BusinessStatus' } };
        // getLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.businessStatusList = response.data; });
    };
  
    $scope.isReview = function () {
        return $scope.search.Type != "Agent" ? true : false;
    };

    //TFS 2330
    //Enabled/disable NonProfit Search Div
    $scope.$watch('search', function () {
        // ...
        
        $scope.search.NonProfit.IsNonProfitEnabled = false;
        if ($scope.search.BusinessTypeID == 26 || $scope.search.BusinessTypeID == 27 || $scope.search.BusinessTypeID == 73 || $scope.search.BusinessTypeID == 74) {
            $scope.search.NonProfit.IsNonProfitEnabled = true;
        }
    }, true); // <-- objectEquality

    $scope.GetNonProfitSearchValues = function () {
        //TFS 2330 set variable for NonProfit Search
        if ($scope.search.NonProfit.IsNonProfitEnabled) {
            $scope.search.IsHostHomeSearch = "";
            if ($scope.search.NonProfit.chkSearchByIsHostHome) {
                if ($scope.search.NonProfit.chkIsHostHome.yes) {
                    $scope.search.IsHostHomeSearch = 'true';
                }
                if ($scope.search.NonProfit.chkIsHostHome.no) {
                    if ($scope.search.NonProfit.IsHostHomeSearch != "") {
                        $scope.search.IsHostHomeSearch = $scope.search.IsHostHomeSearch + ',';
                    }
                    $scope.search.IsHostHomeSearch = $scope.search.IsHostHomeSearch + 'false';
                }
                if ($scope.search.NonProfit.chkIsHostHome.none) {
                    if ($scope.search.IsHostHomeSearch != "") {
                        $scope.search.IsHostHomeSearch = $scope.search.IsHostHomeSearch + ',';
                    }
                    $scope.search.IsHostHomeSearch = $scope.search.IsHostHomeSearch + 'null';
                }
            }
            //wacorpService.alertDialog('IsHostHomeSearch: ' + $scope.search.NonProfit.IsHostHomeSearch);
            //IsPublicBenefitNonProfitSearch
            $scope.search.IsPublicBenefitNonProfitSearch = "";
            if ($scope.search.NonProfit.chkSearchByIsPublicBenefitNonProfit) {
                if ($scope.search.NonProfit.chkIsPublicBenefitNonProfit.yes) {
                    $scope.search.IsPublicBenefitNonProfitSearch = 'true';
                }
                if ($scope.search.NonProfit.chkIsPublicBenefitNonProfit.no) {
                    if ($scope.search.IsPublicBenefitNonProfitSearch != "") {
                        $scope.search.IsPublicBenefitNonProfitSearch = $scope.search.IsPublicBenefitNonProfitSearch + ',';
                    }
                    $scope.search.IsPublicBenefitNonProfitSearch = $scope.search.IsPublicBenefitNonProfitSearch + 'false';
                }
                if ($scope.search.NonProfit.chkIsPublicBenefitNonProfit.none) {
                    if ($scope.search.IsPublicBenefitNonProfitSearch != "") {
                        $scope.search.IsPublicBenefitNonProfitSearch = $scope.search.IsPublicBenefitNonProfitSearch + ',';
                    }
                    $scope.search.IsPublicBenefitNonProfitSearch = $scope.search.IsPublicBenefitNonProfitSearch + 'null';
                }
            }
            //wacorpService.alertDialog('IsPublicBenefitNonProfitSearch: ' + $scope.search.NonProfit.IsPublicBenefitNonProfitSearch);
            //IsCharitableNonProfitSearch
            $scope.search.IsCharitableNonProfitSearch = "";
            if ($scope.search.NonProfit.chkSearchByIsCharitableNonProfit) {
                if ($scope.search.NonProfit.chkIsCharitableNonProfit.yes) {
                    $scope.search.IsCharitableNonProfitSearch = 'true';
                }
                if ($scope.search.NonProfit.chkIsCharitableNonProfit.no) {
                    if ($scope.search.IsCharitableNonProfitSearch != "") {
                        $scope.search.IsCharitableNonProfitSearch = $scope.search.IsCharitableNonProfitSearch + ',';
                    }
                    $scope.search.IsCharitableNonProfitSearch = $scope.search.IsCharitableNonProfitSearch + 'false';
                }
                if ($scope.search.NonProfit.chkIsCharitableNonProfit.none) {
                    if ($scope.search.IsCharitableNonProfitSearch != "") {
                        $scope.search.IsCharitableNonProfitSearch = $scope.search.IsCharitableNonProfitSearch + ',';
                    }
                    $scope.search.IsCharitableNonProfitSearch = $scope.search.IsCharitableNonProfitSearch + 'null';
                }
            }
            //wacorpService.alertDialog('IsCharitableNonProfitSearch: ' + $scope.search.NonProfit.IsCharitableNonProfitSearch);
            //IsGrossRevenueNonProfitSearch
            $scope.search.IsGrossRevenueNonProfitSearch = "";
            if ($scope.search.NonProfit.chkSearchByIsGrossRevenueNonProfit) {
                if ($scope.search.NonProfit.chkIsGrossRevenueNonProfit.over500k) {
                    $scope.search.IsGrossRevenueNonProfitSearch = 'true';
                }
                if ($scope.search.NonProfit.chkIsGrossRevenueNonProfit.under500k) {
                    if ($scope.search.IsGrossRevenueNonProfitSearch != "") {
                        $scope.search.IsGrossRevenueNonProfitSearch = $scope.search.IsGrossRevenueNonProfitSearch + ',';
                    }
                    $scope.search.IsGrossRevenueNonProfitSearch = $scope.search.IsGrossRevenueNonProfitSearch + 'false';
                }
                if ($scope.search.NonProfit.chkIsGrossRevenueNonProfit.none) {
                    if ($scope.search.IsGrossRevenueNonProfitSearch != "") {
                        $scope.search.IsGrossRevenueNonProfitSearch = $scope.search.IsGrossRevenueNonProfitSearch + ',';
                    }
                    $scope.search.IsGrossRevenueNonProfitSearch = $scope.search.IsGrossRevenueNonProfitSearch + 'null';
                }
            }
            //wacorpService.alertDialog('IsHasMembersSearch: ' + $scope.search.NonProfit.IsHasMembersSearch);
            //IsHasMembersSearch
            $scope.search.IsHasMembersSearch = "";
            if ($scope.search.NonProfit.chkSearchByIsHasMembers) {
                if ($scope.search.NonProfit.chkIsHasMembers.yes) {
                    $scope.search.IsHasMembersSearch = 'true';
                }
                if ($scope.search.NonProfit.chkIsHasMembers.no) {
                    if ($scope.search.IsHasMembersSearch != "") {
                        $scope.search.IsHasMembersSearch = $scope.search.IsHasMembersSearch + ',';
                    }
                    $scope.search.IsHasMembersSearch = $scope.search.IsHasMembersSearch + 'false';
                }
                if ($scope.search.NonProfit.chkIsHasMembers.none) {
                    if ($scope.search.IsHasMembersSearch != "") {
                        $scope.search.IsHasMembersSearch = $scope.search.IsHasMembersSearch + ',';
                    }
                    $scope.search.IsHasMembersSearch = $scope.search.IsHasMembersSearch + 'null';
                }
            }
            //wacorpService.alertDialog('IsHasFEINSearch: ' + $scope.search.NonProfit.IsHasFEINSearch);
            //IsHasFEINSearch
            $scope.search.IsHasFEINSearch = "";
            if ($scope.search.NonProfit.chkSearchByIsHasFEIN) {
                $scope.search.FEINNoSearch = $scope.search.NonProfit.FEINNoSearch;

                if ($scope.search.NonProfit.chkIsHasFEIN.yes) {
                    $scope.search.IsHasFEINSearch = 'true';
                }
                if ($scope.search.NonProfit.chkIsHasFEIN.no) {
                    if ($scope.search.IsHasFEINSearch != "") {
                        $scope.search.IsHasFEINSearch = $scope.search.IsHasFEINSearch + ',';
                    }
                    $scope.search.IsHasFEINSearch = $scope.search.IsHasFEINSearch + 'false';
                }
            }
            
        };
        //TFS 2330 
    };

    //TFS 2330
    $scope.$watch('search.BusinessTypeID', function () {
        $scope.clearNonprofitCheckboxes();
    }, true);

    $scope.clearNonprofitCheckboxes = function () {
        $scope.search.NonProfit.chkSearchByIsCharitableNonProfit = false;
        $scope.search.NonProfit.chkIsCharitableNonProfit.yes = false;
        $scope.search.NonProfit.chkIsCharitableNonProfit.no = false;
        $scope.search.NonProfit.chkIsCharitableNonProfit.none = false;

        $scope.search.NonProfit.chkSearchByIsGrossRevenueNonProfit = false;
        $scope.search.NonProfit.chkIsGrossRevenueNonProfit.over500k = false;
        $scope.search.NonProfit.chkIsGrossRevenueNonProfit.under500k = false;
        $scope.search.NonProfit.chkIsGrossRevenueNonProfit.none = false;

        $scope.search.NonProfit.chkSearchByIsHasFEIN = false;
        $scope.search.NonProfit.chkIsHasFEIN.yes = false;
        $scope.search.NonProfit.chkIsHasFEIN.no = false;

        $scope.search.NonProfit.chkSearchByIsHasMembers = false;
        $scope.search.NonProfit.chkIsHasMembers.yes = false;
        $scope.search.NonProfit.chkIsHasMembers.no = false;
        $scope.search.NonProfit.chkIsHasMembers.none = false;

        $scope.search.NonProfit.chkSearchByIsHostHome = false;
        $scope.search.NonProfit.chkIsHostHome.yes = false;
        $scope.search.NonProfit.chkIsHostHome.no = false;
        $scope.search.NonProfit.chkIsHostHome.none = false;


        $scope.search.NonProfit.chkSearchByIsPublicBenefitNonProfit = false
        $scope.search.NonProfit.chkIsPublicBenefitNonProfit.yes = false;
        $scope.search.NonProfit.chkIsPublicBenefitNonProfit.no = false;
        $scope.search.NonProfit.chkIsPublicBenefitNonProfit.none = false;
    };

    //chkIsCharitableNonProfit
    $scope.$watch('search.NonProfit.chkSearchByIsCharitableNonProfit', function () {
        if ($scope.search.NonProfit.chkSearchByIsCharitableNonProfit == false) {
            $scope.search.NonProfit.chkIsCharitableNonProfit.yes = false;
            $scope.search.NonProfit.chkIsCharitableNonProfit.no = false;
            $scope.search.NonProfit.chkIsCharitableNonProfit.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsCharitableNonProfit.yes', function () {
        if ($scope.search.NonProfit.chkIsCharitableNonProfit.yes == true) {

            $scope.search.NonProfit.chkIsCharitableNonProfit.no = false;
            $scope.search.NonProfit.chkIsCharitableNonProfit.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsCharitableNonProfit.no', function () {
        if ($scope.search.NonProfit.chkIsCharitableNonProfit.no == true) {

            $scope.search.NonProfit.chkIsCharitableNonProfit.yes = false;
            $scope.search.NonProfit.chkIsCharitableNonProfit.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsCharitableNonProfit.none', function () {
        if ($scope.search.NonProfit.chkIsCharitableNonProfit.none == true) {

            $scope.search.NonProfit.chkIsCharitableNonProfit.yes = false;
            $scope.search.NonProfit.chkIsCharitableNonProfit.no = false;
        }
    });

    //chkIsGrossRevenueNonProfit
    $scope.$watch('search.NonProfit.chkSearchByIsGrossRevenueNonProfit', function () {
        if ($scope.search.NonProfit.chkSearchByIsGrossRevenueNonProfit == false) {
            $scope.search.NonProfit.chkIsGrossRevenueNonProfit.over500k = false;
            $scope.search.NonProfit.chkIsGrossRevenueNonProfit.under500k = false;
            $scope.search.NonProfit.chkIsGrossRevenueNonProfit.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsGrossRevenueNonProfit.over500k', function () {
        if ($scope.search.NonProfit.chkIsGrossRevenueNonProfit.over500k == true) {

            $scope.search.NonProfit.chkIsGrossRevenueNonProfit.under500k = false;
            $scope.search.NonProfit.chkIsGrossRevenueNonProfit.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsGrossRevenueNonProfit.under500k', function () {
        if ($scope.search.NonProfit.chkIsGrossRevenueNonProfit.under500k == true) {

            $scope.search.NonProfit.chkIsGrossRevenueNonProfit.over500k = false;
            $scope.search.NonProfit.chkIsGrossRevenueNonProfit.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsGrossRevenueNonProfit.none', function () {
        if ($scope.search.NonProfit.chkIsGrossRevenueNonProfit.none == true) {

            $scope.search.NonProfit.chkIsGrossRevenueNonProfit.over500k = false;
            $scope.search.NonProfit.chkIsGrossRevenueNonProfit.under500k = false;
        }
    });

    //chkIsHasFEIN
    $scope.$watch('search.NonProfit.chkSearchByIsHasFEIN', function () {
        if ($scope.search.NonProfit.chkSearchByIsHasFEIN == false) {
            $scope.search.NonProfit.chkIsHasFEIN.yes = false;
            $scope.search.NonProfit.chkIsHasFEIN.no = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsHasFEIN.yes', function () {
        if ($scope.search.NonProfit.chkIsHasFEIN.yes == true) {

            $scope.search.NonProfit.chkIsHasFEIN.no = false;
            $scope.search.NonProfit.FEINNoSearch = "";
        }
    });
    $scope.$watch('search.NonProfit.chkIsHasFEIN.no', function () {
        if ($scope.search.NonProfit.chkIsHasFEIN.no == true) {

            $scope.search.NonProfit.chkIsHasFEIN.yes = false;
            $scope.search.NonProfit.FEINNoSearch = "";
        }
    });
    $scope.$watch('search.NonProfit.FEINNoSearch', function () {
        if ($scope.search.NonProfit.FEINNoSearch !== "") {

            $scope.search.NonProfit.chkIsHasFEIN.yes = false;
            $scope.search.NonProfit.chkIsHasFEIN.no = false;
        }
    });

    //chkIsHasMembers
    $scope.$watch('search.NonProfit.chkSearchByIsHasMembers', function () {
        if ($scope.search.NonProfit.chkSearchByIsHasMembers == false) {
            $scope.search.NonProfit.chkIsHasMembers.yes = false;
            $scope.search.NonProfit.chkIsHasMembers.no = false;
            $scope.search.NonProfit.chkIsHasMembers.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsHasMembers.yes', function () {
        if ($scope.search.NonProfit.chkIsHasMembers.yes == true) {
            $scope.search.NonProfit.chkIsHasMembers.no = false;
            $scope.search.NonProfit.chkIsHasMembers.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsHasMembers.no', function () {
        if ($scope.search.NonProfit.chkIsHasMembers.no == true) {
            $scope.search.NonProfit.chkIsHasMembers.yes = false;
            $scope.search.NonProfit.chkIsHasMembers.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsHasMembers.none', function () {
        if ($scope.search.NonProfit.chkIsHasMembers.none == true) {
            $scope.search.NonProfit.chkIsHasMembers.yes = false;
            $scope.search.NonProfit.chkIsHasMembers.no = false;
        }
    });

    //chkIsHostHome
    $scope.$watch('search.NonProfit.chkSearchByIsHostHome', function () {
        if ($scope.search.NonProfit.chkSearchByIsHostHome == false) {
            $scope.search.NonProfit.chkIsHostHome.yes = false;
            $scope.search.NonProfit.chkIsHostHome.no = false;
            $scope.search.NonProfit.chkIsHostHome.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsHostHome.yes', function () {
        if ($scope.search.NonProfit.chkIsHostHome.yes == true) {
            $scope.search.NonProfit.chkIsHostHome.no = false;
            $scope.search.NonProfit.chkIsHostHome.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsHostHome.no', function () {
        if ($scope.search.NonProfit.chkIsHostHome.no == true) {
            $scope.search.NonProfit.chkIsHostHome.yes = false;
            $scope.search.NonProfit.chkIsHostHome.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsHostHome.none', function () {
        if ($scope.search.NonProfit.chkIsHostHome.none == true) {
            $scope.search.NonProfit.chkIsHostHome.yes = false;
            $scope.search.NonProfit.chkIsHostHome.no = false;
        }
    });

    //chkIsPublicBenefitNonProfit
    $scope.$watch('search.NonProfit.chkSearchByIsPublicBenefitNonProfit', function () {
        if ($scope.search.NonProfit.chkSearchByIsPublicBenefitNonProfit == false) {
            $scope.search.NonProfit.chkIsPublicBenefitNonProfit.yes = false;
            $scope.search.NonProfit.chkIsPublicBenefitNonProfit.no = false;
            $scope.search.NonProfit.chkIsPublicBenefitNonProfit.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsPublicBenefitNonProfit.yes', function () {
        if ($scope.search.NonProfit.chkIsPublicBenefitNonProfit.yes == true) {
            $scope.search.NonProfit.chkIsPublicBenefitNonProfit.no = false;
            $scope.search.NonProfit.chkIsPublicBenefitNonProfit.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsPublicBenefitNonProfit.no', function () {
        if ($scope.search.NonProfit.chkIsPublicBenefitNonProfit.no == true) {
            $scope.search.NonProfit.chkIsPublicBenefitNonProfit.yes = false;
            $scope.search.NonProfit.chkIsPublicBenefitNonProfit.none = false;
        }
    });
    $scope.$watch('search.NonProfit.chkIsPublicBenefitNonProfit.none', function () {
        if ($scope.search.NonProfit.chkIsPublicBenefitNonProfit.none == true) {
            $scope.search.NonProfit.chkIsPublicBenefitNonProfit.yes = false;
            $scope.search.NonProfit.chkIsPublicBenefitNonProfit.no = false;
        }
    });
    //TFS 2330

});

wacorpApp.controller('cftBusinessSearchController', function ($scope, $q, $http, $timeout, $routeParams, $location, $rootScope, $cookieStore, $window, lookupService, wacorpService, ScopesData) {
    // variables
    $scope.page = constant.ZERO;
    $scope.page1 = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.pagesCount1 = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.loadingText = "Search";
    //$scope.businesssearchcriteria = {};
    //$scope.businessSearchEntity = {};
    $cookieStore.remove('cftSearchcriteria');
    $cookieStore.remove('cftAdvanceSearchcriteria');
    $rootScope.isCftOrganizationSearchBack = false;
    $scope.isUserLoggedIn = false;
    $scope.basicSearchResult = [];
    $scope.cftBasicBusinessSearch = [];
    $scope.BasicFeinDataDetail = [];

    //$scope.searchTypesList = [{ value: "Name Starts With", key: "startswith" }, { value: "Name Contains", key: "contains" }, { value: "Name Ends With", key: "EndsWith" }];
    $scope.charitySearchCriteria = { Type: searchTypes.RegistrationNumber, ID: "", IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, IsOnline: true, SearchType: $scope.searchType, isSearchClick: false, SearchCriteria: 'Contains' };
    $scope.basicSearchCriteria = { Type: "", IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, IsOnline: true, SearchType: $scope.searchType, isSearchClick: false };//basic search criteria
    $scope.cftBasicFeinSearchcriteria = {
        EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false, EntityWebsite: null,
        RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, BusinessType: "", Type: "", SearchValue: "", SearchCriteria: "",
    };

    if ($rootScope.repository.loggedUser != undefined) {
        $scope.isUserLoggedIn = true;
    }

    $scope.initCFTSearchBusiness = function () {

        $scope.charitySearchCriteria = { Type: searchTypes.RegistrationNumber, ID: "", IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, IsOnline: true, SearchType: $scope.searchType, isSearchClick: false };
        cftloadingText(false); // cftloadingText method is available in this controller only.
        $scope.charitySearchCriteria = $scope.charitySearchCriteria;
        $scope.charitySearchCriteria.SearchCriteria = 'Contains';
        if ($rootScope.isBasicSearchBack) {
            $scope.isUserLoggedIn = true;
            $scope.charitySearchCriteria = $cookieStore.get('cftBasicSearchcriteria');
            loadBasicCFList(constant.ZERO); // loadBasicCFList method is available in this controller only.
        }
    }

    $scope.searchCFTBusiness = function (PublicSearchform) {
        cftloadingText(true); // cftloadingText method is available in this controller only.
        // var type = $scope.businessSearchEntity.SearchType == searchTypes.REGISTRATIONNUMBER? "RegistrationNumber" : "OrganizationName";
        var searchValue = '';
        var type = '', searchCriteria = '';
        switch ($scope.charitySearchCriteria.Type) {
            case "RegistrationNumber":
                searchValue = $scope.charitySearchCriteria.ID;
                break;
            case "OrganizationName":
                searchValue = $scope.charitySearchCriteria.OrgName;
                // searchCriteria = 'contains';
                break;
            case "FEINNo":
                searchValue = $scope.charitySearchCriteria.ID;
                break;
            case "UBINumber":
                searchValue = $scope.charitySearchCriteria.ID;
                break;
            default:

        }
        $scope.isShowErrorFlag = true;
        //if ($scope[PublicSearchform].$valid) {
        //$scope.charitySearchCriteria.isSearchClick = true;
        $scope.isShowErrorFlag = false;
        $scope.isformValid = true;
        var criteria = {
            Type: $scope.charitySearchCriteria.Type,
            SearchValue: searchValue,
            SearchCriteria: $scope.charitySearchCriteria.SearchCriteria,
            PageID: 1,
            PageCount: 10
        }
        $rootScope.data = criteria;
        $location.path("/cftBusinessDetails");
        //$scope.businesssearchcriteria.RegistrationNumber = '';
        //$scope.businesssearchcriteria.cftBusinessName = '';
        //$scope.businessSearchEntity.SearchCriteria = '';
        searchCriteria = '';
        searchValue = '';
        //}
        //});
    };


    var searchValue1 = null, searchCriteria1 = null;
    $scope.searchCFTBasic = function (basicsearchForm) {
        $scope.isShowErrorFlag = true;
        if ($scope[basicsearchForm].$valid) {
            $scope.isShowErrorFlag = false;
            if ($scope.isUserLoggedIn) {
                switch ($scope.charitySearchCriteria.Type) {
                    case "RegistrationNumber":
                        searchValue1 = $scope.charitySearchCriteria.ID;
                        break;
                    case "OrganizationName":
                        searchValue1 = $scope.charitySearchCriteria.OrgName;
                        searchCriteria1 = 'contains';
                        break;
                    case "FEINNo":
                        searchValue1 = $scope.charitySearchCriteria.ID;
                        break;
                    case "UBINumber":
                        searchValue1 = $scope.charitySearchCriteria.ID;
                        break;
                    default:
                }

                $scope.isformValid = true;
                $scope.charitySearchCriteria.IsSearch = false;
                $scope.charitySearchCriteria.Type = $scope.charitySearchCriteria.Type;
                $scope.charitySearchCriteria.SearchValue = searchValue1;
                $scope.charitySearchCriteria.SearchCriteria = searchCriteria1;
                loadBasicCFList(constant.ZERO); // loadBasicCFList method is available in this controller only.
                //$location.path("/cftBusinessDetails");
                //$scope.businesssearchcriteria.RegistrationNumber = '';
                //$scope.businesssearchcriteria.cftBusinessName = '';
                //$scope.businessSearchEntity.SearchCriteria = '';
                searchCriteria = '';
                searchValue1 = '';
            }
        }

    };

    // search Charity and Fundraiser list
    $scope.searchCF = function (searchform) {
        $scope.businesssearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadBasicCFList(searchform); // loadBasicCFList method is available in this controller only.
    };

    function loadBasicCFList(page) {
        if ($rootScope.isBasicSearchBack == true) {
            //$scope.charitySearchCriteria = $cookieStore.get('cftBasicSearchcriteria');
            $scope.charitySearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        }
        else {
            page = page || constant.ZERO;
            $scope.charitySearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
            //$scope.charitySearchCriteria.Type = $scope.charitySearchCriteria.Type;
            //$scope.charitySearchCriteria.SearchValue = searchValue1;
            //$scope.charitySearchCriteria.SearchCriteria = searchCriteria1;
        }
        var data = angular.copy($scope.charitySearchCriteria);
        $rootScope.data = $scope.charitySearchCriteria;
        $scope.basicSearchCriteria = $scope.charitySearchCriteria;
        data.ID = "";
        $scope.isButtonSerach = page == 0;
        // getCFTCharityFundraiserSearchDetails method is available in constants.js
        wacorpService.post(webservices.CFT.getCFTCharityFundraiserSearchDetails, data, function (response) {
            //wacorpService.post(webservices.CFT.getCFTPublicSearchResults, data, function (response) {
            $scope.basicSearchResult = response.data;

            $cookieStore.put('cftBasicSearchcriteria', $scope.charitySearchCriteria);
            if ($scope.charitySearchCriteria.Type == "FEINNo" || $scope.charitySearchCriteria.Type == "UBINumber")
            {
                $scope.charitySearchCriteria.ID = $scope.charitySearchCriteria.SearchValue;
            }
            if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                var totalcount = response.data.length > 0 ? response.data[constant.ZERO].Criteria.TotalRowCount : 0;
                if (totalcount != 0) {
                    var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                    $scope.pagesCount = response.data.length < $scope.basicSearchCriteria.PageCount && page > constant.ZERO ? $scope.pagesCount : pagecount;
                    $scope.totalCount = totalcount;
                }
            }
            else if (response.data.length == constant.ZERO) {
                $scope.pagesCount = constant.ZERO;
                $scope.totalCount = constant.ZERO;
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            $rootScope.data = null;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    //navigate to business information
    $scope.showBasicBusineInfo = function (id, businessType, flag) {
        if ($scope.isUserLoggedIn) {
            if (!flag) {
                $scope.charitySearchCriteria.CFTId = id;
                $scope.charitySearchCriteria.Businesstype = businessType;
                $rootScope.data = $scope.charitySearchCriteria;
                $rootScope.isBasicSearch = true;
                $rootScope.isAdvanceSearch = null;
                $cookieStore.put('cftBasicBusinessSearchcriteriaId', $scope.charitySearchCriteria.CFTId);
                $cookieStore.put('cftBasicBusinessSearchcriteriaType', $scope.charitySearchCriteria.Businesstype);
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navCharityFoundationOrganization();
            }
            else {
                $scope.charitySearchCriteria.CFTId = id;
                $scope.charitySearchCriteria.Businesstype = businessType;
                $cookieStore.put('cftBusinessSearchcriteriaId', $scope.charitySearchCriteria.CFTId);
                $cookieStore.put('cftBusinessSearchcriteriaType', $scope.charitySearchCriteria.Businesstype);
                $rootScope.data = $scope.charitySearchCriteria;
                $rootScope.isBasicSearch = true;
                $rootScope.isAdvanceSearch = null;
                $scope.navigate($rootScope.data);
            }
        }
    }

    $scope.navigate = function (data) {
        $window.sessionStorage.removeItem('orgData');
        var obj = {
            org: data,
            viewMode: true,
            isBasicSearch: true,
        }
        $window.sessionStorage.setItem('orgData', JSON.stringify(obj));
        $window.open('#/organization');
        $window.sessionStorage.removeItem('orgData');
    }

    $scope.basicSearchFeinData = function (type, value) {
        if ($scope.isUserLoggedIn)
        {
            $scope.cftBasicFeinSearchcriteria.Type = type;
            $scope.cftBasicFeinSearchcriteria.SearchValue = value;
            $scope.cftBasicFeinSearchcriteria.IsSearch = true;
            $scope.cftBasicFeinSearchcriteria.PageID = 1;
            $('#divCharitiesBasicSearchResult').modal('toggle');
            loadCFeinList(constant.ZERO); // loadCFeinList method is available in this controller only.
        }

    };

    // search fein details associated to charity
    $scope.searchFein = function (searchform) {
        $scope.cftBasicFeinSearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadCFeinList(searchform); // loadCFeinList method is available in this controller only.
    };

    //to get data for FEIN link
    function loadCFeinList(page) {
        if ($rootScope.isFeinBasicSearchBack == true) {
            $cookieStore.put('cftFeinSearchcriteria', $scope.cftBasicFeinSearchcriteria);
            $scope.cftBasicFeinSearchcriteria = $cookieStore.get('cftFeinSearchcriteria');
            $scope.cftBasicFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        }
        else {
            page = page || constant.ZERO;
            $scope.cftBasicFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
            $scope.cftBasicFeinSearchcriteria.SearchCriteria = "";
        }
        var data = angular.copy($scope.cftBasicFeinSearchcriteria);
        $scope.isButtonSerach = page == 0;
        //getFEINDataDetailsFundraiserSearchDetails method is available in constants.js
        wacorpService.post(webservices.CFT.getFEINDataDetailsFundraiserSearchDetails, data, function (response) {
            $scope.BasicFeinDataDetails = response.data;
            if ($scope.cftBasicFeinSearchcriteria.PageID == 1)
                //$('#divCharitiesBasicSearchResult').modal('toggle');
                $cookieStore.put('cftFeinSearchcriteria', $scope.cftBasicFeinSearchcriteria);

            if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                var totalcount = response.data.length > 0 ? response.data[constant.ZERO].Criteria.TotalRowCount : 0;
                if (totalcount != 0) {
                    var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                    $scope.pagesCount1 = response.data.length < $scope.cftBasicFeinSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount1 : pagecount;
                    $scope.totalCount = totalcount;
                }
            }
            $scope.page1 = page;
            $scope.BusinessListProgressBar = false;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }


    $scope.cancel = function () {
        $("#divCharitiesBasicSearchResult").modal('toggle');
    }

    function cftloadingText(flag) {
        if (flag == true)
            $scope.loadingText = "Processing ...";
        else
            $scope.loadingText = "Search";
    }

    $scope.setPastedRegNumberHome = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
            $scope.charitySearchCriteria.ID = pastedText;            
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                $scope.charitySearchCriteria.ID = pastedText;
            });
        }
        $scope.checkValue($scope.charitySearchCriteria.ID);
    };

    $scope.setPastedUbiHome = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.charitySearchCriteria.ID = pastedText;            
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.charitySearchCriteria.ID = pastedText;
            });
        }
        $scope.checkValue($scope.charitySearchCriteria.ID);
    };



    $scope.DownloadActivityReport = function (fileName) {

        $http({
            method: "GET",
            // downloadActivityReport method is available in constants.js
            url: webservices.CFT.downloadActivityReport + "?fileName=" + fileName + "", // downloadActivityReport method is available in constants.js
            headers: {
                accept: 'application/octet-stream' //or whatever you need
            },
            responseType: 'arraybuffer',
            cache: false,
            transformResponse: function (data, headers) {
                headers = headers();
                if (headers['content-type'] == undefined || headers['content-type'] != 'application/octet-stream') {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog("File Not Found");
                }
                else {
                    var file = new Blob([data], {
                        type: 'application/octet-stream' //or whatever you need, should match the 'accept headers' above
                    });

                    saveAs(file, fileName)
                }
            },
        })
        .then(function (result) {
         }, function (error) {
         });
    }



    $scope.setRegNumberLengthHome = function (e) {
        if ($scope.businessSearchEntity.RegistrationNumber.length > 8) {
            e.preventDefault();
        }
    };
    //clear text on selecting radio button
    $scope.cleartext = function () {
        $scope.charitySearchCriteria.ID = null;
        $scope.charitySearchCriteria.OrgName = null;
    };
    $scope.checkValue = function (value, id) {
        if (value != "" && value != undefined && value.length > 0) {
            $scope.formValid = true;
        }
        else
            $scope.formValid = false;

        //$('#'+id).focus();
    };
    $scope.CharityUBI = function (e) {
        if ($scope.charitySearchCriteria.ID.length >= 9) {
            if (e.which != 97) {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                    // Allow: Ctrl+A, Command+A
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right, down, up
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
                e.preventDefault();
            }
        }
        //if ($scope.charitySearchCriteria.ID.length >= 9) {
        //    e.preventDefault();
        //    return false;
        //}

    };
});

wacorpApp.controller('cftBusinessDetailsController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, $window) {
    // variable initilization
    $scope.page = constant.ZERO;
    $scope.page1 = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.pagesCount1 = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.cftSearchcriteria = {};
    $scope.isButtonSerach = false;
    $scope.cftBusinessSearch = [];
    $scope.feinDataDetails = [];
    $scope.criteria = [];
    $scope.cftBusinesssearchType = {};
    $scope.search = loadCFList;
    $scope.isAdvanceSearch = false;
    $scope.cftBusinessSearchcriteria = {};
    $scope.cftSearchcriteria = {
        EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false, EntityWebsite: null,
        RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, BusinessType: "", Type: "", SearchValue: "", SearchCriteria: "", SortBy: null, SortType: null
    };

    $scope.cftFeinSearchcriteria = {
        EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false, EntityWebsite: null,
        RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, BusinessType: "", Type: "", SearchValue: "", SearchCriteria: "", SortBy: null, SortType: null
    };

    $scope.loggedUser = false;
    if ($rootScope.repository.loggedUser != undefined)
        $scope.loggedUser = true;
    //scope initialzation
    $scope.initCFBusinessSearch = function () {
        $scope.criteria = $rootScope.data;
        loadCFList(constant.ZERO); // loadCFList method is available in this controller only.
        $scope.cftBusinesssearchType = $cookieStore.get('cftBusinessSearchcriteriaId');
        $scope.cftBusinessSearchcriteria = $cookieStore.get('cftBusinessSearchcriteriaType');

    }


    // search Charity and Fundraiser list
    $scope.searchCF = function (searchform, sortBy) {
        $scope.cftSearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadCFList(searchform, sortBy); // loadCFList method is available in this controller only.
    };

    //navigate to business information
    $scope.showBusineInfo = function (id, businessType, flag) {
        if (!flag) {
            $scope.cftBusinessSearch.CFTId = id;
            $scope.cftBusinessSearch.Businesstype = businessType;
            $rootScope.data = $scope.cftBusinessSearch;
            $rootScope.isAdvanceSearch = false;
            $cookieStore.put('cftBusinessSearchcriteriaId', $scope.cftBusinessSearch.CFTId);
            $cookieStore.put('cftBusinessSearchcriteriaType', $scope.cftBusinessSearch.Businesstype);
            //$scope.cancel();
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCharityFoundationOrganization();
        }
        else {
            $scope.cftBusinessSearch.CFTId = id;
            $scope.cftBusinessSearch.Businesstype = businessType;
            $cookieStore.put('cftBusinessSearchcriteriaId', $scope.cftBusinessSearch.CFTId);
            $cookieStore.put('cftBusinessSearchcriteriaType', $scope.cftBusinessSearch.Businesstype);
            $rootScope.data = $scope.cftBusinessSearch;
            $scope.navigate($rootScope.data);
        }

    }

    $scope.navigate = function (data) {
        $window.sessionStorage.removeItem('orgData');
        var obj = {
            org: data,
            viewMode: true,
            flag: false,
        }
        $window.sessionStorage.setItem('orgData', JSON.stringify(obj));
        $window.open('#/organization');
        $window.sessionStorage.removeItem('orgData');
    }



    // get Charity and Fundraiser list data from server
    function loadCFList(page, sortBy) {
        if ($rootScope.isCftOrganizationSearchBack == true) {
            $scope.cftSearchcriteria = $cookieStore.get('cftSearchcriteria');
            page = page || constant.ZERO;
            $scope.cftSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        }
        else {
            page = page || constant.ZERO;
            $scope.cftSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
            $scope.cftSearchcriteria.Type = $scope.criteria.Type;
            $scope.cftSearchcriteria.SearchValue = $scope.criteria.SearchValue;
            $scope.cftSearchcriteria.SearchCriteria = $scope.criteria.SearchCriteria;
        }
        if (sortBy != undefined) {
            if ($scope.cftSearchcriteria.SortBy == sortBy) {
                if ($scope.cftSearchcriteria.SortType == 'ASC') {
                    $scope.cftSearchcriteria.SortType = 'DESC';
                }
                else {
                    $scope.cftSearchcriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.cftSearchcriteria.SortBy = sortBy;
                $scope.cftSearchcriteria.SortType = 'ASC';
            }
        }
        else {
            if ($scope.cftSearchcriteria.Type == "OrganizationName")
            {
                if ($scope.cftSearchcriteria.SortBy == null || $scope.cftSearchcriteria.SortBy == "" || $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "OrganizationName";
                if ($scope.cftSearchcriteria.SortType == null || $scope.cftSearchcriteria.SortType == "" || $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = 'ASC';
            }
            else if ($scope.cftSearchcriteria.Type == "FEINNo")
            {
                if ($scope.cftSearchcriteria.SortBy == null || $scope.cftSearchcriteria.SortBy == "" || $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "FEINNo";
                if ($scope.cftSearchcriteria.SortType == null || $scope.cftSearchcriteria.SortType == "" || $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = 'ASC';
            }
            else if ($scope.cftSearchcriteria.Type == "UBINumber")
            {
                if ($scope.cftSearchcriteria.SortBy == null || $scope.cftSearchcriteria.SortBy == "" || $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "UBINumber";
                if ($scope.cftSearchcriteria.SortType == null || $scope.cftSearchcriteria.SortType == "" || $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = 'ASC';
            }
        }
        var data = angular.copy($scope.cftSearchcriteria);
        $scope.isButtonSerach = page == 0;
        $rootScope.isAdvanceSearch = false;
        //wacorpService.post(webservices.CFT.getCFTCharityFundraiserSearchDetails, data, function (response) {
        // getCFTPublicSearchResults method is available in constants.js
        wacorpService.post(webservices.CFT.getCFTPublicSearchResults, data, function (response){
            $scope.cftBusinessSearch = response.data;
            $cookieStore.put('cftSearchcriteria', $scope.cftSearchcriteria);

            if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                var totalcount = response.data.length > 0 ? response.data[constant.ZERO].Criteria.TotalRowCount : 0;
                if (totalcount != 0) {
                    var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                    $scope.pagesCount = response.data.length < $scope.cftSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount : pagecount;
                    $scope.totalCount = totalcount;
                }
            }
            else if (response.data.length == constant.ZERO) {
                $scope.pagesCount = constant.ZERO;
                $scope.totalCount = constant.ZERO;
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }


    $scope.searchFeinData = function (type, value) {
        $scope.cftFeinSearchcriteria.Type = type;
        $scope.cftFeinSearchcriteria.SearchValue = value;
        $scope.cftFeinSearchcriteria.IsSearch = true;
        $scope.cftFeinSearchcriteria.PageID = 1;
        loadCFeinList(constant.ZERO); // loadCFeinList method is available in this controller only.

        $('#divFeinResult').modal('toggle');
    };

    // search fein details associated to charity
    $scope.searchFein = function (searchform) {
        $scope.cftFeinSearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadCFeinList(searchform); // loadCFeinList method is available in this controller only.
    };

    $scope.exportCSVServer = function () {
        var criteria = null;
        var searchinfo = angular.copy($scope.cftSearchcriteria);
        searchinfo.PageID = 1;
        searchinfo.PageCount = 9999999;
        // getCFTPublicSearchResults method is available in constants.js
        wacorpService.post(webservices.CFT.getCFTPublicSearchResults, searchinfo, function (response) {
            var result = [];
            result = response.data;            
            $rootScope.exportToCSV(result)

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);

        });

    }

    //Export Data to CSV
    $rootScope.exportToCSV = function (exportData) {

        var arrData = typeof exportData != 'object' ? JSON.parse(exportData) : exportData;

        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
        });

        var CSV = '';
        var row = "";

        var rowData = "";
        //Preapring Candidate Data
        var arrData1 = [];
        candidateColumns = ["Organization Name", "City Name", "Percent to Program Services (Ranges of 10%)"];
        $.each(arrData, function (index, element) {

            arrData1.push({
                "Organization Name": element.EntityName + ((element.AKANames != null && element.AKANames != '') ? '(' + element.AKANames + ')' : ''), "City Name": element.EntityMailingAddress.City,
                "Percent to Program Services (Ranges of 10%)": element.PercentToProgramServices, 

            })
        });
        $.each(arrData1, function (index, Data) {

            rowData = "";
            $.each(Data, function (headerName, Data) {
                if (candidateColumns.indexOf(headerName) != -1) {
                    if (index == 0) {
                        if (headerName == "Organization Name") {
                            headerName = "Organization Name";
                        }
                        else if (headerName == "City Name") {
                            headerName = "	City Name";
                        }
                        else if (headerName == "Percent to Program Services (Ranges of 10%)") {
                            headerName = "Percent to Program Services (Ranges of 10%)";
                        }


                        row += headerName + ',';
                    }
                    if (typeof Data === 'string') {
                        if (Data) {
                            if (Data.indexOf(',') != -1) {
                                Data = '"' + Data + '"';
                            }
                        }
                        //Data = Data.replace(/,/g, " ")
                    }

                    else {
                        if (!Data) {
                            Data = '';
                        }
                        else {
                            Data = Data;
                        }

                    }
                    if (headerName == 'Email' || headerName == 'Email') {
                        rowData = rowData + Data;
                    }
                    else {
                        rowData += Data + ",";
                    }


                }

            });

            if (index == 0) {
                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }
            rowData.slice(0, rowData.length - 1);

            //add a line break after each row
            CSV += rowData + '\r\n';
        });

        row = ""; csv = ""; rowData = "";

        //Generate a file name
        var fileName = "Charity/Fundraiser/Trust SearchList";


        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        if (navigator.msSaveBlob) {
            var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
            navigator.msSaveBlob(blob, "fileName.csv")

        } else {
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        //}
    }

    //to get data for FEIN link
    function loadCFeinList(page) {
        if ($rootScope.isCftOrganizationSearchBack == true) {
            page = page || constant.ZERO;
            $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
            $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);
            $scope.cftFeinSearchcriteria = $cookieStore.get('cftFeinSearchcriteria');
        }
        else {
            page = page || constant.ZERO;
            $scope.cftFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
            //$scope.cftFeinSearchcriteria.Type = $scope.criteria.Type;
            //$scope.cftFeinSearchcriteria.SearchValue = $scope.criteria.SearchValue;
            $scope.cftFeinSearchcriteria.SearchCriteria = "";
        }
        var data = angular.copy($scope.cftFeinSearchcriteria);
        $scope.isButtonSerach = page == 0;
        $rootScope.isAdvanceSearch = false;
        // getFEINDataDetailsFundraiserSearchDetails method is available in constants.js
        wacorpService.post(webservices.CFT.getFEINDataDetailsFundraiserSearchDetails, data, function (response) {
            $scope.feinDataDetails = response.data;
            if ($scope.cftFeinSearchcriteria.PageID == 1)
                //$('#divFeinResult').modal('toggle');
                $cookieStore.put('cftFeinSearchcriteria', $scope.cftFeinSearchcriteria);

            if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                var totalcount = response.data.length > 0 ? response.data[constant.ZERO].Criteria.TotalRowCount : 0;
                if (totalcount != 0) {
                    var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                    $scope.pagesCount1 = response.data.length < $scope.cftFeinSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount1 : pagecount;
                    $scope.totalCount = totalcount;
                }
            }
            $scope.page1 = page;
            $scope.BusinessListProgressBar = false;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.cancel = function () {
        $("#divFeinResult").modal('toggle');
    }

    $scope.$watch('cftSearchcriteria', function () {
        if ($scope.cftBusinessSearch == undefined)
            return;
        if ($scope.cftBusinessSearch == constant.ZERO) {
            $scope.totalCount = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.page = constant.ZERO;
        }
    }, true);

});
wacorpApp.controller('trademarkDetailsController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, $window, lookupService, wacorpService, ScopesData) {
    
    // variable initilization
    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.trademarkSearch = {};
    $scope.isButtonSerach = false;
    $rootScope.isAdvanceSearch = false;
    $scope.cftOrganizationSearchType = false;
    $scope.IsType = false;
    $scope.TradeMarkList = [];

    $scope.criteria = { Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, IsSearch: true, SearchValue: "", SearchCriteria: "", RegistrationNumber: null, SortType: null, SortBy: null };
    $scope.trademarkSearch = {
        Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, isCftOrganizationSearchBack: false,
        TradeMarkText: null, TradeMarkOwner: null, RegistrationNumber: null, UBINumber: null, Contains: searchTypes.Contains, isSearchClick: false,SortType:null,SortBy:null,
        SearchCriteria: "", Selectiontype: searchTypes.Contains
    };
    $scope.trademarkSearch.Type = searchTypes.RegistrationNumber;

    $scope.initTradeSearch = function () {
        
        if ($rootScope.data && $rootScope.data != "") {
            if ($cookieStore.get('trademarkSearchCriteria') != undefined) {
                $scope.trademarkSearch = $cookieStore.get('trademarkSearchCriteria');
            }
            $scope.trademarkSearch.isSearchClick = true;
            $rootScope.data = null;
            loadTradeList(constant.ZERO); // loadTradeList method is available in this controller only.
        }
        setFocus(); // setFocus method is available in this controller only.
    };

    $scope.hideOption = function (value) {
        $scope.IsType = false;
        $scope.trademarkSearch.Type = value;
        switch (value) {
            case "RegistrationNumber":
                $('#txtTrademarkNo').focus();
                $scope.trademarkSearch.TradeMarkOwner = null;
                $scope.trademarkSearch.TradeMarkText = null;
                $scope.trademarkSearch.UBINumber = null;
                $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                //$('#rdoTradeNo').prop('checked', true);
                $scope.trademarkSearch.Type = searchTypes.RegistrationNumber;
                break;
            case "TrademarkOwner":
                $scope.trademarkSearch.RegistrationNumber = null;
                $scope.trademarkSearch.TradeMarkText = null;
                $scope.trademarkSearch.UBINumber = null;
                $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                $('#rdoTradename').prop('checked', true);
                $('#txtOwnerName').focus();
                $scope.IsType = true;
                break;
            case "TrademarkText":

                $scope.trademarkSearch.RegistrationNumber = null;
                $scope.trademarkSearch.TradeMarkOwner = null;
                $scope.trademarkSearch.UBINumber = null;
                if ($scope.trademarkSearch.Selectiontype == searchTypes.Contains)
                    $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                $('#rdoTradetext').prop('checked', true);
                $('#txtTradetext').focus();
                $scope.IsType = true;
                break;
            case "UBINumber":
                $scope.trademarkSearch.RegistrationNumber = null;
                $scope.trademarkSearch.TradeMarkOwner = null;
                $scope.trademarkSearch.TradeMarkText = null;
                $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                $('#rdoTradeUbi').prop('checked', true);
                $('#txtTradeUbi').focus();
                break;
            default:

        }
    };


    function setFocus() {
        $scope.hideOption($scope.trademarkSearch.Type);

    };

    $scope.clearFun = function () {
        $scope.trademarkSearch.RegistrationNumber = null;
        $scope.trademarkSearch.TradeMarkOwner = null;
        $scope.trademarkSearch.TradeMarkText = null;
        $scope.trademarkSearch.UBINumber = null;
        $scope.trademarkSearch.isSearchClick = false;
        $scope.IsType = false;
        $scope.trademarkSearch.Type = searchTypes.RegistrationNumber;
        $('#txtTrademarkNo').focus();
    };

    $scope.setPastedTradeNum = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.RegistrationNumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.RegistrationNumber = pastedText;
            });
        }
    };


    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.UBINumber = pastedText;
            });
        }
    };

    $scope.searchTrade = function (Trademarksearchform) {
        
        $scope.isShowErrorFlag = true;
        if ($scope[Trademarksearchform].$valid) {
            $scope.isShowErrorFlag = false;
            $scope.isButtonSerach = true
            $scope.trademarkSearch.isSearchClick = true;
            $rootScope.isTradeBackSearch = false;
            loadTradeList(constant.ZERO); // loadTradeList method available in this controller only
        }
    };

    $scope.searchTradePagination = function (Trademarksearchform, sortBy) {
        $scope.isButtonSerach = true
        $scope.trademarkSearch.isSearchClick = true;
        loadTradeList(Trademarksearchform, sortBy); // loadTradeList method available in this controller only
    };


    //to get Trademark serach result list.
    function loadTradeList(page, sortBy) {
        
        page = page || constant.ZERO;
        $scope.trademarkSearch.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        if ($scope.trademarkSearch.Type == "RegistrationNumber"  || $scope.trademarkSearch.Type == "UBINumber")
            $scope.criteria.SearchCriteria = "";
        else {
            if ($rootScope.isTradeBackSearch == true) {
                //$scope.trademarkSearch.SearchCriteria = $rootScope.data.SearchCriteria;
                $scope.criteria.SearchCriteria = $scope.trademarkSearch.SearchCriteria;
            }
            else {
                var value = $('input[name="trademarkType"]:checked').val();
                if ($scope.criteria.SearchCriteria == null || $scope.criteria.SearchCriteria == "") {
                    $scope.criteria.SearchCriteria = value;
                    $scope.trademarkSearch.SearchCriteria = value;
                }
            }

        }

        $scope.criteria.Type = $scope.trademarkSearch.Type;

        switch ($scope.trademarkSearch.Type) {

            case "RegistrationNumber":
                $scope.criteria.SearchValue = $scope.trademarkSearch.RegistrationNumber;
                break;
            case "TrademarkOwner":
                $scope.criteria.SearchValue = $scope.trademarkSearch.TradeMarkOwner;
                break;
            case "TrademarkText":
                $scope.criteria.SearchValue = $scope.trademarkSearch.TradeMarkText;
                break;
            case "UBINumber":
                $scope.criteria.SearchValue = $scope.trademarkSearch.UBINumber;
                break;
            default:
        }
        $scope.criteria.PageID = $scope.trademarkSearch.PageID;
        if (sortBy != undefined) {
            if ($scope.criteria.SortBy == sortBy) {
                if ($scope.criteria.SortType == 'ASC') {
                    $scope.criteria.SortType = 'DESC';
                }
                else {
                    $scope.criteria.SortType = 'ASC';
                }
            }
            else {
                $scope.criteria.SortBy = sortBy;
                $scope.criteria.SortType = 'ASC';
            }
        }
        else {
            if ($scope.criteria.Type == "TrademarkOwner")
            {
                if ($scope.criteria.SortBy == null || $scope.criteria.SortBy == "" || $scope.criteria.SortBy == undefined)
                    $scope.criteria.SortBy = "Applicant/OwnerName";

                if($scope.criteria.SortType==null || $scope.criteria.SortType=="" || $scope.criteria.SortType==undefined)
                        $scope.criteria.SortType = 'ASC';

            }
            else if ($scope.criteria.Type == "RegistrationNumber")
            {
                if($scope.criteria.SortBy==null || $scope.criteria.SortBy=="" || $scope.criteria.SortBy==undefined)
                    $scope.criteria.SortBy = "Registration/ReservationNumber";

                if($scope.criteria.SortType==null || $scope.criteria.SortType=="" || $scope.criteria.SortType==undefined)
                    $scope.criteria.SortType = 'ASC';
            }
            else if ($scope.criteria.Type == "TrademarkText")
            {
                if ($scope.criteria.SortBy == null || $scope.criteria.SortBy == "" || $scope.criteria.SortBy == undefined)
                    $scope.criteria.SortBy = "TrademarkText";

                if ($scope.criteria.SortType == null || $scope.criteria.SortType == "" || $scope.criteria.SortType == undefined)
                    $scope.criteria.SortType = 'ASC';
            }
            else if ($scope.criteria.Type == "UBINumber")
            {
                if ($scope.criteria.SortBy == null || $scope.criteria.SortBy == "" || $scope.criteria.SortBy == undefined)
                    $scope.criteria.SortBy = "UBINumber";

                if ($scope.criteria.SortType == null || $scope.criteria.SortType == "" || $scope.criteria.SortType == undefined)
                    $scope.criteria.SortType = 'ASC';
            }
        }
        var data = angular.copy($scope.criteria);
        $scope.isButtonSerach = page == 0;
        // getTrademarSearchDetails method is available in constants.js
        //wacorpService.post(webservices.BusinessSearch.getTrademarSearchDetails, data, function (response) {  //TFS 1500 mkr Spelling Error
        wacorpService.post(webservices.BusinessSearch.getTrademarkSearchDetails, data, function (response) {
            $scope.TradeMarkList = response.data;
            $cookieStore.put('trademarkSearchCriteria', $scope.trademarkSearch);
            if ($scope.isButtonSerach && response.data.length > 0) {
                var totalcount = response.data.length > 0 ? response.data[constant.ZERO].Criteria.TotalRowCount : 0;
                if (totalcount != 0) {
                    var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                    $scope.pagesCount = response.data.length < $scope.trademarkSearch.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                    $scope.totalCount = totalcount;
                    //$scope.searchval = criteria.SearchValue;
                    criteria = response.data[constant.ZERO].Criteria;
                }
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus("tblTrademarkSearch");
        }, function (response) {
            $scope.selectedEntity = null;
            // Folder Name: services
            // Controller Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.exportCSVServer = function () {
        var criteria = null;
        var searchinfo = angular.copy($scope.criteria);
        searchinfo.PageID = 1;
        searchinfo.PageCount = 9999999;
        // getTrademarSearchDetails method is available in constants.js
        //wacorpService.post(webservices.BusinessSearch.getTrademarSearchDetails, searchinfo, function (response) {  //TFS 1500 mkr spelling error
        wacorpService.post(webservices.BusinessSearch.getTrademarkSearchDetails, searchinfo, function (response) {
            var result = [];
            result = response.data;
            $rootScope.exportToCSV(result)

        }, function (response) {
            // Folder Name: services
            // Controller Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);

        });

    }

    //Export Data to CSV
    $rootScope.exportToCSV = function (exportData) {

        var arrData = typeof exportData != 'object' ? JSON.parse(exportData) : exportData;

        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
        });

        var CSV = '';
        var row = "";

        var rowData = "";
        //Preparing Candidate Data
        var arrData1 = [];
        candidateColumns = ["Registration #", "Trademark Text", "Registration/Reservation Date", "Expiration Date", "Classification", "Goods", "Services", "Status"];
        $.each(arrData, function (index, element) {

            arrData1.push({
                "Registration #": element.TrademarkRegistrationNo, "Trademark Text": element.TrademarkText, "Registration/Reservation Date": element.RegistrationDate.split('T')[0], "Expiration Date": element.ExpirationDate.split('T')[0],
                "Classification": element.TrademarkClassification, "Goods": element.TrademarkGoods, "Services": element.TrademarkServices, "Status": element.TrademarkStatus,

            })
        });
        $.each(arrData1, function (index, Data) {

            rowData = "";
            $.each(Data, function (headerName, Data) {
                if (candidateColumns.indexOf(headerName) != -1) {
                    if (index == 0) {
                        if (headerName == "Registration #") {
                            headerName = "Registration #";
                        }
                        else if (headerName == "Trademark Text") {
                            headerName = "Trademark Text";
                        }
                        else if (headerName == "Registration/Reservation Date") {
                            headerName = "Registration/Reservation Date";
                        }
                        else if (headerName == "Expiration Date") {
                            headerName = "Expiration Date";
                        }
                        else if (headerName == "Classification") {
                            headerName = "Classification";
                        }
                        else if (headerName == "Goods") {
                            headerName = "Goods";
                        }
                        else if (headerName == "Services") {
                            headerName = "Services";
                        }
                        else if (headerName == "Status") {
                            headerName = "Status";
                        }

                        row += headerName + ',';
                    }
                    if (typeof Data === 'string') {
                        if (Data) {
                            if (Data.indexOf(',') != -1) {
                                Data = '"' + Data + '"';
                            }
                        }
                        //Data = Data.replace(/,/g, " ")
                    }

                    else {
                        if (!Data) {
                            Data = '';
                        }
                        else {
                            Data = Data;
                        }

                    }
                    if (headerName == 'Email' || headerName == 'Email') {
                        rowData = rowData + Data;
                    }
                    else {
                        rowData += Data + ",";
                    }


                }

            });

            if (index == 0) {
                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }
            rowData.slice(0, rowData.length - 1);

            //add a line break after each row
            CSV += rowData + '\r\n';
        });

        row = ""; csv = ""; rowData = "";

        //Generate a file name
        var fileName = "TrademarkSearchList";


        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        if (navigator.msSaveBlob) {
            var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
            navigator.msSaveBlob(blob, "fileName.csv")

        } else {
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        //}
    }


    //to get trademark details
    $scope.searchTrademark = function (value) {
        if (value != null && value != undefined) {
            $rootScope.isTrademarkPublicSearch = true;
            $scope.criteria.RegistrationNumber = value;
            $rootScope.data = $scope.criteria;
            $location.path('/trademarkInformation')
        }
    }
});
wacorpApp.controller('trademarkSearchController', function ($scope, wacorpService, focus, $rootScope, $cookieStore, $timeout, $routeParams, $location) {
    // variable initialization
    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.trademarkSearch = {};
    $scope.isButtonSerach = false;
    $rootScope.isAdvanceSearch = false;
    $scope.cftOrganizationSearchType = false;
    $scope.IsType = false;
    $scope.TradeMarkList = [];
    $rootScope.isTrademarkPublicSearch = false;
    $scope.criteria = { Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, IsSearch: true, SearchValue: "", SearchCriteria: "", RegistrationNumber: null, SortType: null, SortBy: null };
    $scope.trademarkSearch = {
        Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, isCftOrganizationSearchBack: false,
        TradeMarkText: null, TradeMarkOwner: null, RegistrationNumber: null, UBINumber: null, Contains: searchTypes.Contains, isSearchClick: false, SortType: null, SortBy: null,
        SearchCriteria: "", Selectiontype: searchTypes.Contains
    };
    $scope.trademarkSearch.Type = searchTypes.RegistrationNumber;

    $rootScope.clearTrademarkSearchResults = function () {
        $scope.clearFun();
    }

    $scope.initTradeSearch = function () {

        if ($rootScope.data && $rootScope.data != "") {
            $scope.trademarkSearch = $cookieStore.get('trademarkSearchCriteria');
            $scope.trademarkSearch.isSearchClick = true;
            $rootScope.data = null;
            loadTradeList(constant.ZERO); // loadTradeList method is available in this controller only.
        }
        setFocus(); // setFocus method is available in this controller only.
    };

    $scope.hideOption = function (value) {
        $scope.IsType = false;
        $scope.trademarkSearch.Type = value;
        switch (value) {
            case "RegistrationNumber":
                $('#txtTrademarkNo').focus();
                $scope.trademarkSearch.TradeMarkOwner = null;
                $scope.trademarkSearch.TradeMarkText = null;
                $scope.trademarkSearch.UBINumber = null;
                $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                //$('#rdoTradeNo').prop('checked', true);

                $scope.trademarkSearch.Type = searchTypes.RegistrationNumber;
                if ($scope.criteria) {
                    $scope.criteria.SortBy = "Registration/ReservationNumber";
                    $scope.criteria.SortType = 'ASC';
                }
                break;
            case "TrademarkOwner":
                $scope.trademarkSearch.RegistrationNumber = null;
                $scope.trademarkSearch.TradeMarkText = null;
                $scope.trademarkSearch.UBINumber = null;
                if ($scope.trademarkSearch.Selectiontype == searchTypes.Contains)
                    $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                //$scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                $('#rdoTradename').prop('checked', true);
                $scope.IsType = true;
                $('#txtOwnerName').focus();
                if ($scope.criteria) {
                    $scope.criteria.SortBy = "Applicant/OwnerName";
                    $scope.criteria.SortType = 'ASC';
                }
                break;
            case "TrademarkText":
                $scope.trademarkSearch.RegistrationNumber = null;
                $scope.trademarkSearch.TradeMarkOwner = null;
                $scope.trademarkSearch.UBINumber = null;
                if ($scope.trademarkSearch.Selectiontype == searchTypes.Contains)
                    $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                $('#rdoTradetext').prop('checked', true);
                $('#txtTradetext').focus();
                $scope.IsType = true;
                if ($scope.criteria) {
                    $scope.criteria.SortBy = "TrademarkText";
                    $scope.criteria.SortType = 'ASC';
                }

                break;
            case "UBINumber":
                $scope.trademarkSearch.RegistrationNumber = null;
                $scope.trademarkSearch.TradeMarkOwner = null;
                $scope.trademarkSearch.TradeMarkText = null;
                $scope.trademarkSearch.Selectiontype = searchTypes.Contains;
                $('#rdoTradeUbi').prop('checked', true);
                $('#txtTradeUbi').focus();
                if ($scope.criteria) {
                    $scope.criteria.SortBy = "UBINumber";
                    $scope.criteria.SortType = 'ASC';
                }

                break;
            default:

        }
    };


    function setFocus() {
        $scope.hideOption($scope.trademarkSearch.Type); // hideOption method is available in this file only.

    };

    $scope.clearFun = function () {
        $scope.trademarkSearch.RegistrationNumber = null;
        $scope.trademarkSearch.TradeMarkOwner = null;
        $scope.trademarkSearch.TradeMarkText = null;
        $scope.trademarkSearch.UBINumber = null;
        $scope.trademarkSearch.isSearchClick = false;
        $scope.IsType = false;
        $scope.trademarkSearch.Type = searchTypes.RegistrationNumber;
        $scope.criteria.SortBy = null;
        $scope.criteria.SortType = null;
        $('#txtTrademarkNo').focus();
    };

    $scope.setPastedTradeNum = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.RegistrationNumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.RegistrationNumber = pastedText;
            });
        }
    };


    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.UBINumber = pastedText;
            });
        }
    };

    $scope.searchTrade = function (Trademarksearchform) {
        $scope.isShowErrorFlag = true;
        if ($scope[Trademarksearchform].$valid) {
            $scope.isShowErrorFlag = false;
            $scope.isButtonSerach = true
            $scope.trademarkSearch.isSearchClick = true;
            $rootScope.isTradeBackSearch = false;
            loadTradeList(constant.ZERO); // loadTradeList method is available in this controller only.
        }
    };

    $scope.searchTradePagination = function (Trademarksearchform, sortBy) {
        $scope.isButtonSerach = true
        $scope.trademarkSearch.isSearchClick = true;
        loadTradeList(Trademarksearchform, sortBy); // loadTradeList method is available in this controller only.
    };


    //to get Trademark serach result list.
    function loadTradeList(page, sortBy) {
        //Ticket -- 3167
        $rootScope.isTrademarkBackButtonPressed = false;
        page = page || constant.ZERO;
        $scope.trademarkSearch.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        if ($scope.trademarkSearch.Type == "RegistrationNumber" || $scope.trademarkSearch.Type == "UBINumber")
            $scope.criteria.SearchCriteria = "";
        else {
            if ($rootScope.isTradeBackSearch == true) {
                //$scope.trademarkSearch.SearchCriteria = $rootScope.data.SearchCriteria;
                $scope.criteria.SearchCriteria = $scope.trademarkSearch.SearchCriteria;
            }
            else {
                var value = $('input[name="trademarkType"]:checked').val();
                //if ($scope.criteria.SearchCriteria == null || $scope.criteria.SearchCriteria == "") {
                $scope.criteria.SearchCriteria = value;
                $scope.trademarkSearch.SearchCriteria = value;
                // }
            }

        }

        $scope.criteria.Type = $scope.trademarkSearch.Type;

        switch ($scope.trademarkSearch.Type) {

            case "RegistrationNumber":
                $scope.criteria.SearchValue = $scope.trademarkSearch.RegistrationNumber;
                break;
            case "TrademarkOwner":
                $scope.criteria.SearchValue = $scope.trademarkSearch.TradeMarkOwner;
                break;
            case "TrademarkText":
                $scope.criteria.SearchValue = $scope.trademarkSearch.TradeMarkText;
                break;
            case "UBINumber":
                $scope.criteria.SearchValue = $scope.trademarkSearch.UBINumber;
                break;
            default:
        }
        $scope.criteria.PageID = $scope.trademarkSearch.PageID;
        if (sortBy != undefined) {
            if ($scope.criteria.SortBy == sortBy) {
                if ($scope.criteria.SortType == 'ASC') {
                    $scope.criteria.SortType = 'DESC';
                }
                else {
                    $scope.criteria.SortType = 'ASC';
                }
            }
            else {
                $scope.criteria.SortBy = sortBy;
                $scope.criteria.SortType = 'ASC';
            }
        }
        var data = angular.copy($scope.criteria);
        $scope.isButtonSerach = page == 0;
        // getTrademarSearchDetails method is available in constants.js
        //wacorpService.post(webservices.TraseMarkSearch.getTrademarSearchDetails, data, function (response) { !!!***** Spelling corrected 10/21/2019, KK
        //wacorpService.post(webservices.TraseMarkSearch.getTrademarSearchDetails, data, function (response) {  //TFS 1500 mkr Spelling error
        wacorpService.post(webservices.TradeMarkSearch.getTrademarkSearchDetails, data, function (response) {
            $scope.TradeMarkList = response.data;
            $cookieStore.put('trademarkSearchCriteria', $scope.trademarkSearch);
            if ($scope.isButtonSerach && response.data.length > 0) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                $scope.pagesCount = response.data.length < $scope.trademarkSearch.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                $scope.totalCount = totalcount;
                //$scope.searchval = criteria.SearchValue;
                criteria = response.data[constant.ZERO].Criteria;
            } else if (response.data.length == 0) {
                $scope.pagesCount = 0;
                $scope.totalCount = 0;
            }


            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus("tblTrademarkSearch");
        }, function (response) {
            $scope.selectedEntity = null;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    //to get trademark details
    $scope.searchTrademark = function (value) {
        //Ticket -- 3167
        $rootScope.isTrademarkBackButtonPressed = false;
        if (value != null && value != undefined) {
            $scope.criteria.RegistrationNumber = value;
            $rootScope.data = $scope.criteria;
            $location.path('/trademarkInformation')
        }
    }

    $scope.exportCSVServer = function () {
        var criteria = null;
        var searchinfo = angular.copy($scope.criteria);
        searchinfo.PageID = 1;
        searchinfo.PageCount = 9999999;
        // getTrademarSearchDetails method is available in constants.js
        //wacorpService.post(webservices.TradeMarkSearch.getTrademarSearchDetails, searchinfo, function (response) { !!!***** Spelling corrected 10/21/2019, KK
        //wacorpService.post(webservices.TradeMarkSearch.getTrademarSearchDetails, searchinfo, function (response) {  //TFS 1500 MKR
        wacorpService.post(webservices.TradeMarkSearch.getTrademarkSearchDetails, searchinfo, function (response) {
            var result = [];
            result = response.data;
            $rootScope.exportToCSV(result)

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);

        });

    }

    //Export Data to CSV
    $rootScope.exportToCSV = function (exportData) {

        var arrData = typeof exportData != 'object' ? JSON.parse(exportData) : exportData;

        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
        });

        var CSV = '';
        var row = "";

        var rowData = "";
        //Preparing Candidate Data
        var arrData1 = [];
        candidateColumns = ["Registration #", "Trademark Text", "Registration/Reservation Date", "Expiration Date", "Classification", "Goods", "Services", "Status"];
        $.each(arrData, function (index, element) {

            arrData1.push({
                "Registration #": element.TrademarkRegistrationNo, "Trademark Text": element.TrademarkText, "Registration/Reservation Date": element.RegistrationDate.split('T')[0], "Expiration Date": element.ExpirationDate.split('T')[0],
                "Classification": element.TrademarkClassification, "Goods": element.TrademarkGoods, "Services": element.TrademarkServices, "Status": element.TrademarkStatus,
            })
        });
        $.each(arrData1, function (index, Data) {

            rowData = "";
            $.each(Data, function (headerName, Data) {
                if (candidateColumns.indexOf(headerName) != -1) {
                    if (index == 0) {
                        if (headerName == "Registration #") {
                            headerName = "Registration #";
                        }
                        else if (headerName == "Trademark Text") {
                            headerName = "Trademark Text";
                        }
                        else if (headerName == "Registration/Reservation Date") {
                            headerName = "Registration/Reservation Date";
                        }
                        else if (headerName == "Expiration Date") {
                            headerName = "Expiration Date";
                        }
                        else if (headerName == "Classification") {
                            headerName = "Classification";
                        }
                        else if (headerName == "Goods") {
                            headerName = "Goods";
                        }
                        else if (headerName == "Services") {
                            headerName = "Services";
                        }
                        else if (headerName == "Status") {
                            headerName = "Status";
                        }

                        row += headerName + ',';
                    }
                    if (typeof Data === 'string') {
                        if (Data) {
                            if (Data.indexOf(',') != -1) {
                                Data = '"' + Data + '"';
                            }
                        }
                        //Data = Data.replace(/,/g, " ")
                    }

                    else {
                        if (!Data) {
                            Data = '';
                        }
                        else {
                            Data = Data;
                        }

                    }
                    if (headerName == 'Email' || headerName == 'Email') {
                        rowData = rowData + Data;
                    }
                    else {
                        rowData += Data + ",";
                    }


                }

            });

            if (index == 0) {
                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }
            rowData.slice(0, rowData.length - 1);

            //add a line break after each row
            CSV += rowData + '\r\n';
        });

        row = ""; csv = ""; rowData = "";

        //Generate a file name
        var fileName = "TrademarkSearchList";


        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        if (navigator.msSaveBlob) {
            var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
            navigator.msSaveBlob(blob, "fileName.csv")

        } else {
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        //}
    }

});
wacorpApp.controller('trademarkInformationController', function ($scope, wacorpService, focus, $rootScope, $cookieStore, $timeout, $routeParams, $location, $filter) {
    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.TrademarkInfo = [];
    $scope.trademarkinfosearch = {};
    $scope.init = function () {
        $scope.trademarkinfosearch = $rootScope.data;
        var RegNo = $rootScope.data.RegistrationNumber;
        $scope.getTrademarkDetails(RegNo); // getTrademarkDetails method is available in this controller only.
    }

    $scope.getTrademarkDetails = function (value) {
        if (value && value != "")
        {
            var url;
            var registrationNo = "";
            var config = { params: { registrationNo: value } };
            
            if ($rootScope.isTrademarkPublicSearch) {
                url = webservices.BusinessSearch.getTrademarkInfoDetails // getTrademarkInfoDetails method is available in constants.js
            }
            else if ($rootScope.isTrademarkHomeAdvancedSearch)
            {
                url = webservices.BusinessSearch.getTrademarkInfoDetails // getTrademarkInfoDetails method is available in constants.js
            }
            else {
                //url = webservices.TraseMarkSearch.getTrademarkInfoDetails; // getTrademarkInfoDetails method is available in constants.js// !!!***** Spelling corrected 10/21/2019, KK

                url = webservices.TradeMarkSearch.getTrademarkInfoDetails; // getTrademarkInfoDetails method is available in constants.js
            }
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.get(url, config, function (response) {
                $scope.TrademarkInfo = response.data;
                $scope.TrademarkInfo.TrademarkOwnerInformation.TypeID = $scope.TrademarkInfo.TrademarkOwnerInformation.TypeID != null ? $scope.TrademarkInfo.TrademarkOwnerInformation.TypeID.trim() : '';
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
                // Folder Name: controller
                // Controller Name: rootController.js (you can search with file name in solution explorer)
                searchResultsLoading(false);
            });
        }
    }

    // functions
    function searchResultsLoading(flag) {
        if (flag == true)
            $scope.loadingText = "Processing ...";
        else
            $scope.loadingText = "Search";
    }

    //to get documents for trade mark
    $scope.getTransactionDocumentsList = function (filingNo,id) {
        var criteria = { FilingNumber: filingNo, ID: id, IsInhouse: false };
        if ($rootScope.isTrademarkPublicSearch) {
            url = webservices.BusinessSearch.getTrademarkDocuments // getTrademarkDocuments method is available in constants.js
        }
        else if ($rootScope.isTrademarkHomeAdvancedSearch) {
            url = webservices.BusinessSearch.getTrademarkDocuments // getTrademarkDocuments method is available in constants.js
        }
        else {
            //url = webservices.TraseMarkSearch.getTrademarkDocuments; // getTrademarkDocuments method is available in constants.js // !!!***** Spelling corrected 10/21/2019, KK

            url = webservices.TradeMarkSearch.getTrademarkDocuments; // getTrademarkDocuments method is available in constants.js
        }
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.post(url, criteria, function (response) {
            $scope.transactionDocumentsList = response.data;
            $('#divTradeSearchResult').show();
            $('#divTradeSearchResult').modal('toggle')
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });

    };

    $scope.back = function () {
        //Ticket -- 3167
        $rootScope.isTrademarkBackButtonPressed = true;
        if ($rootScope.isAdvanceSearch == true) {
            $scope.criteria = $cookieStore.get('trademarkAdvancedSearchCriteria');
            $rootScope.isTrademarkAdvancedBackSearch = true;
            $cookieStore.put('trademarkAdvancedSearchCriteria', $scope.criteria);
            if ($rootScope.isTrademarkPublicSearch) {
                $location.path("/trademarkDetails");
            }
            else if ($rootScope.isTrademarkHomeAdvancedSearch) {
                $location.path("/trademarkHomeAdvancedSearch");
            }
            else {
                $location.path("/trademarkAdvancedSearch");
            }
        }
        else {
        $scope.criteria = $cookieStore.get('trademarkSearchCriteria');
        $rootScope.isTradeBackSearch = true;
        $cookieStore.put('trademarkSearchCriteria', $scope.criteria);
        if ($rootScope.isTrademarkPublicSearch) {
            $location.path("/trademarkDetails");
        }
            else if ($rootScope.isTrademarkHomeAdvancedSearch) {
                $location.path("/trademarkHomeAdvancedSearch");
            }
            else {
                $location.path("/trademarkSearch");
            }
        }
    };

    $scope.returnToSearch = function () {
        $rootScope.data = null;
        if ($rootScope.isAdvanceSearch == true) {
            $cookieStore.remove('trademarkAdvancedSearchCriteria');
            if ($rootScope.isTrademarkPublicSearch) {
                $location.path("/Home");
            }
            else if ($rootScope.isTrademarkHomeAdvancedSearch) {
                $location.path("/trademarkHomeAdvancedSearch");
            }
            else {
                $location.path("/trademarkAdvancedSearch");
            }
        }
        else {
            $cookieStore.remove('trademarkSearchCriteria');
            if ($rootScope.isTrademarkPublicSearch) {
                $location.path("/Home");
            }
            else if ($rootScope.isTrademarkHomeAdvancedSearch) {
                $location.path("/trademarkHomeAdvancedSearch");
            }
        else {
            $location.path("/trademarkSearch");
        }
        }
    };

    //$scope.propertyName = 'FilingDate';
    //$scope.reverse = true;

    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };

});
wacorpApp.controller('trademarkAdvancedSearchController', function ($scope, wacorpService, focus, $rootScope, $cookieStore, $timeout, $routeParams, $location) {

    // variable initialization
    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.trademarkSearch = {};
    $scope.isButtonSerach = false;
    $rootScope.isAdvanceSearch = true;
    $scope.cftOrganizationSearchType = false;
    $scope.IsType = false;
    $scope.TradeMarkList = [];
    $rootScope.isTrademarkPublicSearch = false;
    $scope.criteria = {
        Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, IsSearch: true, SearchValue: "", SearchCriteria: "", TrademarkRegistrationNo: null, SortType: null, SortBy: null,
        TrademarkText: "", TrademarkOwnerName: "", UBINumber: "", Status: "", StartDateOfIncorporation: null, EndDateOfIncorporation: null, ExpirationDate: null,
        TrademarkGoodsID: "", TrademarkServicesID: "", Export: 0, SearchType: ""

    };
    $scope.trademarkSearch = {
        Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, isCftOrganizationSearchBack: false,
        TrademarkText: "", TrademarkOwnerName: "", TrademarkRegistrationNo: null, UBINumber: null, Contains: searchTypes.Contains, isSearchClick: false, SortType: null, SortBy: null,
        SearchCriteria: "", Selectiontype: searchTypes.Contains, Status: "", StartDateOfIncorporation: null, EndDateOfIncorporation: null, ExpirationDate: null,
        TrademarkGoodsID: null, TrademarkServicesID: null, Export: 0, SearchType: ""
    };

    var settingScope = { scrollableHeight: '200px', scrollable: true, key: "Value", value: "Key", isKeyList: false, selectall: true };
    $scope.dropdownsettings = $scope.dropdownsettings ? angular.extend(settingScope, $scope.dropdownsettings) : angular.copy(settingScope);

    $scope.TrademarkStatus = function () {
        var config = { params: { name: 'TrademarkStatus' } };
        // getLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.TrademarkStatus = response.data; });
    };

    $scope.TrademarkGoods = function () {
        var config = { params: { name: 'Goods' } };
        // getLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.TrademarkGoods = response.data; });
    };

    $scope.TrademarkServices = function () {
        var config = { params: { name: 'Services' } };
        // getLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.TrademarkServices = response.data; });
    };

    $scope.initTradeSearch = function () {
        $scope.TrademarkStatus(); // TrademarkStatus method is available in this controller only.
        $scope.TrademarkGoods(); // TrademarkGoods method is available in this controller only.
        $scope.TrademarkServices(); // TrademarkServices method is available in this controller only.

        if ($rootScope.data && $rootScope.data != "") {
            $scope.trademarkSearch = $cookieStore.get('trademarkAdvancedSearchCriteria');
            $scope.trademarkSearch.isSearchClick = true;
            $rootScope.data = null;
            loadTradeList(constant.ZERO); // loadTradeList method is available in this controller only.
        }
    };

    $scope.clearFun = function () {
        $scope.trademarkSearch.TrademarkRegistrationNo = null;
        $scope.trademarkSearch.TrademarkOwnerName = null;
        $scope.trademarkSearch.TrademarkText = null;
        $scope.trademarkSearch.UBINumber = null;
        $scope.trademarkSearch.isSearchClick = false;
        $scope.IsType = false;
        $scope.criteria.SortBy = null;
        $scope.criteria.SortType = null;

        $scope.trademarkSearch.Status = "";
        $scope.trademarkSearch.StartDateOfIncorporation = null;
        $scope.trademarkSearch.EndDateOfIncorporation = null;
        $scope.trademarkSearch.ExpirationDate = null;
        $('#ddlSelection').val(1);
        $scope.trademarkSearch.TrademarkGoodsID = [];
        $scope.trademarkSearch.TrademarkServicesID = [];
        $('.myChkbox').prop('checked', false);
    };

    $scope.setPastedTradeNum = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.TrademarkRegistrationNo = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.TrademarkRegistrationNo = pastedText;
            });
        }
    };


    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.UBINumber = pastedText;
            });
        }
    };

    $scope.searchTrade = function (Trademarksearchform) {
        $scope.isShowErrorFlag = true;
        if ($scope[Trademarksearchform].$valid) {
            $scope.isShowErrorFlag = false;
            $scope.isButtonSerach = true
            $scope.trademarkSearch.isSearchClick = true;
            $rootScope.isTrademarkAdvancedBackSearch = false;
            loadTradeList(constant.ZERO); // loadTradeList method is available in this controller only.
        }
    };

    $scope.searchTradePagination = function (Trademarksearchform, sortBy) {
        $scope.isButtonSerach = true
        $scope.trademarkSearch.isSearchClick = true;
        loadTradeList(Trademarksearchform, sortBy); // loadTradeList method is available in this controller only.
    };


    //to get Trademark serach result list.
    function loadTradeList(page, sortBy) {
        //Ticket -- 3167
        $rootScope.isTrademarkBackButtonPressed = false;
        page = page || constant.ZERO;
        $scope.trademarkSearch.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;

        if ($rootScope.isTrademarkAdvancedBackSearch == true) {
            $scope.criteria = $scope.trademarkSearch;
            if ($scope.criteria.TrademarkGoodsID.length > 0)
                $scope.criteria.TrademarkGoodsID = $scope.criteria.TrademarkGoodsID.toString() != "" ? $scope.criteria.TrademarkGoodsID.toString() : "";
            else
                $scope.criteria.TrademarkGoodsID = null;
            if ($scope.criteria.TrademarkServicesID.length > 0)
                $scope.criteria.TrademarkServicesID = $scope.criteria.TrademarkServicesID.toString() != "" ? $scope.criteria.TrademarkServicesID.toString() : "";
            else
                $scope.criteria.TrademarkServicesID = null;
        }
        else {
            $scope.trademarkSearch.SearchType = $('#ddlSelection option:selected').text();

            $scope.criteria.TrademarkText = $scope.trademarkSearch.TrademarkText;
            $scope.criteria.TrademarkOwnerName = $scope.trademarkSearch.TrademarkOwnerName;
            $scope.criteria.TrademarkRegistrationNo = $scope.trademarkSearch.TrademarkRegistrationNo;
            $scope.criteria.UBINumber = $scope.trademarkSearch.UBINumber;
            $scope.criteria.Status = $scope.trademarkSearch.Status;
            $scope.criteria.StartDateOfIncorporation = $scope.trademarkSearch.StartDateOfIncorporation;
            $scope.criteria.EndDateOfIncorporation = $scope.trademarkSearch.EndDateOfIncorporation;
            $scope.criteria.ExpirationDate = $scope.trademarkSearch.ExpirationDate;
            $scope.criteria.TrademarkGoodsID = $scope.trademarkSearch.TrademarkGoodsID.toString() != "" ? $scope.trademarkSearch.TrademarkGoodsID.toString() : $scope.trademarkSearch.TrademarkGoodsID = [];
            $scope.criteria.TrademarkServicesID = $scope.trademarkSearch.TrademarkServicesID.toString() != "" ? $scope.trademarkSearch.TrademarkServicesID.toString() : $scope.trademarkSearch.TrademarkServicesID = [];
            $scope.criteria.Export = 0;
            $scope.criteria.SearchType = $scope.trademarkSearch.SearchType;
        }

        $scope.criteria.PageID = $scope.trademarkSearch.PageID;
        if (sortBy != undefined) {
            if ($scope.criteria.SortBy == sortBy) {
                if ($scope.criteria.SortType == 'ASC') {
                    $scope.criteria.SortType = 'DESC';
                }
                else {
                    $scope.criteria.SortType = 'ASC';
                }
            }
            else {
                $scope.criteria.SortBy = sortBy;
                $scope.criteria.SortType = 'ASC';
            }
        }
        else {
            if ($scope.criteria.SortBy == undefined || $scope.criteria.SortBy == "" || $scope.criteria.SortBy == null) {
                $scope.criteria.SortBy = 'Trademark Text';
                $scope.criteria.SortType = 'ASC';
            }
            else {

                if ($scope.validateData($scope.criteria.SortBy) && $scope.validateData($scope.criteria.SortType)) {
                    $scope.criteria.SortBy = $scope.criteria.SortBy;
                    $scope.criteria.SortType = $scope.criteria.SortType;
                }
            }
        }
        var data = angular.copy($scope.criteria);
        $scope.isButtonSerach = page == 0;
        // getTrademarkAdvancedSearchDetails method is available in constants.js
        //wacorpService.post(webservices.TraseMarkSearch.getTrademarkAdvancedSearchDetails, data, function (response) { !!!***** Spelling corrected 10/21/2019, KK

        wacorpService.post(webservices.TradeMarkSearch.getTrademarkAdvancedSearchDetails, data, function (response) {
            $scope.TradeMarkList = response.data;

            $cookieStore.put('trademarkAdvancedSearchCriteria', $scope.trademarkSearch);
            if ($scope.isButtonSerach && response.data.length > 0) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                $scope.pagesCount = response.data.length < $scope.trademarkSearch.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                $scope.totalCount = totalcount;
                //$scope.searchval = criteria.SearchValue;
                criteria = response.data[constant.ZERO].Criteria;
            } else if (response.data.length == 0) {
                $scope.pagesCount = 0;
                $scope.totalCount = 0;
            }


            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus("tblTrademarkSearch");
        }, function (response) {
            $scope.selectedEntity = null;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    //to get trademark details
    $scope.searchTrademark = function (value) {
        //Ticket -- 3167
        $rootScope.isTrademarkBackButtonPressed = false;
        if (value != null && value != undefined) {
            $scope.criteria.RegistrationNumber = value;
            $rootScope.data = $scope.criteria;
            $location.path('/trademarkInformation')
        }
    }

    $scope.exportCSVServer = function () {

        var criteria = null;
        var searchinfo = angular.copy($scope.criteria);
        searchinfo.PageID = 1;
        searchinfo.PageCount = 9999999;
        searchinfo.Export = 1;
        // getTrademarkAdvancedSearchDetails method is available in constants.js
        //wacorpService.post(webservices.TraseMarkSearch.getTrademarkAdvancedSearchDetails, searchinfo, function (response) { !!!***** Spelling corrected 10/21/2019, KK

        wacorpService.post(webservices.TradeMarkSearch.getTrademarkAdvancedSearchDetails, searchinfo, function (response) {
            var result = [];

            result = response.data;
            $rootScope.exportToCSV(result)

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);

        });

    }


    $scope.validateData = function (data) {
        if (data != undefined && data != null && data != "")
            return true;
        else
            return false;
    }

    //Export Data to CSV
    $rootScope.exportToCSV = function (exportData) {

        var arrData = typeof exportData != 'object' ? JSON.parse(exportData) : exportData;

        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
        });

        var CSV = '';
        var row = "";

        var rowData = "";
        //Preparing Candidate Data
        var arrData1 = [];
        candidateColumns = ["Registration #", "Trademark Text", "Registration/Reservation Date", "Expiration Date", "Classification", "Goods", "Services", "Status"];
        $.each(arrData, function (index, element) {

            arrData1.push({
                "Registration #": element.TrademarkRegistrationNo, "Trademark Text": element.TrademarkText, "Registration/Reservation Date": element.RegistrationDate.split('T')[0], "Expiration Date": element.ExpirationDate.split('T')[0],
                "Classification": element.TrademarkClassification, "Goods": element.TrademarkGoods, "Services": element.TrademarkServices, "Status": element.TrademarkStatus,
            })
        });
        $.each(arrData1, function (index, Data) {

            rowData = "";
            $.each(Data, function (headerName, Data) {
                if (candidateColumns.indexOf(headerName) != -1) {
                    if (index == 0) {
                        if (headerName == "Registration #") {
                            headerName = "Registration #";
                        }
                        else if (headerName == "Trademark Text") {
                            headerName = "Trademark Text";
                        }
                        else if (headerName == "Registration/Reservation Date") {
                            headerName = "Registration/Reservation Date";
                        }
                        else if (headerName == "Expiration Date") {
                            headerName = "Expiration Date";
                        }
                        else if (headerName == "Classification") {
                            headerName = "Classification";
                        }
                        else if (headerName == "Goods") {
                            headerName = "Goods";
                        }
                        else if (headerName == "Services") {
                            headerName = "Services";
                        }
                        else if (headerName == "Status") {
                            headerName = "Status";
                        }

                        row += headerName + ',';
                    }
                    if (typeof Data === 'string') {
                        if (Data) {
                            if (Data.indexOf(',') != -1) {
                                Data = '"' + Data + '"';
                            }
                        }
                        //Data = Data.replace(/,/g, " ")
                    }

                    else {
                        if (!Data) {
                            Data = '';
                        }
                        else {
                            Data = Data;
                        }

                    }
                    if (headerName == 'Email' || headerName == 'Email') {
                        rowData = rowData + Data;
                    }
                    else {
                        rowData += Data + ",";
                    }


                }

            });

            if (index == 0) {
                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }
            rowData.slice(0, rowData.length - 1);

            //add a line break after each row
            CSV += rowData + '\r\n';
        });

        row = ""; csv = ""; rowData = "";

        //Generate a file name
        var fileName = "TrademarkSearchList";


        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        if (navigator.msSaveBlob) {
            var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
            navigator.msSaveBlob(blob, "fileName.csv")

        } else {
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        //}
    }

});
wacorpApp.controller('trademarkHomeAdvancedSearchController', function ($scope, wacorpService, focus, $rootScope, $cookieStore, $timeout, $routeParams, $location) {

    // variable initialization
    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.trademarkSearch = {};
    $scope.isButtonSerach = false;
    $rootScope.isAdvanceSearch = true;
    $scope.cftOrganizationSearchType = false;
    $scope.IsType = false;
    $scope.TradeMarkList = [];
    $rootScope.isTrademarkPublicSearch = false;
    $scope.criteria = {
        Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, IsSearch: true, SearchValue: "", SearchCriteria: "", TrademarkRegistrationNo: null, SortType: null, SortBy: null,
        TrademarkText: "", TrademarkOwnerName: "", UBINumber: "", Status: "", StartDateOfIncorporation: null, EndDateOfIncorporation: null, ExpirationDate: null,
        TrademarkGoodsID: "", TrademarkServicesID: "", Export: 0, SearchType: ""

    };
    $scope.trademarkSearch = {
        Type: "", PageID: constant.ONE, PageCount: constant.TWENTYFIVE, isCftOrganizationSearchBack: false,
        TrademarkText: "", TrademarkOwnerName: "", TrademarkRegistrationNo: null, UBINumber: null, Contains: searchTypes.Contains, isSearchClick: false, SortType: null, SortBy: null,
        SearchCriteria: "", Selectiontype: searchTypes.Contains, Status: "", StartDateOfIncorporation: null, EndDateOfIncorporation: null, ExpirationDate: null,
        TrademarkGoodsID: null, TrademarkServicesID: null, Export: 0, SearchType: ""
    };

    var settingScope = { scrollableHeight: '200px', scrollable: true, key: "Value", value: "Key", isKeyList: false, selectall: true };
    $scope.dropdownsettings = $scope.dropdownsettings ? angular.extend(settingScope, $scope.dropdownsettings) : angular.copy(settingScope);

    $scope.TrademarkStatus = function () {
        var config = { params: { name: 'TrademarkStatus' } };
        // getLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.TrademarkStatus = response.data; });
    };

    $scope.TrademarkGoods = function () {
        var config = { params: { name: 'Goods' } };
        // getLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.TrademarkGoods = response.data; });
    };

    $scope.TrademarkServices = function () {
        var config = { params: { name: 'Services' } };
        // getLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.TrademarkServices = response.data; });
    };

    $scope.initTradeSearch = function () {
        $scope.TrademarkStatus(); // TrademarkStatus method is available in this controller only.
        $scope.TrademarkGoods(); // TrademarkGoods method is available in this controller only.
        $scope.TrademarkServices(); // TrademarkServices method is available in this controller only.
        $('#ddlSelection').val(1);
        if ($rootScope.data && $rootScope.data != "") {
            $scope.trademarkSearch = $cookieStore.get('trademarkAdvancedSearchCriteria');
            $('#ddlSelection').val($scope.trademarkSearch.SearchType == "Contains" ? 1 : $scope.trademarkSearch.SearchType == "Exact Match" ? 2 : 3);
            //$('#ddlSelection').val($scope.trademarkSearch.SearchType).attr('selected','selected');
            $scope.trademarkSearch.isSearchClick = true;
            $rootScope.data = null;
            loadTradeList(constant.ZERO); // loadTradeList method is available in this controller only.
        }
    };

    $scope.clearFun = function () {
        $scope.trademarkSearch.TrademarkRegistrationNo = null;
        $scope.trademarkSearch.TrademarkOwnerName = null;
        $scope.trademarkSearch.TrademarkText = null;
        $scope.trademarkSearch.UBINumber = null;
        $scope.trademarkSearch.isSearchClick = false;
        $scope.IsType = false;
        $scope.criteria.SortBy = null;
        $scope.criteria.SortType = null;

        $scope.trademarkSearch.Status = "";
        $scope.trademarkSearch.StartDateOfIncorporation = null;
        $scope.trademarkSearch.EndDateOfIncorporation = null;
        $scope.trademarkSearch.ExpirationDate = null;
        $('#ddlSelection').val(1);
        $scope.trademarkSearch.TrademarkGoodsID = [];
        $scope.trademarkSearch.TrademarkServicesID = [];
        $('.myChkbox').prop('checked', false);
    };

    $scope.setPastedTradeNum = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.TrademarkRegistrationNo = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.TrademarkRegistrationNo = pastedText;
            });
        }
    };


    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.trademarkSearch.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.trademarkSearch.UBINumber = pastedText;
            });
        }
    };

    $scope.searchTrade = function (Trademarksearchform) {
        $scope.isShowErrorFlag = true;
        if ($scope[Trademarksearchform].$valid) {
            $scope.isShowErrorFlag = false;
            $scope.isButtonSerach = true
            $scope.trademarkSearch.isSearchClick = true;
            $rootScope.isTrademarkAdvancedBackSearch = false;
            loadTradeList(constant.ZERO); // loadTradeList method is available in this controller only.
        }
    };

    $scope.searchTradePagination = function (Trademarksearchform, sortBy) {
        $scope.isButtonSerach = true
        $scope.trademarkSearch.isSearchClick = true;
        loadTradeList(Trademarksearchform, sortBy); // loadTradeList method is available in this controller only.
    };


    //to get Trademark serach result list.
    function loadTradeList(page, sortBy) {

        page = page || constant.ZERO;
        $scope.trademarkSearch.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;

        if ($rootScope.isTrademarkAdvancedBackSearch == true) {
            $scope.criteria = $scope.trademarkSearch;

            //$scope.criteria.TrademarkGoodsID = $scope.criteria.TrademarkGoodsID.toString();
            if ($scope.trademarkSearch.TrademarkGoodsID.length > 0)
                $scope.criteria.TrademarkGoodsID = $scope.trademarkSearch.TrademarkGoodsID.toString() != "" ? $scope.trademarkSearch.TrademarkGoodsID.toString() : "";
            else
                $scope.criteria.TrademarkGoodsID = "";
            //$scope.criteria.TrademarkServicesID = $scope.criteria.TrademarkServicesID.toString();
            if ($scope.trademarkSearch.TrademarkServicesID.length > 0)
                $scope.criteria.TrademarkServicesID = $scope.trademarkSearch.TrademarkServicesID.toString() != "" ? $scope.trademarkSearch.TrademarkServicesID.toString() : "";
            else
                $scope.criteria.TrademarkServicesID = "";
        }
        else {
            $scope.trademarkSearch.SearchType = $('#ddlSelection option:selected').text();

            $scope.criteria.TrademarkText = $scope.trademarkSearch.TrademarkText;
            $scope.criteria.TrademarkOwnerName = $scope.trademarkSearch.TrademarkOwnerName;
            $scope.criteria.TrademarkRegistrationNo = $scope.trademarkSearch.TrademarkRegistrationNo;
            $scope.criteria.UBINumber = $scope.trademarkSearch.UBINumber;
            $scope.criteria.Status = $scope.trademarkSearch.Status;
            $scope.criteria.StartDateOfIncorporation = $scope.trademarkSearch.StartDateOfIncorporation;
            $scope.criteria.EndDateOfIncorporation = $scope.trademarkSearch.EndDateOfIncorporation;
            $scope.criteria.ExpirationDate = $scope.trademarkSearch.ExpirationDate;
            $scope.criteria.TrademarkGoodsID = $scope.trademarkSearch.TrademarkGoodsID.toString() != "" ? $scope.trademarkSearch.TrademarkGoodsID.toString() : $scope.trademarkSearch.TrademarkGoodsID = [];
            $scope.criteria.TrademarkServicesID = $scope.trademarkSearch.TrademarkServicesID.toString() != "" ? $scope.trademarkSearch.TrademarkServicesID.toString() : $scope.trademarkSearch.TrademarkServicesID = [];
            $scope.criteria.Export = 0;
            $scope.criteria.SearchType = $scope.trademarkSearch.SearchType;
        }

        $scope.criteria.PageID = $scope.trademarkSearch.PageID;
        if (sortBy != undefined) {
            if ($scope.criteria.SortBy == sortBy) {
                if ($scope.criteria.SortType == 'ASC') {
                    $scope.criteria.SortType = 'DESC';
                }
                else {
                    $scope.criteria.SortType = 'ASC';
                }
            }
            else {
                $scope.criteria.SortBy = sortBy;
                $scope.criteria.SortType = 'ASC';
            }
        }
        else {
            if ($scope.criteria.SortBy == undefined || $scope.criteria.SortBy == "" || $scope.criteria.SortBy == null) {
                $scope.criteria.SortBy = 'Trademark Text';
                $scope.criteria.SortType = 'ASC';
            }
            else if ($scope.validateData($scope.criteria.SortBy) && $scope.validateData($scope.criteria.SortType)) {
                $scope.criteria.SortBy = $scope.criteria.SortBy;
                $scope.criteria.SortType = $scope.criteria.SortType;
            }
        }
        var data = angular.copy($scope.criteria);
        $scope.isButtonSerach = page == 0;
        // getTrademarkAdvancedSearchDetails method is available in constants.js
        //wacorpService.post(webservices.TraseMarkSearch.getTrademarkAdvancedSearchDetails, data, function (response) { !!!***** Spelling corrected 10/21/2019, KK

        wacorpService.post(webservices.TradeMarkSearch.getTrademarkAdvancedSearchDetails, data, function (response) {
            $scope.TradeMarkList = response.data;

            $cookieStore.put('trademarkAdvancedSearchCriteria', $scope.trademarkSearch);
            if ($scope.isButtonSerach && response.data.length > 0) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                $scope.pagesCount = response.data.length < $scope.trademarkSearch.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                $scope.totalCount = totalcount;
                //$scope.searchval = criteria.SearchValue;
                criteria = response.data[constant.ZERO].Criteria;
            } else if (response.data.length == 0) {
                $scope.pagesCount = 0;
                $scope.totalCount = 0;
            }


            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus("tblTrademarkSearch");
        }, function (response) {
            $scope.selectedEntity = null;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    //to get trademark details
    $scope.searchTrademark = function (value) {
        if (value != null && value != undefined) {
            $rootScope.isTrademarkHomeAdvancedSearch = true;
            $scope.criteria.RegistrationNumber = value;
            $rootScope.data = $scope.criteria;
            $location.path('/trademarkInformation')
        }
    }

    $scope.exportCSVServer = function () {

        var criteria = null;
        var searchinfo = angular.copy($scope.criteria);
        searchinfo.PageID = 1;
        searchinfo.PageCount = 9999999;
        searchinfo.Export = 1;
        // getTrademarkAdvancedSearchDetails method is available in constants.js
        //wacorpService.post(webservices.TraseMarkSearch.getTrademarkAdvancedSearchDetails, searchinfo, function (response) { !!!***** Spelling corrected 10/21/2019, KK

        wacorpService.post(webservices.TradeMarkSearch.getTrademarkAdvancedSearchDetails, searchinfo, function (response) {
            var result = [];

            result = response.data;
            $rootScope.exportToCSV(result)

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);

        });

    }


    $scope.validateData = function (data) {
        if (data != undefined && data != null && data != "")
            return true;
        else
            return false;
    }

    //Export Data to CSV
    $rootScope.exportToCSV = function (exportData) {

        var arrData = typeof exportData != 'object' ? JSON.parse(exportData) : exportData;

        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
        });

        var CSV = '';
        var row = "";

        var rowData = "";
        //Preparing Candidate Data
        var arrData1 = [];
        candidateColumns = ["Registration #", "Trademark Text", "Registration/Reservation Date", "Expiration Date", "Classification", "Goods", "Services", "Status"];
        $.each(arrData, function (index, element) {

            arrData1.push({
                "Registration #": element.TrademarkRegistrationNo, "Trademark Text": element.TrademarkText, "Registration/Reservation Date": element.RegistrationDate.split('T')[0], "Expiration Date": element.ExpirationDate.split('T')[0],
                "Classification": element.TrademarkClassification, "Goods": element.TrademarkGoods, "Services": element.TrademarkServices, "Status": element.TrademarkStatus,
            })
        });
        $.each(arrData1, function (index, Data) {

            rowData = "";
            $.each(Data, function (headerName, Data) {
                if (candidateColumns.indexOf(headerName) != -1) {
                    if (index == 0) {
                        if (headerName == "Registration #") {
                            headerName = "Registration #";
                        }
                        else if (headerName == "Trademark Text") {
                            headerName = "Trademark Text";
                        }
                        else if (headerName == "Registration/Reservation Date") {
                            headerName = "Registration/Reservation Date";
                        }
                        else if (headerName == "Expiration Date") {
                            headerName = "Expiration Date";
                        }
                        else if (headerName == "Classification") {
                            headerName = "Classification";
                        }
                        else if (headerName == "Goods") {
                            headerName = "Goods";
                        }
                        else if (headerName == "Services") {
                            headerName = "Services";
                        }
                        else if (headerName == "Status") {
                            headerName = "Status";
                        }

                        row += headerName + ',';
                    }
                    if (typeof Data === 'string') {
                        if (Data) {
                            if (Data.indexOf(',') != -1) {
                                Data = '"' + Data + '"';
                            }
                        }
                        //Data = Data.replace(/,/g, " ")
                    }

                    else {
                        if (!Data) {
                            Data = '';
                        }
                        else {
                            Data = Data;
                        }

                    }
                    if (headerName == 'Email' || headerName == 'Email') {
                        rowData = rowData + Data;
                    }
                    else {
                        rowData += Data + ",";
                    }


                }

            });

            if (index == 0) {
                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }
            rowData.slice(0, rowData.length - 1);

            //add a line break after each row
            CSV += rowData + '\r\n';
        });

        row = ""; csv = ""; rowData = "";

        //Generate a file name
        var fileName = "TrademarkSearchList";


        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        if (navigator.msSaveBlob) {
            var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
            navigator.msSaveBlob(blob, "fileName.csv")

        } else {
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        //}
    }

});
wacorpApp.controller('annualReportController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if (["Active", "Delinquent", "Administratively Dissolved", "Terminated"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            var data = { params: { businessId: $scope.selectedBusiness.BusinessID, filingTypeName: "Annual Report", isOnline: true } };
            // ValidateBusinessStatus method is available in constants.js
            wacorpService.get(webservices.Common.ValidateBusinessStatus, data, function (response) {
                var result = response.data;
                if (result.Key != 0) {
                    if (result.Key == BusinessStatus.AdministrativelyDissolved) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.confirmDialog(result.Value, function () {
                            $rootScope.reinstatementModal = null;
                            $rootScope.transactionID = null;
                            $rootScope.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit;  //passing Gross Revenue Value on redirect
                            $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);
                        });
                    }
                        // key 4 for second message for AR
                    else if (result.Key == BusinessStatus.AdministrativelyTerminated) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    }
                    else
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    return;
                }
                else {
                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                    $rootScope.annualReportModal = null;
                    $rootScope.transactionID = null;

                    $location.path('/AnnualReport/' + $scope.selectedBusiness.BusinessID);
                }
            }, function (response) {
                // Folder Name: app Folder
                // Alert Name: serverError method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.serverError);
            });
        }
        else {
            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.AnnualReport.ActiveAndDelinquentStatus);
        }
    }

    /* --------Annual Report Functionality------------- */
    // scope variable
    $scope.modal = {};
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    $scope.nobSelectedItems = [];
    $scope.validateErrors = false;
    $scope.validateAgentErrors = false;
    $scope.principalsCount = 0;
    $scope.amendprincipalsCount = 0;
    $scope.isShowContinue = true;
    $scope.isShowFeeList = false;
    $scope.feeListLayout = PartialViews.FilingFeeListView;
    $scope.feeDetailsDescription = "Annual Report Fee Details";

    function canShowFeeList() {
        if (!angular.isDefined($scope.modal.FeeList))
            return false;
        else if (angular.isNullorEmpty($scope.modal.FeeList))
            return false;
        return $scope.modal.FeeList.length > 0;
    }

    // scope load 
    $scope.Init = function () {
        $scope.messages = messages;
        getNaicsCodes(); // getNaicsCodes method is available in this controller only.
        getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in this controller only.
        // get business details
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.annualReportModal = $rootScope.modal;
            //$rootScope.modal = null;
            $scope.IsGrossRevenueNonProfit = $rootScope.annualReportModal.IsGrossRevenueNonProfit;//TFS 2628 Getting value from saved Json
        } else {
            $scope.IsGrossRevenueNonProfit = $rootScope.IsGrossRevenueNonProfit;//TFS 2628 getting value from business Search (index)
        }

        var data = null;
        if ($rootScope.transactionID > 0)
            // Here filingTypeID : 2 is ADM DISSOLUTION/TERMINIATION.
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 2 } };
        else
            data = { params: { businessID: $routeParams.id, transactionID: $rootScope.transactionID, filingTypeID: 2 } };
        if ($rootScope.annualReportModal == null || $rootScope.annualReportModal == undefined 
            || $scope.IsGrossRevenueNonProfit == null || $scope.IsGrossRevenueNonProfit == undefined) {  //TFS 2626
            // AnnualReportCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.AnnualReportCriteria, data, function (response) {
                $scope.modal = response.data;
                if (!angular.isNullorEmpty($scope.modal.BusinessName)) {
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.EffectiveDateType = $scope.modal.EffectiveDate == null ? 'DateOfFiling' : $scope.modal.EffectiveDateType;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertStringToObject($scope.modal.NatureOfBusinessEntity.NAICSCode);
                    $scope.modal.NatureOfBusinessEntity.IsOtherNAICS = !angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.OtherDescription) ? true : false;
                    $scope.modal.NatureOfBusinessEntity.BusinessID = $scope.modal.BusinessID;
                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;
                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;

                    //$scope.modal.BINAICSCodeDesc=!angular.isNullorEmpty($scope.modal.BINAICSCodeDesc)?$scope.modal.BINAICSCodeDesc.replace(/&amp;/g, '&'):"";
                    //$scope.modal.BINAICSCodeDesc = !angular.isNullorEmpty($scope.modal.BIOtherDescription)?$scope.modal.BINAICSCodeDesc+','+$scope.modal.BIOtherDescription:$scope.modal.BINAICSCodeDesc;
                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js (you can search with file name in solution explorer)
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                    $scope.isShowReturnAddress = true;

                    $scope.modal.FEINNo = $scope.modal.FEINNo != null ? $scope.modal.FEINNo : $scope.FEINNo;

                    // TFS#2329/13.7; 
                    $scope.modal.IsCanBePublicBenefitNonProfit = $scope.modal.IsCanBePublicBenefitNonProfit != null ? $scope.modal.IsCanBePublicBenefitNonProfit : $scope.IsCanBePublicBenefitNonProfit;
                    $scope.modal.IsPublicBenefitNonProfit = $scope.modal.IsPublicBenefitNonProfit != null ? $scope.modal.IsPublicBenefitNonProfit : $scope.IsPublicBenefitNonProfit;

                    //TFS 2628
                    $scope.modal.IsCharitableNonProfit = $scope.modal.IsCharitableNonProfit != undefined ? $scope.modal.IsCharitableNonProfit : $scope.IsCharitableNonProfit
                    $scope.modal.IsNonProfitExempt = $scope.modal.IsNonProfitExempt != undefined ? $scope.modal.IsNonProfitExempt : $scope.IsNonProfitExempt;
                    $scope.modal.NonProfitReporting1 = $scope.modal.NonProfitReporting1 != undefined ? $scope.modal.NonProfitReporting1 : $scope.NonProfitReporting1;
                    $scope.modal.NonProfitReporting2 = $scope.modal.NonProfitReporting2 != undefined ? $scope.modal.NonProfitReporting2 : $scope.NonProfitReporting2;
                    $scope.modal.BusinessType = $scope.modal.BusinessType != undefined ? $scope.modal.BusinessType : $scope.BusinessType;

                    //TFS 2626
                    if ($scope.modal.IsGrossRevenueNonProfit != null || $scope.modal.IsGrossRevenueNonProfit != undefined) {
                        $scope.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit;
                        $rootScope.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit;
                    } else {
                        $scope.modal.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit;
                    };
                    if ($scope.modal.IsGrossRevenueNonProfit != null || $scope.modal.IsGrossRevenueNonProfit != undefined) {
                        $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit;
                    } else {
                        $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit;
                    }
                    //TFS 2626
                }

            }, function (response) { $scope.isShowContinue = false }); //;
        }
        else {
            $scope.modal = $rootScope.annualReportModal;
            if ($scope.modal.EffectiveDate != null && $scope.modal.EffectiveDate != "" && $scope.modal.EffectiveDate != undefined)
                $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode.split(',');
            }
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = "";

            $scope.isShowReturnAddress = true;

            //TFS 2626
            $scope.modal.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit;
            $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit != undefined ? $scope.modal.IsGrossRevenueNonProfit : $scope.IsGrossRevenueNonProfit;
            //TFS 2626
        }

    };

    $(document).ready(function () {
        //If Gross Revenue is null, redirect (on refresh)
        //alert($scope.modal.BusinessType);
        if (
            typeof($scope.modal.BusinessType) === 'undefined'
            ) {
            if ($scope.IsGrossRevenueNonProfit !== true
                && $scope.IsGrossRevenueNonProfit !== false) {
                $scope.back();
            };
        };
    });

    // back to annual report business serarch
    $scope.back = function () {
        $location.path('/AnnualReport/BusinessSearch');
    };

    // validate & continue annual report for review
    $scope.ContinueSave = function (annualReportForm) {
        if (!angular.isDefined($scope.modal.BusinessStatus)) {
            // Folder Name: app Folder
            // Alert Name: UnableFilingMsg method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.AnnualReport.UnableFilingMsg);
            return;
        }

        if (["Active", "Delinquent"].indexOf($scope.modal.BusinessStatus) < 0) {
            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.AnnualReport.ActiveAndDelinquentStatus);
            return;
        }

        if (!$scope.modal.IsEligibleFilingType) {
            // Folder Name: app Folder
            // Alert Name: InvalidFilingTypeMsg method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.AnnualReport.InvalidFilingTypeMsg);
            return;
        }

        if ($scope.modal.isBusinessNameValid == false) {
            var publicBenefitNonProfitMsg = 'If the Nonprofit Corporation does not qualify or no longer elects to have the Public Benefit designation applied, the Nonprofit Corporation must file an Amendment to remove the words "Public Benefit" from its name prior to submitting the Annual Report.';
            wacorpService.alertDialog(publicBenefitNonProfitMsg);
            return;
        }

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Service Folder: services
        // File Name: wacorpService.js 
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[annualReportForm]);

        $scope.validateErrors = true;
        // registered agent

        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent = true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true;
        }
        //TFS 1143

        $scope.validateAgentErrors = $scope.modal.Agent.IsNewAgent ? true : ($scope.modal.Agent.IsAgentEdit ? true : false);
        $scope.validateOneAgent = $scope.modal.Agent.AgentID == 0 && !$scope.modal.Agent.IsNewAgent;

        // registered agent
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
                   ((!$scope.modal.Agent.IsNewAgent ? ($scope.modal.Agent.AgentID != 0 && $scope.modal.Agent.StreetAddress.FullAddress) ? true : (false && !$scope.modal.Agent.IsNoncommercialStreetAddress) : true) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 : true) && $scope[annualReportForm].RegisteredAgentForm.$valid));

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;

        $scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        $scope.checkRAStreetAddress = wacorpService.isRAStreetAddressValid($scope.modal.Agent.StreetAddress);//to check RA street address is valid or not 

        $scope.validateNonCommercialStreetAddress = !isRegisteredAgentValid && !$scope.modal.Agent.IsNoncommercialStreetAddress && !$scope.checkRAStreetAddress ? true : false;

        // nature of business
        $scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
             (!$scope.modal.NatureOfBusinessEntity.IsOtherNAICS ? $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0 : ($scope.modal.NatureOfBusinessEntity.IsOtherNAICS && !$scope.modal.NatureOfBusinessEntity.OtherDescription ? false : true)));
        //!($scope.modal.NatureOfBusinessEntity.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusinessEntity.OtherDescription == null ? true : $scope.modal.NatureOfBusinessEntity.OtherDescription.length <= 0)));

        // nature of business for non profit
        $scope.validateNatureOfBusinessNonProfit = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID) ||
             (!$scope.modal.NatureOfBusinessEntity.IsOtherNAICS ? $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0 : ($scope.modal.NatureOfBusinessEntity.IsOtherNAICS && !$scope.modal.NatureOfBusinessEntity.OtherDescription ? false : true)));

        //TFS 2628
        //Charitable NonProfit Corp and Reporting Questions
        $scope.ValidateCharityNonProfitReporting = ((!$scope.ScreenPart($scope.modal.AllScreenParts.CharitableNonProfitReporting, $scope.modal, $scope.modal.BusinessTypeID))
                || ($scope.modal.isCharityAndReportingValid));

        // general partners
        $scope.isGeneralPartnersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartners, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount() > 0);

        // general partners signature confirmation
        $scope.isGeneralPartnersAignConfimValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartnersSignatureConfirmation, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                    ($scope.modal.isGeneralPartnerSignatureConfirmation == "true" || $scope.modal.isGeneralPartnerSignatureConfirmation == true));

        // governing persons
        $scope.isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.amendprincipalsCount("GOVERNINGPERSON") > 0);

        // trustees
        $scope.isTrusteesValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Trustees, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount() > 0);

        //// principal office in wa
        //$scope.isPrincipalOfficeInWAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                    $scope[annualReportForm].PrincipalOffice.$valid);

        // principal office
        $scope.isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                $scope[annualReportForm].PrincipalOffice.$valid);

        // fein number
        $scope.isFeinValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.FEINNo, $scope.modal, $scope.modal.BusinessTypeID) ||
	        ($scope[annualReportForm].FEINNonProfitForm.$valid && $scope.modal.FEINNo.replace("-", "").length == 9));

        //(!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                $scope[annualReportForm].PrincipalOffice.$valid);

        //$scope.modal.PrincipalOfficeInWA.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOfficeInWA.PrincipalMailingAddress);
        $scope.modal.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalMailingAddress);

        // purpose and powers
        $scope.isPurposeAndPowersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PurposeAndPowers, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        ($scope[annualReportForm].PurposeAndPowers.$valid));

        // Public Benefit NonProfit Form validation
        $scope.ValidatePublicBenefitNonProfit = ((!$scope.ScreenPart($scope.modal.AllScreenParts.PublicBenefitNonProfit, $scope.modal, $scope.modal.BusinessTypeID)
            || !$scope.modal.IsPublicBenefitNonProfit)
            || $scope.modal.isPublicBenefitNonProfitValid);

        var isCorrespondenceAddressValid = $scope[annualReportForm].CorrespondenceAddress.$valid;

        //Check to hide effective date section for Np and Foreign NP TFS 2345
        //var isEffectiveDateValid = ($scope[annualReportForm].EffectiveDate.$valid);
        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[annualReportForm].EffectiveDate.$valid);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist
                                      && $scope.modal.UploadDocumentsList != null
                                      && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isOtherFormsValid = (isFormValid($scope[annualReportForm].AttestationOfSocialPurposeForm)
                                && isFormValid($scope[annualReportForm].AuthorizedPersonForm)
                                && isFormValid($scope[annualReportForm].DescriptionOfBusinessIncludedForm)
                                && isFormValid($scope[annualReportForm].AttestationOfSocialPurposeForm)
                                && isFormValid($scope[annualReportForm].GeneralPartnersSignatureConfirmationForm)
                                && isFormValid($scope[annualReportForm].NumberOfPartnersForm)
                                && isFormValid($scope[annualReportForm].PurposeOfCorporationForm
                                && isFormValid($scope[annualReportForm].FEINNonProfitForm
                                && isFormValid($scope[annualReportForm].CharitableNonProfitReportingForm)  //TFS 2628
                                )

                                && $scope.isPrincipalOfficeValid) && isCorrespondenceAddressValid && isRegisteredAgentValidStates)
        if (isRegisteredAgentValid
            && $scope.validateNatureOfBusiness
            && $scope.validateNatureOfBusinessNonProfit
            && $scope.ValidateCharityNonProfitReporting  //TFS 2628
            && $scope.isGeneralPartnersAignConfimValid
            && $scope.isGoverningPersonValid
            //&& $scope.isPrincipalOfficeInWAValid
            && $scope.ValidatePublicBenefitNonProfit  
            && $scope.isTrusteesValid
            && $scope.isPrincipalOfficeValid
            && $scope.isPurposeAndPowersValid
            && $scope.isFeinValid
            && isOtherFormsValid
            && isEffectiveDateValid
            && isAdditionalUploadValid) {

            if ($scope.modal.BusinessTransaction.LastARFiledDate != null && $scope.modal.BusinessTransaction.LastARFiledDate != '') {
                $scope.modal.ExpirationDateReview = new Date($scope.modal.BusinessTransaction.LastARFiledDate);
                $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
            }
            else {
                $scope.modal.ExpirationDateReview = new Date($scope.modal.NextARDueDate);
                $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
            }

            $scope.modal.IsReveiwPDFFieldsShow = true;
            $scope.isReviewAgent = false;
            $scope.validateErrors = false;
            $scope.validateRegAgentErrors = false;
            $scope.validatePrincipalOfficeInWAErrors = false;
            $scope.validateprincipalErrors = false;
            $scope.modal.BusinessFiling.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.EffectiveDate;
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
                $scope.modal.IsEmailOptionChecked = false;
            }
            $rootScope.annualReportModal = $scope.modal;
            $scope.isShowFeeList = canShowFeeList();
            if (!$scope.isShowFeeList)
                $rootScope.modal = $scope.modal;
            $location.path("/AnnualReportReview");
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // bind Naics codes to multi select dropdpwn
    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
            //$scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode;
        });
    }

    // bind Naics codes For Non Profit to multi select dropdpwn
    function getNaicsCodesNonProfit() {
        // Service Folder: services
        // File Name: lookupService.js  (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            $scope.NaicsCodesNonProfit = response.data;
            //$scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode;
        });
    }

    //  check whether form is valid / not
    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    // validate principals count
    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    $scope.amendprincipalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };
    $scope.clearOtherDescription = function () {
        $scope.modal.NatureOfBusinessEntity.OtherDescription = null;
    }

    //to trim empty spaces for NOB Other
    $scope.validateOtherNOB = function () {
        $scope.modal.NatureOfBusinessEntity.OtherDescription = $scope.modal.NatureOfBusinessEntity.OtherDescription ? angular.copy($scope.modal.NatureOfBusinessEntity.OtherDescription.trim()) : (($scope.modal.NatureOfBusinessEntity.OtherDescription == undefined || $scope.modal.NatureOfBusinessEntity.OtherDescription == "") ? $scope.modal.NatureOfBusinessEntity.OtherDescription = null : $scope.modal.NatureOfBusinessEntity.OtherDescription);
    }

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.NatureOfBusinessEntity.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusinessEntity.OtherDescription == null ? true : $scope.modal.NatureOfBusinessEntity.OtherDescription.length <= 0))
    }

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/AnnualReport';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode.join(",");
            $scope.modal.NatureOfBusinessEntity.BusinessID = $scope.modal.BusinessID;
        }

        $scope.modelDraft = {};

        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent = true;
        }

        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true;
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });

        // AnnualReportSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AnnualReportSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode;
            }
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }
});
wacorpApp.controller('annualReportIndexController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService,focus) {
    // declare scope variables
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
    $scope.businessSearchCriteria = { Type: "businessname", ID: "", IsSearch: true, PageID: 1, PageCount: 10, BusinessTypeId: 0, IsOnline: true, SearchType: "AnnualReport", isSearchClick: false };
    $scope.selectedBusiness = null;
    $scope.search = loadbusinessList;
    $scope.isEntityOrUBIRequired = $scope.isEntityOrUBIRequired || messages.EntityNameRequired;
    focus('searchField');

    // search business list
    $scope.submit = function (searchform) {
        $scope.isShowErrorFlag = true;
        $scope.isEntityOrUBIRequired = $scope.businessSearchCriteria.Type == 'businessname' ? messages.EntityNameRequired : messages.UBINumberRequired;
        if ($scope[searchform].$valid) {
            $scope.businessSearchCriteria.isSearchClick = true;
            $scope.isShowErrorFlag = false;
            loadbusinessList($scope.page); // loadbusinessList method is available in this controller only.
        }
    };
    // clear fields
    $scope.clearFun = function () {
        $scope.businessSearchCriteria.ID = "";
        $scope.businessSearchCriteria.isSearchClick = false;
        focus('searchField');
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
    }

    // navigate to annual report
    $scope.getNavigation = function () {
        if (["Active", "Delinquent"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
            $rootScope.annualReportModal = null;
            $rootScope.transactionID = null;
            $location.path('/AnnualReport/' + $scope.selectedBusiness.BusinessID);
        }
        else {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog('Selected business is ' + $scope.selectedBusiness.BusinessStatus);
        }
    };
   // get business list data from server
    function loadbusinessList(page) {
        page = page || 0;
        $scope.businessSearchCriteria.PageID = page == 0 ? 1 : page + 1;
        $scope.selectedBusiness = null;
        var data = $scope.businessSearchCriteria
        // getBusinessNames method is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.BusinessList = response.data;
            if ($scope.totalCount == 0) {
                var totalcount = response.data[0].Criteria.TotalRowCount;
                $scope.pagesCount = Math.round(totalcount / response.data.length);
                $scope.totalCount = totalcount;
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus('tblBusinessSearch');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == 0) {
            $scope.totalCount = 0;
            $scope.pagesCount = 0;
            $scope.totalCount = 0;
            $scope.page = 0;
        }
    }, true);
});



wacorpApp.controller('annualReportReviewController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService) {
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    //scope load
    $scope.Init = function () {
        if (!angular.isNullorEmpty($rootScope.annualReportModal)) {
            $scope.modal = $rootScope.annualReportModal;

            if ($scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID)) {
                getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in this controller only.
            }
            else {
                getNaicsCodes(); // getNaicsCodesNonProfit method is available in this controller only.
            }
        }
        else
            $scope.navAnnualReport();
    }

    // add annual filing to cart 
    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        //TFS 2751 hiding NP Checkboxes in PDF
        if (typeof (document.getElementById("divNPCheckboxes")) !== 'undefined') {
            $("#divNPCheckboxes").hide();
        };
        //TFS 2751

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");

        if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && angular.isArray($scope.modal.NatureOfBusinessEntity.NAICSCode) && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusinessEntity.NAICSCode);
        }
        else {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode;
        }
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        //TFS 2626
        $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit;
        //TFS 2626
        
        wacorpService.post(webservices.OnlineFiling.AnnualAddToCart, $scope.modal, function (response) {
            $rootScope.annualReportModal = null;
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $location.path('/shoppingCart');
           
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

   // back to annual report flow
    $scope.back = function () { 
        $rootScope.annualReportModal = $scope.modal;
        if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
            $rootScope.annualReportModal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode.join(",");
        }
        $location.path('/AnnualReport/' + $scope.modal.BusinessID);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // get selected Naics Codes
    function getNaicsCodes() {
        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc = '';
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.NatureOfBusinessEntity.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc += $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    }
    // get selected Naics Codes for Non Profit
    function getNaicsCodesNonProfit() {
        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc = '';
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            var principalsList = $scope.modal.NatureOfBusinessEntity.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodesNonProfit.push(response.data[i]);
                        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc += $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    }

    $scope.AddMoreItems = function () {
        
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusinessEntity.NAICSCode);
        // AnnualAddToCart method is availble in constants.js
        wacorpService.post(webservices.OnlineFiling.AnnualAddToCart, $scope.modal, function (response) {
            $rootScope.annualReportModal = null;
            $rootScope.transactionID = null;
            //if (response.BusinessTransaction.TransactionId > 0)
            $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('initialReportIndexController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    // declare scope variables
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
    $scope.businessSearchCriteria = { Type: "businessname", ID: "", IsSearch: true, PageID: 1, PageCount: 10, BusinessTypeId: 0, IsOnline: true, SearchType: "InitialReport", isSearchClick: false };
    $scope.selectedBusiness = null;
    $scope.search = loadbusinessList;
    $scope.isEntityOrUBIRequired = $scope.isEntityOrUBIRequired || messages.EntityNameRequired;
    focus('searchField');

    // search business list
    $scope.submit = function (searchform) {
        $scope.isShowErrorFlag = true;
        $scope.isEntityOrUBIRequired = $scope.businessSearchCriteria.Type == 'businessname' ? messages.EntityNameRequired : messages.UBINumberRequired;
        if ($scope[searchform].$valid) {
            $scope.businessSearchCriteria.isSearchClick = true;
            $scope.isShowErrorFlag = false;
            loadbusinessList($scope.page);// loadbusinessList method is available in this controller only.
        }
    };
    // clear fields
    $scope.clearFun = function () {
        $scope.businessSearchCriteria.ID = "";
        $scope.businessSearchCriteria.isSearchClick = false;
        focus('searchField');
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
    }

    // navigate to initial report
    $scope.getNavigation = function () {
        if (["Active", "Delinquent"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
            $rootScope.initialReportModal = null;
            $rootScope.transactionID = null;
            $location.path('/InitialReport/' + $scope.selectedBusiness.BusinessID);
        }
        else {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog('Selected business is ' + $scope.selectedBusiness.BusinessStatus);
        }
    };
   // get business list data from server
    function loadbusinessList(page) {
        page = page || 0;
        $scope.businessSearchCriteria.PageID = page == 0 ? 1 : page + 1;
        $scope.selectedBusiness = null;
        var data = $scope.businessSearchCriteria
        // getBusinessNames method is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.BusinessList = response.data;
            if ($scope.totalCount == 0) {
                var totalcount = response.data[0].Criteria.TotalRowCount;
                $scope.pagesCount = Math.round(totalcount / response.data.length);
                $scope.totalCount = totalcount;
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus('tblBusinessSearch');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == 0) {
            $scope.totalCount = 0;
            $scope.pagesCount = 0;
            $scope.totalCount = 0;
            $scope.page = 0;
        }
    }, true);
});



/*
Author      : Kishore Penugonda
File        : initialreportController.js
Description : initial report for domestic and foreign entities
*/
wacorpApp.controller('initialreportController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if (["Active", "Delinquent"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            var data = { params: { businessId: $scope.selectedBusiness.BusinessID, filingTypeName: "Initial Report", isOnline: true } };
            // ValidateBusinessStatus method is available in constants.js
            wacorpService.get(webservices.Common.ValidateBusinessStatus, data, function (response) {
                var result = response.data;
                if (result.Key != 0) {
                    if (result.Key == BusinessStatus.Delinquent) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.confirmDialog(result.Value, function () {
                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                    $rootScope.initialReportModal = null;
                    $rootScope.transactionID = null;
                    $location.path('/InitialReport/' + $scope.selectedBusiness.BusinessID);
                        });
                    }
                        //If the Annual Report has been filed
                    else if (result.Key == BusinessStatus.Active) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                }
                    else // Initial Report Already Filied
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    return;
                }
                else {
                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                    $rootScope.initialReportModal = null;
                    $rootScope.transactionID = null;
                    $location.path('/InitialReport/' + $scope.selectedBusiness.BusinessID);
                }
            }, function (response) {
                // Folder Name: app Folder
                // Alert Name: serverError method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.serverError);
            });
        }
        else {
            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InitialReport.ActiveAndDelinquentStatus);
        }
    }

    /* --------Initial Report Functionality------------- */

    // scope variables
    $scope.modal = {};
    $scope.NaicsCodes = [];
    //$scope.NaicsCodesNonProfit = [];
    $scope.validateErrors = false;
    $scope.validateAgentErrors = false;
    $scope.principalsCount = 0;
    $scope.InitialprincipalsCount = 0;
    $scope.isShowContinue = true;
    $scope.isExecutorEntityName = false;
    $scope.isIncorporatorEntityName = false;
    $scope.isGeneralPartnerEntityName = false;
    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        getNaicsCodes(); // getNaicsCodes method is available in this controller only.
        //getNaicsCodesNonProfit();
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.initialReportModal = $rootScope.modal;
            //$rootScope.modal = null;
        }
        // get business details 
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 18 is AMENDMENT OF TRADEMARK REGISTRATION
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 18 } };
        else
            data = { params: { businessID: $routeParams.id, transactionID: $rootScope.transactionID, filingTypeID: 18 } };
        if (angular.isNullorEmpty($rootScope.initialReportModal)) {
            // InitialReportCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.InitialReportCriteria, data, function (response) {
                $scope.modal = response.data;
                if (!angular.isNullorEmpty($scope.modal.BusinessName)) {
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.EffectiveDateType = $scope.modal.EffectiveDate == null ? 'DateOfFiling' : $scope.modal.EffectiveDateType;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertStringToObject($scope.modal.NatureOfBusiness.NAICSCode);
                    $scope.modal.NatureOfBusiness.IsOtherNAICS = !angular.isNullorEmpty($scope.modal.NatureOfBusiness.OtherDescription) ? true : false;
                    $scope.modal.NatureOfBusiness.BusinessID = $scope.modal.BusinessID;
                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    //$scope.modal.NatureOfBusiness.IsOtherNAICS = $scope.modal.NatureOfBusiness.OtherDescription != '' ? true : false;// Is Other NAICS check box in Nature Of Business Condition
                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                    // $scope.modal.BINAICSCodeDesc=!angular.isNullorEmpty($scope.modal.BINAICSCodeDesc)?$scope.modal.BINAICSCodeDesc.replace(/&amp;/g, '&'):"";
                    //$scope.modal.BINAICSCodeDesc = !angular.isNullorEmpty($scope.modal.BIOtherDescription)?$scope.modal.BINAICSCodeDesc+','+$scope.modal.BIOtherDescription:$scope.modal.BINAICSCodeDesc;
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.isShowReturnAddress = true;
                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                }
            }, function (response) {
                $scope.isShowContinue = false;
            });
        }
        else {
            $scope.modal = $rootScope.initialReportModal;
           
              if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                   $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode.split(',');
              }
              $scope.modal.NatureOfBusiness.BusinessID = $scope.modal.BusinessID;
           
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = "";

            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            $scope.isShowReturnAddress = true;
        }
    };



    // continue for review
    $scope.ContinueSave = function (initialReportForm) {
        if (["Active", "Delinquent"].indexOf($scope.modal.BusinessStatus) < 0) {
            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InitialReport.ActiveAndDelinquentStatus);
            return;
        }

        if (!$scope.modal.IsEligibleFilingType) {
            // Folder Name: app Folder
            // Alert Name: InvalidFilingTypeMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InitialReport.InvalidFilingTypeMsg);
            return;
        }


        $scope.validateErrors = true;

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[initialReportForm]);

        // registered agent
        $scope.validateAgentErrors = $scope.modal.Agent.IsNewAgent ? true : ($scope.modal.Agent.IsAgentEdit ? true : false);
        $scope.validateOneAgent = $scope.modal.Agent.AgentID == 0 && !$scope.modal.Agent.IsNewAgent;
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143


        // registered agent
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
                   ((!$scope.modal.Agent.IsNewAgent ? ($scope.modal.Agent.AgentID != 0 && $scope.modal.Agent.StreetAddress.FullAddress) ? true : (false && !$scope.modal.Agent.IsNoncommercialStreetAddress) : true) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 : true) && $scope[initialReportForm].RegisteredAgentForm.$valid));

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;

        $scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        $scope.checkRAStreetAddress = wacorpService.isRAStreetAddressValid($scope.modal.Agent.StreetAddress); //to check RA street address is valid or not

        $scope.validateNonCommercialStreetAddress = !isRegisteredAgentValid && !$scope.modal.Agent.IsNoncommercialStreetAddress && !$scope.checkRAStreetAddress ? true : false;

        // nature of business
        $scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusiness.IsOtherNAICS ? $scope.modal.NatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.NatureOfBusiness.IsOtherNAICS && !$scope.modal.NatureOfBusiness.OtherDescription  ? false : true)));

            //!($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0)));

        //$scope.NatureOfBusinessNonProfit = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID)
        //    || !($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0)));

        // general partners
        $scope.isGeneralPartnersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartners, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount() > 0);

        // general partners signature confirmation
        $scope.isGeneralPartnersAignConfimValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartnersSignatureConfirmation, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                   ($scope.modal.GeneralPartnersSignatureConfirmation == "true" || $scope.modal.GeneralPartnersSignatureConfirmation == true));

        // governing persons
        $scope.isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                         $scope.InitialprincipalsCount("GOVERNINGPERSON") > 0);

        // principal office in wa
        $scope.isPrincipalOfficeInWAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                $scope[initialReportForm].PrincipalOffice.$valid);

            //(!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
            //                                $scope[initialReportForm].PrincipalOffice.$valid);

        //var isAttestationOfStatedProfessionValid = !$scope.ScreenPart($scope.modal.AllScreenParts.AttestationOfStatedProfession, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].AttestationOfStatedProfessionForm.$valid;

        // PurposeAndPowers
        $scope.isPurposeAndPowersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PurposeAndPowers, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        ($scope[initialReportForm].PurposeAndPowers.$valid));

        var isEffectiveDateValid = ($scope[initialReportForm].EffectiveDate.$valid);
        var isCorrespondenceAddressValid = $scope[initialReportForm].CorrespondenceAddress.$valid;

        //var isNotExecutorEntityName = wacorpService.validateExecutorListWithEntityName($rootScope.NewEntityNameCleanUp) == false ? true : false;
        //$scope.isExecutorEntityName = isNotExecutorEntityName == false ? true : false;

        //var isNotIncorporatorEntityName = wacorpService.validateIncorporatorListWithEntityName($rootScope.NewEntityNameCleanUp) == false ? true : false;
        //$scope.isIncorporatorEntityName = isNotIncorporatorEntityName == false ? true : false;

        //var isNotGeneralPartnerEntityName = wacorpService.validateGeneralPartnerWithEntityName($rootScope.NewEntityNameCleanUp) == false ? true : false;
        //$scope.isGeneralPartnerEntityName = isNotGeneralPartnerEntityName == false ? true : false;


        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isOtherFormsValid = (isFormValid($scope[initialReportForm].AttestationOfSocialPurposeForm)
                                && isFormValid($scope[initialReportForm].AuthorizedPersonForm)
                                && isFormValid($scope[initialReportForm].DescriptionOfBusinessIncludedForm)
                                && isFormValid($scope[initialReportForm].AttestationOfSocialPurposeForm)
                                && isFormValid($scope[initialReportForm].GeneralPartnersSignatureConfirmationForm)
                                && isFormValid($scope[initialReportForm].NumberOfPartnersForm)
                                && isFormValid($scope[initialReportForm].PurposeOfCorporationForm));

        if (isRegisteredAgentValid
            && $scope.validateNatureOfBusiness
            && $scope.isGeneralPartnersAignConfimValid
            && $scope.isGoverningPersonValid
            && $scope.isPrincipalOfficeInWAValid
            && $scope.isPurposeAndPowersValid
            && isOtherFormsValid
            && isEffectiveDateValid && isAdditionalUploadValid && isCorrespondenceAddressValid && isRegisteredAgentValidStates) {
            $scope.isReviewAgent = false;
            $scope.validateErrors = false;
            $scope.validateRegAgentErrors = false;
            $scope.validatePrincipalOfficeInWAErrors = false;
            $scope.validateprincipalErrors = false;
            $scope.modal.BusinessFiling.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.EffectiveDate;
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	            // $rootScope.$broadcast('onEmailEmpty');
	            $scope.modal.IsEmailOptionChecked = false;
            }
            $rootScope.initialReportModal = $scope.modal;
            $rootScope.modal = $scope.modal;
            $location.path('/InitialReportReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // back to business search
    $scope.back = function () {
        $location.path('/InitialReport/SearchBusiness');
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // validate principals count
    $scope.principalsCount = function () {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    $scope.InitialprincipalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };

    // dropdown binding for nature of business
    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
        });
    }

    //function getNaicsCodesNonProfit() {
    //    lookupService.NaicsCodesNonProfit(function (response) {
    //        $scope.NaicsCodesNonProfit = response.data;
    //    });
    //}

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }
    $scope.clearOtherDescription = function () {
        $scope.modal.NatureOfBusiness.OtherDescription = null;
    }

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0))
    }
    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/InitialReport';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0 && angular.isArray($scope.modal.NatureOfBusiness.NAICSCode)) {
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $scope.modelDraft = {};
        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        wacorpService.post(webservices.OnlineFiling.InitialReportSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0 && !angular.isArray($scope.modal.NatureOfBusiness.NAICSCode)) {
                $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode)   ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
            }
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }
});

wacorpApp.controller('initialReportReviewController', function ($scope, $routeParams, $location, $rootScope,lookupService, wacorpService, ScopesData, focus) {
    $scope.NaicsCodes = [];
    //$scope.NaicsCodesNonProfit = [];
    //scope load
    $scope.Init = function () {
        if (!angular.isNullorEmpty($rootScope.initialReportModal)) {
            $scope.modal = $rootScope.initialReportModal;
            getNaicsCodes(); // getNaicsCodes method is available in this controller only.
            //getNaicsCodesNonProfit();
        }
        else
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            $scope.navInitialReport();
       
    }

    // add filing to cart
    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");

        $scope.modal.IsInitialReportFiled = true;
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusiness.NAICSCode);
        }
        // InitialAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.InitialAddToCart, $scope.modal, function (response) {
            $rootScope.initialReportModal = null;
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $location.path('/shoppingCart');
            
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    // back to initial report flow
    $scope.back = function () {
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $rootScope.initialReportModal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $rootScope.initialReportModal = $scope.modal;
        $location.path('/InitialReport/' + $scope.modal.BusinessID);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // get selected Naics Codes
    function getNaicsCodes() {
        $scope.modal.NatureOfBusiness.NAICSCodeDesc = '';
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        $scope.modal.NatureOfBusiness.NAICSCodeDesc += $scope.modal.NatureOfBusiness.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    }

    // add filing to cart
    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.IsInitialReportFiled = true;
        $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusiness.NAICSCode);
        // InitialAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.InitialAddToCart, $scope.modal, function (response) {
            $rootScope.initialReportModal = null;
            $rootScope.transactionID = null;
           // if ($scope.modal.BusinessTransaction.TransactionId > 0)
                $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    // get selected Naics Codes for Non Profit
    //function getNaicsCodes() {
    //    lookupService.NaicsCodesNonProfit(function (response) {
    //        var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
    //            for (var i = 0; i < response.data.length; i++) {
    //                if (naicscode == response.data[i].Key) {
    //                    $scope.NaicsCodesNonProfit.push(response.data[i]);
    //                    break;
    //                }
    //            }
    //        });
    //    });
    //}


});

wacorpApp.controller('statementofChangeController', function ($scope, $location, $rootScope, wacorpService) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        // if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.BusinessStatus) >= constant.ZERO) { // TFS 13053
        $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
        $rootScope.statementofChangeModal = null;
        $rootScope.transactionID = null;
        $location.path('/StatementofChange');
        //}
        //else {
        //    wacorpService.alertDialog(messages.selectedBusiness.replace('{0}', $scope.selectedBusiness.BusinessStatus));
        //}
    }

    //-------------------------------------- Statement of change screen functionality--------------------//

    $scope.Init = function () {
        $scope.validateOneAgent = $scope.validateAgentErrors = $scope.validateAuthorizedErrors = false;
        $scope.messages = messages;
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.statementofChangeModal = $rootScope.modal;
            //$rootScope.modal = null;
        }
        var data = null;
        if ($rootScope.transactionID > constant.ZERO)
            data = {
                params: {
                    businessID: null, transactionID: $rootScope.transactionID,
                }
            };
        else
            data = {
                params: {
                    businessID: $rootScope.BusinessID, transactionID: $rootScope.transactionID
                }
            };
        if (angular.isNullorEmpty($rootScope.statementofChangeModal)) {
            if ($rootScope.BusinessID == undefined && $rootScope.transactionID == undefined) {
                $location.path('/StatementofChangeIndex');
            }
            else {
                // StatementofChangeCriteria method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.StatementofChangeCriteria, data, function (response) {
                    $scope.modal = response.data;
                    $scope.modal.RegisteredAgent = undefined;
                    $scope.isShow = true;
                    $scope.modal.PrevRegisteredAgent.AgentType = $scope.modal.PrevRegisteredAgent.AgentType || ResultStatus.INDIVIDUAL;
                    //$scope.modal.PrevRegisteredAgent.IsNonCommercial = true;
                    $scope.IsInvalidStateS(); // IsInvalidStateS method is available in this controller only.
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || ResultStatus.INDIVIDUAL;
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.isShowReturnAddress = true;
                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }

                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                }, function (response) { });
            }
        }

        else {
            $scope.isShow = true;
            $scope.modal = $rootScope.statementofChangeModal;
            $scope.isShowReturnAddress = true;
        }
    };

    $scope.continueSave = function (stmtChangeForm) {

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[stmtChangeForm]);

        $scope.validateAgentErrors = $scope.modal.PrevRegisteredAgent.IsNewAgent ? true : ($scope.modal.Agent.IsAgentEdit ? true : false);
        $scope.validateOneAgent = $scope.modal.PrevRegisteredAgent.AgentID == constant.ZERO && !$scope.modal.PrevRegisteredAgent.IsNewAgent;
        var isRegisteredAgentValid = (!$scope.modal.PrevRegisteredAgent.IsNewAgent ? ($scope.modal.PrevRegisteredAgent.AgentID != 0 && $scope.modal.PrevRegisteredAgent.StreetAddress.FullAddress) ? true : (false && !$scope.modal.PrevRegisteredAgent.IsNoncommercialStreetAddress) : true) && (!$scope.modal.PrevRegisteredAgent.IsNonCommercial ? $scope.modal.PrevRegisteredAgent.StreetAddress.StreetAddress1 : true) && $scope[stmtChangeForm].RegisteredAgent.$valid;
        var isRegisteredAgentValidStates = !$scope.modal.PrevRegisteredAgent.StreetAddress.IsInvalidState && !$scope.modal.PrevRegisteredAgent.MailingAddress.IsInvalidState && !$scope.modal.PrevRegisteredAgent.StreetAddress.invalidPoBoxAddress;
        $scope.validateStreetAddress = !$scope.modal.PrevRegisteredAgent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        $scope.checkRAStreetAddress = wacorpService.isRAStreetAddressValid($scope.modal.Agent.StreetAddress);// 

        $scope.validateNonCommercialStreetAddress = !isRegisteredAgentValid && !$scope.modal.PrevRegisteredAgent.IsNoncommercialStreetAddress && !$scope.checkRAStreetAddress ? true : false;
        $scope.validateAuthorizedErrors = true;
        var isCorrespondenceAddressValid = $scope[stmtChangeForm].CorrespondenceAddress.$valid;//to check RA street address is valid or not

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
        if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
            $scope.modal.IsEmailOptionChecked = false;
        }

        if ($scope[stmtChangeForm].AuthorizedPersonForm.$valid && isRegisteredAgentValid && isAdditionalUploadValid && isCorrespondenceAddressValid && isRegisteredAgentValidStates) {
            $scope.validateOneAgent = $scope.validateAgentErrors = $scope.validateAuthorizedErrors = false;
            $scope.modal.PrevRegisteredAgent.MailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrevRegisteredAgent.MailingAddress);
            $scope.modal.PrevRegisteredAgent.StreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrevRegisteredAgent.StreetAddress);
            $rootScope.statementofChangeModal = $scope.modal;
            $rootScope.modal = $scope.modal;
            $location.path('/StatementofChangeReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // back to business search
    $scope.back = function () {
        $location.path('/StatementofChangeIndex');
    };
    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {

        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl= '/StatementofChange';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // StatementOfChangeSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.StatementOfChangeSaveAsDraft, $scope.modelDraft, function (response) {

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.nonCommercialRAEdit = function (PrevRegisteredAgent) {
        var config = { params: { BusinessID: PrevRegisteredAgent.BusinessIDForRA, AgentId: PrevRegisteredAgent.AgentID } };
        var data = "";
        // getNonCommercialRADetailsForEdit method is available in constants.js
        wacorpService.get(webservices.Common.getNonCommercialRADetailsForEdit, config, function (response) {
            if (response.data != null) {
                $scope.agentInfo = angular.copy(response.data);
                $scope.modal.PrevRegisteredAgent.ConfirmEmailAddress = $scope.agentInfo.EmailAddress;
                $scope.modal.PrevRegisteredAgent.IsAgentEdit = true;
                $scope.modal.PrevRegisteredAgent.IsAgentAltered = true; //TFS 1143
                //$scope.agent.IsNonCommercial = true;
                //$scope.agent.IsAgentEdit = true;
                //$scope.agent.IsNewAgent = true;

            }
            else
                // Folder Name: app Folder
                // Alert Name: noDataFound method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.noDataFound);
        },
            function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data.Message);
            }
        );
    }

    $scope.clearAgentInfo = function (agentType) {
        if (agentType == 'I') {
            $scope.modal.PrevRegisteredAgent.EntityName = '';
            //$scope.agent.OfficeOrPosition = '';
        }
        else if (agentType == 'E') {
            $scope.modal.PrevRegisteredAgent.FirstName = '';
            $scope.modal.PrevRegisteredAgent.LastName = '';
            $scope.modal.PrevRegisteredAgent.EntityName = '';
            //$scope.agent.OfficeOrPosition = '';
        }
        else {
            $scope.modal.PrevRegisteredAgent.FirstName = '';
            $scope.modal.PrevRegisteredAgent.LastName = '';
            $scope.modal.PrevRegisteredAgent.EntityName = '';
        }
    }

    //Copy the Mailing address to Street Address
    $scope.CopyAgentStreetFromMailing = function () {
        if ($scope.modal.PrevRegisteredAgent.IsSameAsMailingAddress)
            angular.copy($scope.modal.PrevRegisteredAgent.StreetAddress, $scope.modal.PrevRegisteredAgent.MailingAddress);
        else
            angular.copy("", $scope.modal.PrevRegisteredAgent.MailingAddress);
    };

    $scope.IsInvalidStateS = function () {


        // validate agent state
        // Street Address
        if (!$scope.modal.PrevRegisteredAgent.StreetAddress.IsInvalidState) {
            if ($scope.modal.PrevRegisteredAgent.StreetAddress && $scope.modal.PrevRegisteredAgent.StreetAddress.State && $scope.modal.PrevRegisteredAgent.StreetAddress.State != 'WA') {
                $scope.modal.PrevRegisteredAgent.isStreetStateMustbeinWA = true;
                $scope.modal.PrevRegisteredAgent.StreetAddress.IsInvalidState = true;
            }
            else {
                $scope.modal.PrevRegisteredAgent.isStreetStateMustbeinWA = false;
                $scope.modal.PrevRegisteredAgent.StreetAddress.IsInvalidState = false;
            }
        }


        // Mailing Address
        if (!$scope.modal.PrevRegisteredAgent.MailingAddress.IsInvalidState) {
            if ($scope.modal.PrevRegisteredAgent.MailingAddress && $scope.modal.PrevRegisteredAgent.MailingAddress.State && $scope.modal.PrevRegisteredAgent.MailingAddress.State != 'WA') {
                $scope.modal.PrevRegisteredAgent.isMailingStateMustbeinWA = true;
                $scope.modal.PrevRegisteredAgent.MailingAddress.IsInvalidState = true;
            }
            else {
                $scope.modal.PrevRegisteredAgent.isMailingStateMustbeinWA = false;
                $scope.modal.PrevRegisteredAgent.MailingAddress.IsInvalidState = false;
            }
        }
    }
});

wacorpApp.controller('statementofChangeReviewController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    //-------------------------------------- Statement of change screen functionality--------------------//
    $scope.Init = function () {
        if (angular.isNullorEmpty($rootScope.statementofChangeModal))
            $location.path('/StatementofChangeIndex');
        else
            $scope.modal = $rootScope.statementofChangeModal;
    };

    $scope.back = function () {
        $rootScope.statementofChangeModal = $scope.modal;
        $location.path('/StatementofChange');
    };

    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        //DevOps 2476 - hiding NP Checkboxes in PDF
        if (typeof (document.getElementById("divNPCheckboxes")) !== 'undefined') {
            $("#divNPCheckboxes").hide();
        };
        //DevOps 2476

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // StatementofChangeAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.StatementofChangeAddToCart, $scope.modal, function (response) {
            $rootScope.statementofChangeModal = null;
            $rootScope.modal = null;
            $rootScope.BusinessType = null;
            $location.path('/shoppingCart');
            
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        // StatementofChangeAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.StatementofChangeAddToCart, $scope.modal, function (response) {
            $rootScope.statementofChangeModal = null;
            $rootScope.BusinessType = null;
           // if ($scope.modal.BusinessTransaction.TransactionId > 0)
                $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('reinstatementController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, ScopesData, focus) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        // here BusinessCategoryID = 3 DOMESTIC ENTITY
        if ($scope.selectedBusiness.BusinessCategoryID == 3) {//If This is Domestic Navigate to Reinstatement
            if ([ResultStatus.AdministrativelyDissolved].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
                var data = { params: { businessId: $scope.selectedBusiness.BusinessID, filingTypeName: "Reinstatement", isOnline: true } };
                // ValidateBusinessStatus method is available in constants.js
                wacorpService.get(webservices.Common.ValidateBusinessStatus, data, function (response) {
                    var result = response.data;
                    if (result.Key != 0) {
                        if (result.Key == BusinessStatus.AdministrativelyDissolved) {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.confirmDialog(result.Value, function () {
                                var data1 = { params: { businessId: $scope.selectedBusiness.BusinessID, IsGrossRevenueNonProfit: $rootScope.IsGrossRevenueNonProfit } };  //TFS 2324 adding bool? IsGrossRevenueNonProfit
                                // isReinstatementARWithInDueDate method is available in constants.js
                                wacorpService.get(webservices.Common.isReinstatementARWithInDueDate, data1, function (result) {
                                    var result1 = result.data;
                                    if (result1.isAddCurrentARFee) {
                                        // Folder Name: app Folder
                                        // Alert Name: ReinstatementARalert method is available in alertMessages.js
                                        wacorpService.confirmDialog($scope.messages.Reinstatement.ReinstatementARalert, function () {
                                            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                            $rootScope.reinstatementModal = null;
                                            $rootScope.transactionID = null;
                                            $rootScope.addCurrentARFee = 'Y';

                                            $scope.IsGrossRevenueNonProfit = $rootScope.IsGrossRevenueNonProfit;

                                            $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);
                                        },
                                            function () {
                                                $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                                $rootScope.reinstatementModal = null;
                                                $rootScope.transactionID = null;
                                                $rootScope.addCurrentARFee = 'N';

                                                $scope.IsGrossRevenueNonProfit = $rootScope.IsGrossRevenueNonProfit;

                                                $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);
                                            }
                                        );
                                    }
                                    else {
                                        $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                        $rootScope.reinstatementModal = null;
                                        $rootScope.transactionID = null;
                                        $rootScope.addCurrentARFee = 'N';

                                        $scope.IsGrossRevenueNonProfit = $rootScope.IsGrossRevenueNonProfit;

                                        $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);
                                    }
                                },

                                 function (response) {
                                     // Folder Name: app Folder
                                     // Alert Name: serverError method is available in alertMessages.js
                                     wacorpService.alertDialog($scope.messages.serverError);
                                 });
                            });
                        }
                            // key 4 for second message for AR
                        else
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog(result.Value);
                        return;
                    }
                    else {
                        var data1 = { params: { businessId: $scope.selectedBusiness.BusinessID, IsGrossRevenueNonProfit: $rootScope.IsGrossRevenueNonProfit } };  //TFS 2324 adding bool? IsGrossRevenueNonProfit
                        // isReinstatementARWithInDueDate method is available in constants.js
                        wacorpService.get(webservices.Common.isReinstatementARWithInDueDate, data1, function (result) {
                            var result1 = result.data;
                            if (result1.isAddCurrentARFee) {
                                // Folder Name: app Folder
                                // Alert Name: ReinstatementARalert method is available in alertMessages.js 
                                wacorpService.confirmDialog($scope.messages.Reinstatement.ReinstatementARalert, function () {
                                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                    $rootScope.reinstatementModal = null;
                                    $rootScope.transactionID = null;
                                    $rootScope.addCurrentARFee = 'Y';
                                    $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);
                                },
                                    function () {
                                        $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                        $rootScope.reinstatementModal = null;
                                        $rootScope.transactionID = null;
                                        $rootScope.addCurrentARFee = 'N';
                                        $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);
                                    }
                                );
                            }
                            else {
                                $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                $rootScope.reinstatementModal = null;
                                $rootScope.transactionID = null;
                                $rootScope.addCurrentARFee = 'N';
                                $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);
                            }
                        },

                         function (response) {
                             // Folder Name: app Folder
                             // Alert Name: serverError method is available in alertMessages.js 
                             wacorpService.alertDialog($scope.messages.serverError);
                         });
                    }
                }, function (response) {
                    // Folder Name: app Folder
                    // Alert Name: serverError method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.serverError);
                });
            }
            else {
                // Folder Name: app Folder
                // Alert Name: isAdministrativeDissolved method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.Reinstatement.isAdministrativeDissolved);
            }
        }

        if ($scope.selectedBusiness.BusinessCategoryID == 5) {//If This is Foreign Navigate to Requalification
            if ([ResultStatus.Terminated].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
                var data = { params: { businessId: $scope.selectedBusiness.BusinessID, filingTypeName: "Requalification", isOnline: true } };
                // ValidateBusinessStatus method is available in constants.js
                wacorpService.get(webservices.Common.ValidateBusinessStatus, data, function (response) {
                    var result = response.data;
                    if (result.Key != 0) {
                        if (result.Key == BusinessStatus.Dissolved) {
                            wacorpService.confirmDialog(result.Value, function () {
                                var data1 = { params: { businessId: $scope.selectedBusiness.BusinessID } };
                                // isRequalificationARWithInDueDate method is available in constants.js
                                wacorpService.get(webservices.Common.isRequalificationARWithInDueDate, data1, function (result) {
                                    var result1 = result.data;
                                    if (result1.isAddCurrentARFee) {
                                        // Folder Name: app Folder
                                        // Alert Name: ReinstatementARalert method is available in alertMessages.js S
                                        wacorpService.confirmDialog($scope.messages.Requalification.ReinstatementARalert, function () {
                                            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                            $rootScope.reinstatementModal = null;
                                            $rootScope.transactionID = null;
                                            $rootScope.addCurrentARFee = 'Y';
                                            $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                                        },
                                            function () {
                                                $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                                $rootScope.reinstatementModal = null;
                                                $rootScope.transactionID = null;
                                                $rootScope.addCurrentARFee = 'N';
                                                $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                                            }
                                        );
                                    }
                                    else {
                                        $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                        $rootScope.reinstatementModal = null;
                                        $rootScope.transactionID = null;
                                        $rootScope.addCurrentARFee = 'N';
                                        $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                                    }
                                },

                                 function (response) {
                                     // Folder Name: app Folder
                                     // Alert Name: serverError method is available in alertMessages.js 
                                     wacorpService.alertDialog($scope.messages.serverError);
                                 });
                            });
                        }
                            // key 4 for second message for AR
                        else
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog(result.Value);
                        return;
                    }
                    else {
                        var data1 = { params: { businessId: $scope.selectedBusiness.BusinessID } };
                        // isRequalificationARWithInDueDate method is available in constants.js
                        wacorpService.get(webservices.Common.isRequalificationARWithInDueDate, data1, function (result) {
                            var result1 = result.data;
                            if (result1.isAddCurrentARFee) {
                                // Folder Name: app Folder
                                // Alert Name: ReinstatementARalert method is available in alertMessages.js
                                wacorpService.confirmDialog($scope.messages.Requalification.ReinstatementARalert, function () {
                                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                    $rootScope.reinstatementModal = null;
                                    $rootScope.transactionID = null;
                                    $rootScope.addCurrentARFee = 'Y';
                                    $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                                },
                                    function () {
                                        $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                        $rootScope.reinstatementModal = null;
                                        $rootScope.transactionID = null;
                                        $rootScope.addCurrentARFee = 'N';
                                        $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                                    }
                                );
                            }
                            else {
                                $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                $rootScope.reinstatementModal = null;
                                $rootScope.transactionID = null;
                                $rootScope.addCurrentARFee = 'N';
                                $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                            }
                        },

                         function (response) {
                             // Folder Name: app Folder
                             // Alert Name: serverError method is available in alertMessages.js
                             wacorpService.alertDialog($scope.messages.serverError);
                         });
                    }

                }, function (response) {
                    // Folder Name: app Folder
                    // Alert Name: serverError method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.serverError);
                });
            }
            else {
                // Folder Name: app Folder
                // Alert Name: isTerminated method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.Requalification.isTerminated);
            }
        }
    };

    /* --------Annual Report Functionality------------- */

    // scope variable
    $scope.modal = {};
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    $scope.validateErrors = false;
    $scope.validateAgentErrors = false;
    $scope.principalsCount = 0;
    $scope.isShowContinue = true;
    $scope.isShowFeeList = false;
    $scope.feeListLayout = PartialViews.FilingFeeListView;
    $scope.feeDetailsDescription = "Reinstatement Fee Details";
    function canShowFeeList() {
        if (!angular.isDefined($scope.modal.FeeList))
            return false;
        else if (angular.isNullorEmpty($scope.modal.FeeList))
            return false;
        return $scope.modal.FeeList.length > 0;
    }

    // scope load 
    $scope.Init = function () {
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.reinstatementModal = $rootScope.modal;
            //$rootScope.modal = null;
            // Added lines below to mirror AR controller, prevent interposition of data between Cart and Incomplete
            $scope.IsGrossRevenueNonProfit = $rootScope.reinstatementModal.IsGrossRevenueNonProfit;//TFS 2628 Getting value from saved Json
        } else {
            $scope.IsGrossRevenueNonProfit = $rootScope.IsGrossRevenueNonProfit;//TFS 2628 getting value from business Search (index)
        }

        $scope.modal.isBusinessNameAvailable = false;
        $scope.modal.IsAmendmentEntityNameChange = true;

        $scope.messages = messages;
        getNaicsCodes(); // getNaicsCodes method is available in this controller only.
        getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in this controller only.
        // get business details
        var data = null;
        if ($rootScope.transactionID > 0) {
            var transactionid = $rootScope.transactionID;
            // here filingTypeID: 3 is ADMINISTRATIVE DISSOLUTION
            data = { params: { businessID: null, transactionID: transactionid, filingTypeID: 3, addCurrentARFee: $rootScope.addCurrentARFee } };
        }
        else
        {
            data = { params: { businessID: $routeParams.id, transactionID: $rootScope.transactionID, filingTypeID: 3, addCurrentARFee: $rootScope.addCurrentARFee } };

        }

        if ($rootScope.reinstatementModal == null || $rootScope.reinstatementModal == undefined
            || $scope.IsGrossRevenueNonProfit == null || $scope.IsGrossRevenueNonProfit == undefined) { //TFS 2626  losing Gross Rev on load, this is needed but breaks the page

            // GetReinstatementBusinessCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.GetReinstatementBusinessCriteria, data, function (response) {
                $scope.modal = response.data;
                if (!angular.isNullorEmpty($scope.modal.BusinessName)) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.EffectiveDateType = $scope.modal.EffectiveDate == null ? 'DateOfFiling' : $scope.modal.EffectiveDateType;
                    //$scope.modal.BusinessName = !angular.isNullorEmpty(response.data.NewBusinessName) ? response.data.NewBusinessName : response.data.BusinessName;
                    $scope.modal.NewBusinessName = !angular.isNullorEmpty(response.data.NewBusinessName) ? response.data.NewBusinessName : response.data.BusinessName;

                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertStringToObject($scope.modal.NatureOfBusiness.NAICSCode);
                    $scope.modal.NatureOfBusiness.IsOtherNAICS = !angular.isNullorEmpty($scope.modal.NatureOfBusiness.OtherDescription) ? true : false;
                    $scope.modal.NatureOfBusiness.BusinessID = $scope.modal.BusinessID;
                    $scope.modal.BusinessTransaction.TransactionId = !$rootScope.transactionID ? transactionid : $rootScope.transactionID;
                    $scope.modal.NameReservedId = ($scope.modal.NameReservedId == 0 ? null : $scope.modal.NameReservedId);
                    $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;
                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                    $scope.modal.NewBusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
                    $scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
                    $scope.modal.OldBusinessName = !angular.isNullorEmpty($scope.modal.OldBusinessName) ? $scope.modal.OldBusinessName : $scope.modal.BusinessName;
                    // $scope.modal.BINAICSCodeDesc=!angular.isNullorEmpty($scope.modal.BINAICSCodeDesc)?$scope.modal.BINAICSCodeDesc.replace(/&amp;/g, '&'):"";
                    //$scope.modal.BINAICSCodeDesc = !angular.isNullorEmpty($scope.modal.BIOtherDescription)?$scope.modal.BINAICSCodeDesc+','+$scope.modal.BIOtherDescription:$scope.modal.BINAICSCodeDesc;
                    $scope.isShowReturnAddress = true;
                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js 
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.modal.IsAmendmentEntityNameChange = $scope.modal.IsAmendmentEntityNameChange;
                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;

                    // TFS#2347; adding (same code as in AR)
                    //$scope.TestValuesAlert();//TFS 2626 TFS 2347
                    $scope.modal.IsCharitableNonProfit = $scope.modal.IsCharitableNonProfit != undefined ? $scope.modal.IsCharitableNonProfit : $scope.IsCharitableNonProfit
                    $scope.modal.IsNonProfitExempt = $scope.modal.IsNonProfitExempt != undefined ? $scope.modal.IsNonProfitExempt : $scope.IsNonProfitExempt;
                    $scope.modal.NonProfitReporting1 = $scope.modal.NonProfitReporting1 != undefined ? $scope.modal.NonProfitReporting1 : $scope.NonProfitReporting1;
                    $scope.modal.NonProfitReporting2 = $scope.modal.NonProfitReporting2 != undefined ? $scope.modal.NonProfitReporting2 : $scope.NonProfitReporting2;
                    //$scope.modal.BusinessType = $scope.modal.BusinessType != undefined ? $scope.modal.BusinessType : $scope.BusinessType;


                    //$scope.TestValuesAlert();
                    //TFS 2626 TFS 2347
                    if (
                        ($scope.modal.BusinessType == "WA NONPROFIT CORPORATION" ||
                        $scope.modal.BusinessType == "WA NONPROFIT PROFESSIONAL SERVICE CORPORATION" ||
                        $scope.modal.BusinessType == "FOREIGN NONPROFIT CORPORATION" ||
                        $scope.modal.BusinessType == "FOREIGN NONPROFIT PROFESSIONAL SERVICE CORPORATION")
                        &&
                        ($scope.IsGrossRevenueNonProfit == undefined &&
                        $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit == undefined &&
                        $scope.modal.IsCharitableNonProfit == undefined)
                        ) {
                        $location.path('/ReinstatementIndex');
                    }
                    else {
                        //TFS 2626 TFS 2347
                        if ($scope.modal.BusinessTransaction.IsGrossRevenueNonProfit != undefined) {
                            $scope.IsGrossRevenueNonProfit = $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit;
                            $rootScope.IsGrossRevenueNonProfit = $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit;
                        };
                        //TFS 2626 TFS 2347
                        $scope.modal.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit;
                        $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit;
                    };
                    //TFS 2626 TFS 2347
                }
            }, function (response) { $scope.isShowContinue = false; });
        }
        else {
            //$scope.modal.NewBusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
            //$scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
            $scope.modal.OldBusinessName = !angular.isNullorEmpty($scope.modal.OldBusinessName) ? $scope.modal.OldBusinessName : $scope.modal.BusinessName;

            $scope.modal = $rootScope.reinstatementModal;
            $scope.modal.IsAmendmentEntityNameChange = $scope.modal.IsAmendmentEntityNameChange;
            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
            }
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = "";

            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);

            //$scope.modal.IsGrossRevenueNonProfit = $rootScope.reinstatementModal.IsGrossRevenueNonProfit;  //TFS 2427

            $scope.isShowReturnAddress = true;
        }
    };

    // back to annual report business serarch
    $scope.back = function () {
        $location.path('/ReinstatementIndex');
    };

    // validate & continue annual report for review
    $scope.ContinueSave = function (reinstatementForm) {
        $scope.showEntityErrorMessage = true;
        $scope.validateErrorMessage = true;

        if (["Administratively Dissolved"].indexOf($scope.modal.BusinessStatus) < 0) {
            // Folder Name: app Folder
            // Alert Name: administrativeDissolvedMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.Reinstatement.administrativeDissolvedMsg);
            return;
        }

        if (!$scope.modal.IsEligibleFilingType) {
            // Folder Name: app Folder
            // Alert Name: InvalidFilingTypeMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.Reinstatement.InvalidFilingTypeMsg);
            return;
        }

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[reinstatementForm]);

        $scope.validateErrors = true;

        //// Check indicators Validation
        //if (!$scope.modal.IsNameReserved) {
        //    $scope.modal.isValidIndicator();
        //}

        //Entity Name
        var businessNameCount = $scope.availableBusinessCount(); // availableBusinessCount method is available in this controller only.
        var isBusinessNameExists = ($scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable))
            || $scope.modal.IsNameReserved;
        //var isBusinessNameExists = (!$scope.modal.IsNameReserved ? (($scope.modal.isBusinessNameAvailable == null || $scope.modal.isBusinessNameAvailable == undefined) ? true : $scope.modal.isBusinessNameAvailable) : true);
        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);
        var isEntityValid = ($scope[reinstatementForm].NewEntityName.$valid && businessNameValid &&
                                ((!$scope.modal.IsNameReserved && wacorpService.isIndicatorValid($scope.modal))
                                || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != ""))
                            );

        if (!wacorpService.isIndicatorValid($scope.modal)) {
            $rootScope.$broadcast("checkIndicator");
        }
        // registered agent
        $scope.validateAgentErrors = $scope.modal.ReinstatementAgent.IsNewAgent ? true : ($scope.modal.Agent.IsAgentEdit ? true : false);
        $scope.validateOneAgent = $scope.modal.ReinstatementAgent.AgentID == 0 && !$scope.modal.ReinstatementAgent.IsNewAgent;
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // registered agent
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
                   //($scope.modal.ReinstatementAgent.AgentID == 0 && $scope[reinstatementForm].RegisteredAgent.$valid) || ($scope.modal.ReinstatementAgent.AgentID != 0));
        ((!$scope.modal.ReinstatementAgent.IsNewAgent ? ($scope.modal.ReinstatementAgent.AgentID != 0 && $scope.modal.ReinstatementAgent.StreetAddress.FullAddress) ? true : (false && !$scope.modal.ReinstatementAgent.IsNoncommercialStreetAddress) : true) && (!$scope.modal.ReinstatementAgent.IsNonCommercial ? $scope.modal.ReinstatementAgent.StreetAddress.StreetAddress1 : true) && $scope[reinstatementForm].RegisteredAgentForm.$valid));

        var isRegisteredAgentValidStates = !$scope.modal.ReinstatementAgent.StreetAddress.IsInvalidState && !$scope.modal.ReinstatementAgent.MailingAddress.IsInvalidState && !$scope.modal.ReinstatementAgent.StreetAddress.invalidPoBoxAddress;

        $scope.validateStreetAddress = !$scope.modal.ReinstatementAgent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        $scope.checkRAStreetAddress = wacorpService.isRAStreetAddressValid($scope.modal.Agent.StreetAddress); //to check RA street address is valid or not

        $scope.validateNonCommercialStreetAddress = !isRegisteredAgentValid && !$scope.modal.ReinstatementAgent.IsNoncommercialStreetAddress && !$scope.checkRAStreetAddress ? true : false;
        // nature of business
        $scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
        (!$scope.modal.NatureOfBusiness.IsOtherNAICS ? $scope.modal.NatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.NatureOfBusiness.IsOtherNAICS && !$scope.modal.NatureOfBusiness.OtherDescription ? false : true)));

        // nature of business non profit
        $scope.NatureOfBusinessNonProfit = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusiness.IsOtherNAICS ? $scope.modal.NatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.NatureOfBusiness.IsOtherNAICS && !$scope.modal.NatureOfBusiness.OtherDescription ? false : true)));

        //!($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0)));

        // TFS#2347; added validation for Charitable NonProfit Corp and Reporting Questions
        var isCharityAndReportingValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.CharitableNonProfitandReporting, $scope.modal, $scope.modal.BusinessTypeID)
            || ($scope.modal.isCharityAndReportingValid));

        var isOtherFormsValid = isFormValid($scope[reinstatementForm].AuthorizedPersonForm);

        // var isCharityAndReportingValid = $scope.modal.isCharityAndReportingValid; // Not needed - KK

        // governing persons
        $scope.isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount("GOVERNINGPERSON") > 0);

        // principal office in wa
        $scope.isPrincipalOfficeInWAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                $scope[reinstatementForm].PrincipalOffice.$valid);

        // FEIN Nonprofit; TFS#2347; added
        $scope.isFeinValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.FEINNo, $scope.modal, $scope.modal.BusinessTypeID) ||
	        ($scope[reinstatementForm].FEINNonProfitForm.$valid && $scope.modal.FEINNo.replace("-","").length == 9));

        //$scope.modal.PrincipalOffice.IsOldDataExist ? (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                $scope[reinstatementForm].PrincipalOffice.$valid) : true;

	    //Check to hide effective date section for Np and Foreign NP TFS 2345
        //var isEffectiveDateValid = ($scope[reinstatementForm].EffectiveDate.$valid);
        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID)
	        || $scope[reinstatementForm].EffectiveDate.$valid);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        var isCorrespondenceAddressValid = $scope[reinstatementForm].CorrespondenceAddress.$valid;


        if (isRegisteredAgentValid
            && $scope.validateNatureOfBusiness
            && $scope.NatureOfBusinessNonProfit
            && $scope.isGoverningPersonValid
            && $scope.isPrincipalOfficeInWAValid
            && isOtherFormsValid
            && isEntityValid
            && isEffectiveDateValid
            && isAdditionalUploadValid
            && isCorrespondenceAddressValid
            && isRegisteredAgentValidStates
            && isCharityAndReportingValid
            && $scope.isFeinValid
            ) {

            if ($rootScope.addCurrentARFee == 'Y') {
                $scope.modal.ExpirationDateReview = new Date($scope.modal.BusinessTransaction.LastARFiledDate);
                $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
            }
            else {
                $scope.modal.ExpirationDateReview = new Date($scope.modal.RenewalDate);
                $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
            }

            $scope.modal.IsReveiwPDFFieldsShow = true;
            $scope.isReviewAgent = false;
            $scope.validateErrors = false;
            $scope.validateRegAgentErrors = false;
            $scope.validatePrincipalOfficeInWAErrors = false;
            $scope.validateprincipalErrors = false;
            $scope.modal.BusinessFiling.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.EffectiveDate;
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.ReinstatementAgent.EmailAddress == "" || $scope.modal.ReinstatementAgent.EmailAddress == null || $scope.modal.ReinstatementAgent.EmailAddress == undefined)) {
	            $scope.modal.IsEmailOptionChecked = false;
            }
            $scope.modal.IsAmendmentEntityNameChange = true;

            $rootScope.reinstatementModal = $scope.modal;
            $rootScope.modal = $scope.modal;
            $scope.isShowFeeList = canShowFeeList();
            if (!$scope.isShowFeeList)
                $location.path("/ReinstatementReview");
        }
        else {
            // All validation false
            if (isBusinessNameExists && !isEntityValid) {
                setTimeout(function () {
                    $("#txtBusiessName").trigger("blur");
                }, 500);
                //return false;
            }
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // bind Naics codes to multi select dropdpwn
    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
            //$scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
        });
    }

    // bind Naics codes to multi select dropdpwn for Non Profit
    function getNaicsCodesNonProfit() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            $scope.NaicsCodesNonProfit = response.data;
            //$scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
        });
    }


    //  check whether form is valid / not
    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    // validate principals count
    //$scope.principalsCount = function (baseType) {
    //    var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
    //        return (principal.Status != principalStatus.DELETE);
    //    });
    //    return principalsList.length;
    //};

    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '130px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };

    // check business count availability
    $scope.availableBusinessCount = function () {
        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {
            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };

    $scope.clearOtherDescription = function () {
        $scope.modal.NatureOfBusiness.OtherDescription = null;
    }

    //to trim empty spaces for NOB Other
    $scope.validateOtherNOB = function () {
        $scope.modal.NatureOfBusiness.OtherDescription = $scope.modal.NatureOfBusiness.OtherDescription ? angular.copy($scope.modal.NatureOfBusiness.OtherDescription.trim()) : (($scope.modal.NatureOfBusiness.OtherDescription == undefined || $scope.modal.NatureOfBusiness.OtherDescription == "") ? $scope.modal.NatureOfBusiness.OtherDescription = null : $scope.modal.NatureOfBusiness.OtherDescription);
    }

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0))
    }

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.IsAmendmentEntityNameChange = true;

        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/Reinstatement';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }

        $scope.modelDraft = {};
        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        wacorpService.post(webservices.OnlineFiling.ReinstatementSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
            }

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }


    //$scope.TestValuesAlert = function () {
    //    alert('$scope.IsGrossRevenueNonProfit: ' + $scope.IsGrossRevenueNonProfit + '\r\n' +
    //        '$scope.modal.IsGrossRevenueNonProfit: ' + $scope.modal.IsGrossRevenueNonProfit + '\r\n' +
    //        '$scope.modal.BusinessTransaction.IsGrossRevenueNonProfit: ' + $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit + '\r\n' +
    //        '$rootScope.IsGrossRevenueNonProfit: ' + $rootScope.IsGrossRevenueNonProfit + '\r\n');
    //};
});
wacorpApp.controller('reinstatementIndexController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, ScopesData, focus) {
    // declare scope variables
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
    $scope.businessSearchCriteria = { Type: "businessname", ID: "", IsSearch: true, PageID: 1, PageCount: 10, BusinessTypeId: 0, IsOnline: true,SearchType: "InitialReport", isSearchClick: false };
    $scope.selectedBusiness = null;
    $scope.search = loadbusinessList;
    $scope.isEntityOrUBIRequired = $scope.isEntityOrUBIRequired || messages.EntityNameRequired;
    focus('searchField');

    // search business list
    $scope.submit = function (searchform) {
        $scope.isShowErrorFlag = true;
        $scope.isEntityOrUBIRequired = $scope.businessSearchCriteria.Type == 'businessname' ? messages.EntityNameRequired : messages.UBINumberRequired;
        if ($scope[searchform].$valid) {
            $scope.businessSearchCriteria.isSearchClick = true;
            $scope.isShowErrorFlag = false;
            loadbusinessList($scope.page); // loadbusinessList method is available in this controller only.
        }
    };
    // clear fields
    $scope.clearFun = function () {
        $scope.businessSearchCriteria.ID = "";
        $scope.businessSearchCriteria.isSearchClick = false;
        focus('searchField');
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
    }

    // navigate to annual report
    $scope.getNavigation = function () {
        if ([ResultStatus.AdministrativelyDissolved].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
        //if (["Active", "Delinquent"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
            $rootScope.reinstatementModal = null;
            $rootScope.transactionID = null;
            $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);
           
        }
        else {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog('Selected business is ' + $scope.selectedBusiness.BusinessStatus);
        }
    };
   // get business list data from server
    function loadbusinessList(page) {
        page = page || 0;
        $scope.businessSearchCriteria.PageID = page == 0 ? 1 : page + 1;
        $scope.selectedBusiness = null;
        var data = $scope.businessSearchCriteria
        // getBusinessNames methiod is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.BusinessList = response.data;
            if ($scope.totalCount == 0) {
                var totalcount = response.data[0].Criteria.TotalRowCount;
                $scope.pagesCount = Math.round(totalcount / response.data.length);
                $scope.totalCount = totalcount;
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus('tblBusinessSearch');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == 0) {
            $scope.totalCount = 0;
            $scope.pagesCount = 0;
            $scope.totalCount = 0;
            $scope.page = 0;
        }
    }, true);
});



wacorpApp.controller('reinstatementReviewController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, ScopesData, focus) {
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    //scope load
    $scope.Init = function () {
        if (!angular.isNullorEmpty($rootScope.reinstatementModal)) {
            $scope.modal = $rootScope.reinstatementModal;
            getNaicsCodes(); // getNaicsCodes method is available in constants.js
            getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in constants.js
        }
        else
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            $scope.navReinstatement();
    }

    // add annual filing to cart 
    $scope.AddToCart = function () {

        $scope.modal.NewBusinessName = $scope.modal.BusinessName;
        $scope.modal.BusinessName = $scope.modal.OldBusinessName;
        $scope.modal.OldBusinessName = $scope.modal.OldBusinessName;

        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';
        
        //TFS 2751 hiding NP Checkboxes in PDF
        if (typeof (document.getElementById("divNPCheckboxes")) !== 'undefined') {
            $("#divNPCheckboxes").hide();
        };
        //TFS 2751

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusiness.NAICSCode);
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        $scope.modal.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit; //TFS 2324 TFS 2347

        // AddReinstatementToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AddReinstatementToCart, $scope.modal, function (response) {
            $rootScope.reinstatementModal = null;
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $location.path('/shoppingCart');
          
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    // back to annual report flow
    $scope.back = function () {
        $rootScope.reinstatementModal = $scope.modal;
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $rootScope.reinstatementModal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $location.path('/Reinstatement/' + $scope.modal.BusinessID);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // get selected Naics Codes
    function getNaicsCodes() {
        var naicDesc = "";
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        naicDesc += (naicDesc == "" ? response.data[i].Value : (", " + response.data[i].Value));
                        break;
                    }
                }
            });
            $scope.modal.NatureOfBusiness.NAICSCodeDesc = naicDesc;
        });
    }
    // get selected Naics Codes for non profit
    function getNaicsCodesNonProfit() {
        var naicDesc = "";
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodesNonProfit.push(response.data[i]);
                        naicDesc += (naicDesc == "" ? response.data[i].Value : (", " + response.data[i].Value));
                        break;
                    }
                }
            });
            $scope.modal.NatureOfBusiness.NAICSCodeDesc = naicDesc;
        });
    }

    // add annual filing to cart 
    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusiness.NAICSCode);

        // AddReinstatementToCart method is vailable in constants.js
        wacorpService.post(webservices.OnlineFiling.AddReinstatementToCart, $scope.modal, function (response) {
            $rootScope.reinstatementModal = null;
            $rootScope.transactionID = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
                $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('amendedAnnualReportController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService) {
    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if (["Active", "Delinquent"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0)
            // validateAmendedAR method is available in this method only.
            validateAmendedAR($scope.selectedBusiness.BusinessID);
        else
            wacorpService.alertDialog($scope.messages.AmendedAnnualReport.ActiveAndDelinquentStatus);
    }

    function validateAmendedAR(businessid) {
        var data = { params: { businessId: businessid, filingTypeName: "Amended Annual Report", isOnline: true } };
        // ValidateBusinessStatus method is available in constants.js 
        wacorpService.get(webservices.Common.ValidateBusinessStatus, data, function (response) {
            var result = response.data;
            if (result.Key != 0) {
                if (result.Key == BusinessStatus.AdministrativelyDissolved) {
                    wacorpService.confirmDialog(result.Value, function () {
                        $rootScope.BusinessID = businessid;
                        $rootScope.amendedAnnualReportModal = null;
                        $rootScope.transactionID = null;
                        $location.path('/AmendedAnnualReport/' + businessid);
                    });
                }
                else if (result.Key == BusinessStatus.Active) {
                    wacorpService.alertDialog(result.Value);
                } else {
                    $rootScope.BusinessID = businessid;
                    $rootScope.amendedAnnualReportModal = null;
                    $rootScope.transactionID = null;
                    $location.path('/AmendedAnnualReport/' + businessid);
                }
                return;
            }
            else {
                $rootScope.BusinessID = businessid;
                $rootScope.amendedAnnualReportModal = null;
                $rootScope.transactionID = null;
                $location.path('/AmendedAnnualReport/' + businessid);
            }
        }, function (error) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });
    }



    /* --------Annual Report Functionality------------- */

    // scope variable
    $scope.modal = {};
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    $scope.validateErrors = false;
    $scope.validateAgentErrors = false;
    $scope.principalsCount = 0;
    $scope.isShowContinue = true;
    // scope load 
    $scope.Init = function () {
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.amendedAnnualReportModal = $rootScope.modal;
            //$rootScope.modal = null;
        }

        $scope.messages = messages;
        getNaicsCodes(); // getNaicsCodes method is available in this controller only.
        getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in this controller only.
        // get business details
        var data = null;
        if ($rootScope.transactionID > 0)
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 19 } };
        else
            data = { params: { businessID: $routeParams.id, transactionID: $rootScope.transactionID, filingTypeID: 19 } };
        if ($rootScope.amendedAnnualReportModal == null || $rootScope.amendedAnnualReportModal == undefined) {
            //AmendedAnnualReportCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.AmendedAnnualReportCriteria, data, function (response) {
                $scope.modal = response.data;
                if (!angular.isNullorEmpty($scope.modal.BusinessName)) {
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.EffectiveDateType = $scope.modal.EffectiveDate == null ? 'DateOfFiling' : $scope.modal.EffectiveDateType;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertStringToObject($scope.modal.NatureOfBusinessEntity.NAICSCode);
                    $scope.modal.NatureOfBusinessEntity.IsOtherNAICS = !angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.OtherDescription) ? true : false;
                    $scope.modal.NatureOfBusinessEntity.BusinessID = $scope.modal.BusinessID;
                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;
                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                    //$scope.modal.BINAICSCodeDesc=!angular.isNullorEmpty($scope.modal.BINAICSCodeDesc)?$scope.modal.BINAICSCodeDesc.replace(/&amp;/g, '&'):"";
                    //$scope.modal.BINAICSCodeDesc = !angular.isNullorEmpty($scope.modal.BIOtherDescription)?$scope.modal.BINAICSCodeDesc+','+$scope.modal.BIOtherDescription:$scope.modal.BINAICSCodeDesc;
                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                    $scope.isShowReturnAddress = true;
                }
            }, function (response) { $scope.isShowContinue = false; });
        }
        else {
            $scope.modal = $rootScope.amendedAnnualReportModal;
            if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode.split(',');
            }

            //$scope.Canshow($rootScope.amendedAnnualReportModal,19)
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = "";

            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            $scope.isShowReturnAddress = true;
        }
    };

    // back to annual report business serarch
    $scope.back = function () {

        $location.path("/AmendedAnnualReport/BusinessSearch");
    };

    // validate & continue annual report for review
    $scope.ContinueSave = function (amendedAnnualReportForm) {
        
        if (["Active", "Delinquent"].indexOf($scope.modal.BusinessStatus) < 0) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.AmendedAnnualReport.ActiveAndDelinquentStatus);
            return;
        }

        if (!$scope.modal.IsEligibleFilingType) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.AmendedAnnualReport.InvalidFilingTypeMsg);
            return;
        }

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
      

        $scope.validatePrincipalOfficeInWAErrors = $scope.validateErrors = $scope.validateprincipalErrors = true;
        // registered agent

        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143
 
        
        $scope.validateAgentErrors = $scope.modal.Agent.IsNewAgent ? true : ($scope.modal.Agent.IsAgentEdit?true:false);
        $scope.validateOneAgent = $scope.modal.Agent.AgentID == 0 && !$scope.modal.Agent.IsNewAgent;

        // registered agent old code
        //var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
        //           ($scope.modal.Agent.AgentID == 0 && $scope[amendedAnnualReportForm].RegisteredAgent.$valid) || ($scope.modal.Agent.AgentID != 0));

        // registered agent new code
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
                  ((!$scope.modal.Agent.IsNewAgent ? (($scope.modal.Agent.AgentID != 0 && $scope.modal.Agent.StreetAddress.FullAddress)?true:(false && !$scope.modal.Agent.IsNoncommercialStreetAddress)) : true) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 : true) && $scope[amendedAnnualReportForm].RegisteredAgent.$valid));

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;

        $scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        $scope.checkRAStreetAddress = wacorpService.isRAStreetAddressValid($scope.modal.Agent.StreetAddress);//to check RA street address is valid or not

        $scope.validateNonCommercialStreetAddress = !isRegisteredAgentValid && !$scope.modal.Agent.IsNoncommercialStreetAddress && !$scope.checkRAStreetAddress ? true : false;

        //$scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial?$scope.validateAgentErrors;

        //($scope.modal.Agent.AgentID != 0 && ($scope.modal.Agent.AgentID == 0 || $scope.modal.Agent.AgentID!=0 ? $scope[amendedAnnualReportForm].RegisteredAgent.$valid: true)));


        // nature of business
        $scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusinessEntity.IsOtherNAICS ? $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0 : ($scope.modal.NatureOfBusinessEntity.IsOtherNAICS && !$scope.modal.NatureOfBusinessEntity.OtherDescription ? false : true)));

        // nature of business non Profit
        $scope.NatureOfBusinessNonProfit = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusinessEntity.IsOtherNAICS ? $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0 : ($scope.modal.NatureOfBusinessEntity.IsOtherNAICS && !$scope.modal.NatureOfBusinessEntity.OtherDescription  ? false : true)));


        // governing persons
        $scope.isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                      $scope.principalsCount("GOVERNINGPERSON") > 0);

        // principal office in wa
        //$scope.isPrincipalOfficeInWAValid = $scope.modal.PrincipalOfficeInWA.IsOldDataExist ? (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                    $scope[amendedAnnualReportForm].PrincipalOffice.$valid): true;

        // principal office
        $scope.isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                $scope[amendedAnnualReportForm].PrincipalOffice.$valid);

            //$scope.modal.PrincipalOffice.IsOldDataExist ? (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
            //                                $scope[amendedAnnualReportForm].PrincipalOffice.$valid) : true;

        var isEffectiveDateValid = ($scope[amendedAnnualReportForm].EffectiveDate.$valid);
        var isCorrespondenceAddressValid = $scope[amendedAnnualReportForm].CorrespondenceAddress.$valid;
        //$scope[amendedAnnualReportForm].ConfirmEmailAddress = $scope[amendedAnnualReportForm].isCorrespondenceAddressValid;
        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isOtherFormsValid = (isFormValid($scope[amendedAnnualReportForm].AuthorizedPersonForm)
                                && isFormValid($scope[amendedAnnualReportForm].DescriptionOfBusinessIncludedForm));

        if (isRegisteredAgentValid
            && $scope.validateNatureOfBusiness
            && $scope.NatureOfBusinessNonProfit
            && $scope.isGoverningPersonValid
            //&& $scope.isPrincipalOfficeInWAValid
            && $scope.isPrincipalOfficeValid
            && isOtherFormsValid
            && isEffectiveDateValid
            && isAdditionalUploadValid
            && isCorrespondenceAddressValid && isRegisteredAgentValidStates) {
            $scope.isReviewAgent = false;
            $scope.validateErrors = false;
            $scope.validateRegAgentErrors = false;
            $scope.validatePrincipalOfficeInWAErrors = false;
            $scope.validateprincipalErrors = false;
            $scope.modal.BusinessFiling.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.EffectiveDate;
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	            $scope.modal.IsEmailOptionChecked = false;
            }
            $rootScope.amendedAnnualReportModal = $scope.modal;
            $rootScope.modal = $scope.modal;
            $location.path("/AmendedAnnualReportReview")
        }
        else
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        var val = false;
        if (angular.isNullorEmpty(screenPart))
            return false;
        if (screenPart == 20) {
            // Here businessTypeID = 24 is FOREIGN MASSACHUSETTS TRUST.
            if (businessTypeID == 24)
                val = true;
        }

        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // bind Naics codes to multi select dropdpwn
    function getNaicsCodes() {
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
            //$scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode;
        });
    }

    // bind Naics codes to multi select dropdpwn for Non Profit
    function getNaicsCodesNonProfit() {
        lookupService.NaicsCodesNonProfit(function (response) {
            $scope.NaicsCodesNonProfit = response.data;
            //$scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode;
        });
    }


    //  check whether form is valid / not
    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    // validate principals count
    //$scope.principalsCount = function (baseType) {
    //    var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
    //        return (principal.Status != principalStatus.DELETE);
    //    });
    //    return principalsList.length;
    //};

    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };
    $scope.clearOtherDescription = function () {
        $scope.modal.NatureOfBusinessEntity.OtherDescription = null;
    }

    //to trim empty spaces for NOB Other
    $scope.validateOtherNOB = function () {
         
        $scope.modal.NatureOfBusinessEntity.OtherDescription = $scope.modal.NatureOfBusinessEntity.OtherDescription ? angular.copy($scope.modal.NatureOfBusinessEntity.OtherDescription.trim()) : (($scope.modal.NatureOfBusinessEntity.OtherDescription == undefined || $scope.modal.NatureOfBusinessEntity.OtherDescription == "") ? $scope.modal.NatureOfBusinessEntity.OtherDescription = null : $scope.modal.NatureOfBusinessEntity.OtherDescription);
    }

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.NatureOfBusinessEntity.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusinessEntity.OtherDescription == null ? true : $scope.modal.NatureOfBusinessEntity.OtherDescription.length <= 0))
    }
    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/AmendedAnnualReport';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode.join(",");
        }
        $scope.modelDraft = {};
        angular.copy($scope.modal, $scope.modelDraft);
        //wacorpService.AllScreenParts($scope.modelDraft);
        //wacorpService.EntityTypesWithScreens($scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        
        // AmendmentAnnualReportSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AmendmentAnnualReportSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode;
            }
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $scope.modal.CartStatus = response.data.CartStatus;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

});

wacorpApp.controller('amendedAnnualReportIndexController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {
    // declare scope variables
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
    $scope.businessSearchCriteria = { Type: "businessname", ID: "", IsSearch: true, PageID: 1, PageCount: 10, BusinessTypeId: 0, IsOnline: true, SearchType: "AnnualReport", isSearchClick: false };
    $scope.selectedBusiness = null;
    $scope.search = loadbusinessList;
    $scope.isEntityOrUBIRequired = $scope.isEntityOrUBIRequired || messages.EntityNameRequired;
    focus('searchField');

    // search business list
    $scope.submit = function (searchform) {
        $scope.isShowErrorFlag = true;
        $scope.isEntityOrUBIRequired = $scope.businessSearchCriteria.Type == 'businessname' ? messages.EntityNameRequired : messages.UBINumberRequired;
        if ($scope[searchform].$valid) {
            $scope.businessSearchCriteria.isSearchClick = true;
            $scope.isShowErrorFlag = false;
            loadbusinessList($scope.page); // loadbusinessList method is available in this controller only.
        }
    };
    // clear fields
    $scope.clearFun = function () {
        $scope.businessSearchCriteria.ID = "";
        $scope.businessSearchCriteria.isSearchClick = false;
        focus('searchField');
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
    }

    // navigate to annual report
    $scope.getNavigation = function () {
        if (["Active", "Delinquent"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            // validateAmendedAR method is available in this controller only.
            validateAmendedAR($scope.selectedBusiness.BusinessID);
        }
        else {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog('Selected business is ' + $scope.selectedBusiness.BusinessStatus);
        }
    };
   // get business list data from server
    function loadbusinessList(page) {
        page = page || 0;
        $scope.businessSearchCriteria.PageID = page == 0 ? 1 : page + 1;
        $scope.selectedBusiness = null;
        var data = $scope.businessSearchCriteria
        // getBusinessNames method is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.BusinessList = response.data;
            if ($scope.totalCount == 0) {
                var totalcount = response.data[0].Criteria.TotalRowCount;
                $scope.pagesCount = Math.round(totalcount / response.data.length);
                $scope.totalCount = totalcount;
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus('tblBusinessSearch');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    function validateAmendedAR(businessid) {
        var config = { params: { busid: businessid } };
        // ValidateAmendedAR method is available in constants.js
        wacorpService.get(webservices.OnlineFiling.ValidateAmendedAR, config, function (response) {
            var result = JSON.parse(response.data);
            if (result === ""){
                $rootScope.BusinessID = businessid;
                $rootScope.amendedAnnualReportModal = null;
                $rootScope.transactionID = null;
                $location.path('/AmendedAnnualReport/' + businessid);
            }
            else
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(result);
        }, function (error) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == 0) {
            $scope.totalCount = 0;
            $scope.pagesCount = 0;
            $scope.totalCount = 0;
            $scope.page = 0;
        }
    }, true);
});



wacorpApp.controller('amendedAnnualReportReviewController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService) {
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    //scope load
    $scope.Init = function () {
        if (!angular.isNullorEmpty($rootScope.amendedAnnualReportModal)) {
            $scope.modal = $rootScope.amendedAnnualReportModal;

            if ($scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID)) {
                getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in this controller only.
            }
            else {
                getNaicsCodes(); // getNaicsCodes method is available in this controller only.
            }
        }
        else
            $scope.navAmendedAnnualReport();
    }
    // add amended annual filing to cart 
    $scope.AddToCart = function () {
        
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        //DevOps 2476 hiding NP Checkboxes in PDF 
        if (typeof (document.getElementById("divNPCheckboxes")) !== 'undefined') {
            $("#divNPCheckboxes").hide();
        };
        //DevOps 2476

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");

        if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && angular.isArray($scope.modal.NatureOfBusinessEntity.NAICSCode) && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusinessEntity.NAICSCode);
        }
        else {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode;
        }

        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        wacorpService.post(webservices.OnlineFiling.AmendedAnnualAddToCart, $scope.modal, function (response) {
            $rootScope.amendedAnnualReportModal = null;
            $rootScope.modal =null;
            $rootScope.transactionID = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
            $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    // back to amended annual report flow
    $scope.back = function () {
        $rootScope.amendedAnnualReportModal = $scope.modal;
        if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
            $rootScope.amendedAnnualReportModal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode.join(",");
        }
        $location.path('/AmendedAnnualReport/' + $scope.modal.BusinessID);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };
   
    // get selected Naics Codes
    function getNaicsCodes() {
        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc = '';
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.NatureOfBusinessEntity.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc += $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    }

    // get selected Naics Codes for Non Profit
    function getNaicsCodesNonProfit() {
        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc = '';
        lookupService.NaicsCodesNonProfit(function (response) {
            var principalsList = $scope.modal.NatureOfBusinessEntity.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodesNonProfit.push(response.data[i]);
                        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc += $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    }

    //Add More Items functionality
    $scope.AddMoreItems = function () {
        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc = '';
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusinessEntity.NAICSCode);
        // AmendedAnnualAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AmendedAnnualAddToCart, $scope.modal, function (response) {
            $rootScope.amendedAnnualReportModal = null;
            $rootScope.transactionID = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('amendmentOfForiegnRegistrationStatementIndexController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {
    // declare scope variables
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
    $scope.businessSearchCriteria = { Type: "businessname", ID: "", IsSearch: true, PageID: 1, PageCount: 10, BusinessTypeId: 0, IsOnline: true, SearchType: "AmendmentofForiegnRegistrationStatement", isSearchClick: false };
    $scope.selectedBusiness = null;
    $scope.search = loadbusinessList;
    focus('searchField');

    // search business list
    $scope.submit = function (searchform) {
        
        $scope.isShowErrorFlag = true;
        if ($scope[searchform].$valid) {
            $scope.businessSearchCriteria.isSearchClick = true;
            $scope.isShowErrorFlag = false;
            loadbusinessList($scope.page); // loadbusinessList method is available in this controller only.
        }
    };
    // clear fields
    $scope.clearFun = function () {
        $scope.businessSearchCriteria.ID = "";
        $scope.businessSearchCriteria.isSearchClick = false;
        focus('searchField');
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
    }

    // navigate to Amendment of Foriegn Registration Statement
    $scope.getNavigation = function () {
        if (["Active"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
            $rootScope.annualReportModal = null;
            $rootScope.transactionID = null;
            $location.path('/AmendmentofForiegnRegistrationStatement/' + $scope.selectedBusiness.BusinessID);
        }
        else {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog('Selected business is ' + $scope.selectedBusiness.BusinessStatus);
        }
    };
   // get business list data from server
    function loadbusinessList(page) {
        page = page || 0;
        $scope.businessSearchCriteria.PageID = page == 0 ? 1 : page + 1;
        $scope.selectedBusiness = null;
        var data = $scope.businessSearchCriteria
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.BusinessList = response.data;
            if ($scope.totalCount == 0) {
                var totalcount = response.data[0].Criteria.TotalRowCount;
                $scope.pagesCount = Math.round(totalcount / response.data.length);
                $scope.totalCount = totalcount;
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus('tblBusinessSearch');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == 0) {
            $scope.totalCount = 0;
            $scope.pagesCount = 0;
            $scope.totalCount = 0;
            $scope.page = 0;
        }
    }, true);
});



wacorpApp.controller('amendmentOfForiegnRegistrationStatementController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus, $timeout) {

    /* ------------Business Search Functionality--------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if (["Active", "Delinquent"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
            $rootScope.annualReportModal = null;
            $rootScope.transactionID = null;
            $location.path('/AmendmentofForiegnRegistrationStatement/' + $scope.selectedBusiness.BusinessID);
        }
        else {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.AmendmentOfForiegnRegistrationStmt.ActiveAndDelinquentStatus);
        }
    }


    $scope.currentbusinesstypeid = 0;

    /* ------------Amendment of Foriegn Registration Statement functionality--------------- */

    // scope variable
    $scope.modal = {};

    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    $scope.CountriesList;
    $scope.StatesList;
    $scope.validateErrorMessage = false;
    $scope.principalsCount = 0;
    $scope.uploadFilesCount = 0;
    $scope.businessLayout = "/ng-app/view/partial/BusinessInfo.html";
    $scope.IsAmendEntityTypeShow = false;    
    // scope load 
    $scope.Init = function () {
        //$scope.isRequiredAmend = true;
        $scope.unitedstates = "UNITED STATES";
        $scope.CountryChangeDesc();
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $scope.modal = $rootScope.modal;
        }
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
        });

        lookupService.NaicsCodesNonProfit(function (response) {
            $scope.NaicsCodesNonProfit = response.data;
        });

        var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
            $scope.CountriesList = response.data;

            $timeout(function () {
                $("#id-JurisdictionCountry").val($scope.modal.JurisdictionCountry);
                //$("#id-JurisdictionState").val($scope.modal.JurisdictionState);
            }, 1000);

        }, function (response) {
        });

        var lookupStatesParams = { params: { name: 'ForeignJurisdictionStates' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
            $scope.StatesList = response.data;
            $timeout(function () {
                var state = $scope.modal.JurisdictionState;
                $("#id-JurisdictionState").val(state == 0 ? $scope.modal.JurisdictionState = state.toString().replace(0, "") : (state == null ? $scope.modal.JurisdictionState = "" : $scope.modal.JurisdictionState));
            }, 1000);
        }, function (response) {
        });
       
        // get business details
        var data = null;
        if ($rootScope.transactionID > 0)
            // Here filingTypeID = 10 is AMENDED CERTIFICATE OF LIMITED LIABILITY LIMITED PARTNERSHIP.
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 10 } };
        else {
            data = { params: { businessID: $routeParams.id, transactionID: $rootScope.transactionID, filingTypeID: 10 } };
        }

         
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            // AmendmentOfForiegnRegistrationStatementCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.AmendmentOfForiegnRegistrationStatementCriteria, data, function (response) {
                // store current business info to hidden object
               // $scope.currentBusiness = angular.copy(response.data);
                $scope.modal = angular.copy(response.data);
                if (!angular.isNullorEmpty($scope.modal.BusinessName)) {
                    //$scope.modal.BusinessName = !angular.isNullorEmpty(response.data.NewBusinessName) ? response.data.NewBusinessName : response.data.BusinessName;
                    //$scope.modal.NewBusinessName = !angular.isNullorEmpty(response.data.NewBusinessName) ? response.data.NewBusinessName : response.data.BusinessName;
                    //$scope.modal.BusinessTypeID = !angular.isNullorEmpty(response.data.AmendedBusinessType) ? response.data.AmendedBusinessType : response.data.BusinessTypeID;
                    //$scope.modal.BusinessType = !angular.isNullorEmpty(response.data.AmendedBusinessTypeDesc) ? response.data.AmendedBusinessTypeDesc : response.data.BusinessType;
                    $scope.modal.NameInHomeJurisdiction = !angular.isNullorEmpty(response.data.NewNameInHomeJurisdiction) ? response.data.NewNameInHomeJurisdiction : response.data.NameInHomeJurisdiction;
                    //$scope.modal.DBABusinessName = !angular.isNullorEmpty(response.data.NewDBABusinessName) ? response.data.NewDBABusinessName : response.data.DBABusinessName;
                    calcDuration(); // calcDuration method is available in this controller only.

                    if ($scope.modal.DurationYears > 0) {
                        $scope.modal.DurationExpireDate = "";
                    }
                    $scope.modal.PeriodofDurationDate = (wacorpService.dateFormatService($scope.modal.PeriodofDurationDate) != null || wacorpService.dateFormatService($scope.modal.PeriodofDurationDate) == "") ? $scope.modal.PeriodofDurationDate : $scope.modal.DurationExpireDate;

                    $scope.modal.IsAmendmentDurationChange = angular.isNullorEmpty($scope.modal.IsAmendmentDurationChange) ? false : $scope.modal.IsAmendmentDurationChange; //Is Entity Type Radio button
                    $scope.currentbusinesstypeid = $scope.modal.BusinessTypeID;
                    $scope.modal.OldBusinessTypeID = $scope.currentbusinesstypeid;
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.EffectiveDateType = $scope.modal.EffectiveDateType || "DateOfFiling";
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
                    $scope.modal.DateOfFormationInHomeJurisdiction = $scope.modal.DateOfFormationInHomeJurisdiction == "0001-01-01T00:00:00" ? "" : wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);
                    $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertStringToObject($scope.modal.NatureOfBusiness.NAICSCode);
                    $scope.modal.NatureOfBusiness.IsOtherNAICS = !angular.isNullorEmpty($scope.modal.NatureOfBusiness.OtherDescription) ? true : false;
                    $scope.modal.NatureOfBusiness.BusinessID = $scope.modal.BusinessID;
                   
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                    $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
                    $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0 || $scope.modal.JurisdictionCountry == "") ? usaCode : $scope.modal.JurisdictionCountry.toString();
                    $scope.modal.JurisdictionState = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0) ? null : $scope.modal.JurisdictionState.toString();
                    $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;

                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;

                    $scope.ExpireDate = (wacorpService.dateFormatService($scope.modal.DurationExpireDate) == '01/01/1970'
                                   || wacorpService.dateFormatService($scope.modal.DurationExpireDate) == null)
                                   ? 'PERPETUAL' : $scope.modal.DurationExpireDate;
                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;

                    $scope.amendmentEntityType = {
                        Key: angular.isNullorEmpty($scope.modal.AmendedBusinessType) ? "" : $scope.modal.AmendedBusinessType,
                        Value: angular.isNullorEmpty($scope.modal.AmendedBusinessTypeDesc) ? "" : $scope.modal.AmendedBusinessTypeDesc
                    }

                    $scope.modal.NewBusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
                    $scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
                    $scope.modal.OldBusinessName = !angular.isNullorEmpty($scope.modal.OldBusinessName) ? $scope.modal.OldBusinessName : $scope.modal.BusinessName;

                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                    $scope.modal.NewDBABusinessName = !angular.isNullorEmpty($scope.modal.NewDBABusinessName) ? $scope.modal.NewDBABusinessName: $scope.modal.DBABusinessName;
                    $scope.modal.DBABusinessName = !angular.isNullorEmpty($scope.modal.NewDBABusinessName) ? $scope.modal.NewDBABusinessName: $scope.modal.DBABusinessName;
                   
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    //$scope.modal.BINAICSCodeDesc=!angular.isNullorEmpty($scope.modal.BINAICSCodeDesc)?$scope.modal.BINAICSCodeDesc.replace(/&amp;/g, '&'):"";
                    //$scope.modal.BINAICSCodeDesc = !angular.isNullorEmpty($scope.modal.BIOtherDescription)?$scope.modal.BINAICSCodeDesc+','+$scope.modal.BIOtherDescription:$scope.modal.BINAICSCodeDesc;
                    // Copy old Entity Data
                    if (!$scope.modal.oldAmendmentEntity) {
                        $scope.modal.oldAmendmentEntity = {};
                        angular.copy($scope.modal, $scope.modal.oldAmendmentEntity);// Copy old Entity Data
                    }

                }
                $scope.currentBusiness = angular.copy($scope.modal);
                $scope.getEntityTypes($scope.currentBusiness.BusinessType);
                $scope.isShowReturnAddress = true;

                if ($scope.modal.IsActiveFilingExist) {
                    //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }
            }, function (response) { $scope.back(); });
        }
        else {
            $scope.modal = $rootScope.modal;
            $scope.modal.DateOfFormationInHomeJurisdiction= $scope.modal.DateOfFormationInHomeJurisdiction == "0001-01-01T00:00:00" ? "" : wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);
            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode.split(',');
            }
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = "";

            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            //$scope.currentBusiness = $rootScope.currentBusiness;
            if (typeof $rootScope.currentBusiness == typeof undefined) {
                $rootScope.currentBusiness = angular.copy($scope.modal);
                $scope.currentBusiness = angular.copy($scope.modal);
            }
           
            $scope.getEntityTypes($rootScope.currentBusiness.BusinessType);
            calcDuration(); // calcDuration method is available in this controller only.

            //$scope.modal.NewBusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
            //$scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
            $scope.modal.OldBusinessName = !angular.isNullorEmpty($scope.modal.OldBusinessName) ? $scope.modal.OldBusinessName: $scope.modal.BusinessName;
            //$scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName: $scope.modal.DBABusinessName;

            $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
            $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
            //$scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0 || $scope.modal.JurisdictionState == "") ? usaCode : $scope.modal.JurisdictionCountry.toString();
            $scope.modal.JurisdictionState = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0) ? null : $scope.modal.JurisdictionState.toString();
            $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);

            // Copy old Entity Data
            if (!$scope.modal.oldAmendmentEntity) {
                $scope.modal.oldAmendmentEntity = {};
                angular.copy($scope.modal, $scope.modal.oldAmendmentEntity);// Copy old Entity Data
            }
            if ($scope.modal.DurationYears > 0) {
                $scope.modal.DurationExpireDate = "";
            }


            $scope.modal.PeriodofDurationDate = wacorpService.dateFormatService($scope.modal.PeriodofDurationDate);
            $scope.modal.DurationExpireDate = wacorpService.dateFormatService($scope.modal.DurationExpireDate);

            $scope.amendmentEntityType = {
                Key: angular.isNullorEmpty($scope.modal.AmendedBusinessType) ? "" : $scope.modal.AmendedBusinessType,
                Value: angular.isNullorEmpty($scope.modal.AmendedBusinessTypeDesc) ? "" : $scope.modal.AmendedBusinessTypeDesc
            }
            $scope.isShowReturnAddress = true;

            // OSOS ID--3192
            $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0) ? "" : $scope.modal.JurisdictionCountry.toString();

        }

    };
    
    $scope.differenceInDays = function (firstdate, seconddate) {
        var dt1 = firstdate.split('/'),
        dt2 = seconddate.split('/'),
        one = new Date(firstdate),
        two = new Date(seconddate);

        var millisecondsPerDay = 1000 * 60 * 60 * 24;
        var millisBetween = two.getTime() - one.getTime();
        var days = millisBetween / millisecondsPerDay;

        return Math.floor(days);
    };

    // back to annual report business serarch
    $scope.back = function () {
        //$location.path('/AmendmentofForiegnRegistrationStatement/BusinessSearch');
        $location.path('/BusinessAmendmentIndex');
    };

    $scope.changeEntityType = function () {
        var businesstypeid = angular.isNullorEmpty($scope.amendmentEntityType) ? $scope.modal.oldAmendmentEntity.BusinessTypeID : $scope.amendmentEntityType.Key;
        //var businesstype = angular.isNullorEmpty($scope.amendmentEntityType) ? $scope.currentBusiness.BusinessType : $scope.amendmentEntityType.Value;
        var data = { params: { businessTypeid: businesstypeid } };
        //var data = { params: {businessTypeid: $scope.amendmentEntityType.Key, businessType: $scope.amendmentEntityType.Value } };
        wacorpService.get(webservices.OnlineFiling.reloadwithNewBusinessType, data, function (response) {
            $scope.modal.Indicator = response.data.Indicator;
            $scope.modal.FilingType = response.data.FilingType;
            $scope.currentBusiness.BusinessTypeID = businesstypeid;
            //$scope.currentBusiness.BusinessType = businesstype;
            $scope.modal.BusinessTransaction.BusinessTypeID = businesstypeid;
            if (businesstypeid != 0) {
                $scope.modal.IsAmendmentEntityNameChange = true;
                // Check indicators Validation
                if ($scope.modal.DBABusinessName)
                    $scope.$broadcast('isDBAValid'); //To check DBA name contains valid indicator in DBA directive.
                else
                    $scope.modal.isValidIndicator(null, $scope.modal.Indicator);
            }
        },
        function (error) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);  
        });

    }
    
    // validate & continue Amendment of Foriegn Registration Statement for review
    $scope.Review = function (amendmentBusinessForm) {
        //OSOS ID--2851 Business Amendments - available for any entity status
        //if (["Active"].indexOf($scope.modal.BusinessStatus) < 0) {
        //    wacorpService.alertDialog($scope.messages.AmendmentOfForiegnRegistrationStmt.ActiveStatus);
        //    return;
        //}
        var indicatorFlag = false;

        if ($scope.modal.IsDBASectionExist && $scope.modal.DBABusinessName && $scope.modal.invalidDBAIndicator)
        {
            $scope.modal.IsDBAInUse = true;
        }
      
        if (!$scope.modal.IsDBAInUse && $scope.modal.DBABusinessName == null && $scope.modal.DBABusinessName == '')
            indicatorFlag = wacorpService.isIndicatorValid($scope.modal) ? true : false;

        $scope.validateErrorMessage = true;
        $scope.validateAgentErrors = $scope.modal.Agent.IsNewAgent ? true : ($scope.modal.Agent.IsAgentEdit ? true : false);
        $scope.validateOneAgent = $scope.modal.Agent.AgentID == 0 && !$scope.modal.Agent.IsNewAgent;

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[amendmentBusinessForm]);

        var datediff = $scope.modal.DateOfFormationInHomeJurisdiction ==null|| $scope.modal.DateOfFormationInHomeJurisdiction == "" || $scope.modal.DateOfFormationInHomeJurisdiction == "01/01/0001" ? 0 : $scope.differenceInDays(wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction), wacorpService.dateFormatService(new Date()));

        var isUploadExistance = datediff < 60 ? (($scope.currentBusiness != null && ($scope.currentBusiness.Jurisdiction == $scope.modal.Jurisdiction))
                                         && ($scope.currentBusiness != null && ($scope.currentBusiness.BusinessName == $scope.modal.BusinessName))
                                         && ($scope.currentBusiness != null && ($scope.currentBusiness.BusinessType == $scope.modal.BusinessType))) : true;

        $scope.isUploadExistance = (!$scope.ScreenPart($scope.modal.AllScreenParts.PreparedAmendment, $scope.modal, $scope.modal.BusinessTypeID) || (isUploadExistance ? true : $rootScope.transactionID > 0 ? $scope.modal.UploadFileInfo.length > 0 :
                                   ($scope.currentBusiness != null && ($scope.modal.UploadFileInfo.length > $scope.currentBusiness.UploadFileInfo.length))));


        //// Check indicators Validation
        //if (!$scope.modal.IsNameReserved) {
        //    $scope.modal.isValidIndicator();
        //}

        //Entity Name
        var businessNameCount = $scope.availableBusinessCount();
        var isBusinessNameExists = $scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable);
        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);
      
        var indicator = wacorpService.isIndicatorValid($scope.modal);

        var isEntityValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EntityName, $scope.modal, $scope.modal.BusinessTypeID) ||
                             ($scope[amendmentBusinessForm].NewEntityName.$valid
                             && (($scope.modal.IsDBAInUse && $scope.modal.DBABusinessName != null && $scope.modal.DBABusinessName != '') ? (businessNameValid || $scope.modal.IsDBAInUse) : businessNameValid)
                             && ((!$scope.modal.IsNameReserved
                            //&& $scope.modal.isBusinessNameAvailable == ""
                             && indicator)
                            || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != "")))
                              );
        // OSOS ID-- 3070
        var isDBAValid = $scope.modal.IsAmendmentEntityNameChange ? (!$scope.modal.IsDBAInUse || ((!$scope.ScreenPart($scope.modal.AllScreenParts.DbaName, $scope.modal, $scope.modal.BusinessTypeID)
                                                                    || ($scope[amendmentBusinessForm].DBAName.$valid) && $scope.modal.isDBANameAvailable && $scope.modal.IsDBAInUse) || $scope.modal.IsNameReserved))
                                                                  : true;

        if ($scope.modal.IsDBAInUse && $scope.modal.DBABusinessName != null && $scope.modal.DBABusinessName != '' && $scope.modal.DBABusinessName != undefined) {
            $rootScope.$broadcast("checkDBAIndicator");//DBA Name Indicator

        }
        else if (!indicatorFlag) {
            $rootScope.$broadcast("checkIndicator");//Entity Name Indicator
        }


        //Name In Home Jurisdiction
        //var isNameInHomeJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.NameInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                    $scope[amendmentBusinessForm].NameInHomeJurisdictionForm.$valid);

        var isJurisdictionFormValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Jurisdiction, $scope.modal, $scope.modal.BusinessTypeID) ||
                                            $scope[amendmentBusinessForm].JurisdictionForm.$valid);

        //Duration
        var isDurationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Duration, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[amendmentBusinessForm].DurationForm.$valid);

        // principal office
        var isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                $scope[amendmentBusinessForm].PrincipalOffice.$valid);

            //$scope.modal.PrincipalOffice.IsOldDataExist ? (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
            //                                $scope[amendmentBusinessForm].PrincipalOffice.$valid) : true;
        // registered agent
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
                   ((!$scope.modal.Agent.IsNewAgent ? ($scope.modal.Agent.AgentID != 0 && $scope.modal.Agent.StreetAddress.FullAddress) ? true : (false && !$scope.modal.Agent.IsNoncommercialStreetAddress) : true) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 : true) && $scope[amendmentBusinessForm].RegisteredAgentForm.$valid));

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        $scope.modal.Agent.IsAmendmentAgentInfoChange = !isRegisteredAgentValidStates || $scope.modal.Agent.IsAmendmentAgentInfoChange ? true : false;
        $scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        $scope.checkRAStreetAddress = wacorpService.isRAStreetAddressValid($scope.modal.Agent.StreetAddress); //to check RA street address is valid or not

        $scope.validateNonCommercialStreetAddress = !isRegisteredAgentValid && !$scope.modal.Agent.IsNoncommercialStreetAddress && !$scope.checkRAStreetAddress ? true : false;

        //Governing Person 
        var isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount("GOVERNINGPERSON") > 0);

        //>Date of Formation in Home Jurisdiction
        //var isDOFHomeJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DateOfFormationInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID)
        //    || $scope[amendmentBusinessForm].DOFHomeJurisdiction.$valid);

       
        // Nature of business 
        var isNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusiness.IsOtherNAICS ? $scope.modal.NatureOfBusiness.NAICSCode.length > 0 : (!$scope.modal.NatureOfBusiness.IsOtherNAICS && $scope.modal.NatureOfBusiness.OtherDescription ? false : true)));

            //!($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0)));

        // Nature of business Non Profit
        var isNatureOfBusinessNonProfit = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusiness.IsOtherNAICS ? $scope.modal.NatureOfBusiness.NAICSCode.length > 0 : (!$scope.modal.NatureOfBusiness.IsOtherNAICS && $scope.modal.NatureOfBusiness.OtherDescription ? false : true)));

            //!($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0)));


        var isAuthorizedPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID) || $scope[amendmentBusinessForm].AuthorizedPersonForm.$valid);

        // Effective Date Valid
        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID) || $scope[amendmentBusinessForm].EffectiveDate.$valid);

        //This section is commented,so validation also removed
        //Upload Certificate Form
        //var isArticalUploadValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UploadCertificateOfExistence, $scope.modal, $scope.modal.BusinessTypeID)
        //    || $scope.modal.IsArticalsExist ? ($scope.modal.UploadFileInfo != null && $scope.modal.UploadFileInfo.length > 0) : true);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isCorrespondenceAddressValid = $scope[amendmentBusinessForm].CorrespondenceAddress.$valid;
        var isFormValid = isEntityValid && isJurisdictionFormValid && isPrincipalOfficeValid && isRegisteredAgentValid && isGoverningPersonValid
                            && isNatureOfBusiness && isNatureOfBusinessNonProfit && isAuthorizedPersonValid && isEffectiveDateValid && $scope.isUploadExistance && isAdditionalUploadValid && isCorrespondenceAddressValid && isDBAValid
        && !$scope.modal.invalidDBAIndicator && isRegisteredAgentValidStates; //&& isNameInHomeJurisdictionValid

        

        //&& isArticalUploadValid;
        if (isFormValid) {
            $scope.validateErrorMessage = false;
            $scope.validateAgentErrors = false;
            $scope.validateOneAgent = false;
            calcDuration(); // calcDuration method is available in this controller.
            $scope.modal.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalMailingAddress);
            $scope.modal.PrincipalOffice.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalStreetAddress);
            // Here JurisdictionCountry = 261 is United States.
            if ($scope.modal.JurisdictionCountry == 261) {
                var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
                var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.JurisdictionState);
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionState);
                $scope.modal.JurisdictionDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionStateDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
            }
            else {
                var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionCountry);
                $scope.modal.JurisdictionDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionStateDesc = null;
                $scope.modal.JurisdictionState = null;
            }
            $scope.modal.AmendedBusinessType = angular.isNullorEmpty($scope.amendmentEntityType) ? "" : $scope.amendmentEntityType.Key;
            $scope.modal.AmendedBusinessTypeDesc = angular.isNullorEmpty($scope.amendmentEntityType) ? "" : $scope.amendmentEntityType.Value;
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = new Date();
            $scope.modal.BusinessFiling.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.EffectiveDate;
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	            $scope.modal.IsEmailOptionChecked = false;
            }
            $rootScope.currentBusiness = $scope.currentBusiness;
            $scope.modal.OldBusinessTypeID = $scope.currentbusinesstypeid;
            $scope.modal.PeriodofDurationDate = $scope.modal.PeriodofDurationDate;
            if ($scope.modal.DurationYears > 0) {
                var d = new Date();
                var year = d.getFullYear() + parseInt($scope.modal.DurationYears);
                var month = d.getMonth();
                var day = d.getDate();
                $scope.modal.DurationExpireDate = new Date(year, month, day)
            }
            $rootScope.modal = $scope.modal;
            $location.path('/AmendmentofForiegnRegistrationStatementReview');
        }
        else {
            if (!isEntityValid) {
                $scope.modal.IsAmendmentEntityNameChange = true;
            }
            else if (isEntityValid && !isDBAValid && $scope.modal.DBABusinessName != '') {
                $scope.modal.IsAmendmentEntityNameChange = $scope.modal.isBusinessNameAvailable ? false : true;
            }
            else if (isEntityValid && $scope.modal.isBusinessNameAvailable == '') {
                $scope.modal.IsAmendmentEntityNameChange = true;
            }

            //if (isBusinessNameExists && !isEntityValid && !$scope.modal.IsDBAInUse) {
            //    setTimeout(function () {
            //        $("#txtBusiessName").trigger("blur");
            //    }, 500);
            //    //return false;
            //}
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }

    };




    $scope.selectedJurisdiction = function (items, selectedVal) {
        var result = "";
        angular.forEach(items, function (item) {
            if (selectedVal == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    // get business entity types list for amendment
    $scope.getEntityTypes = function (entityname) {
        
        var config = { params: { name: entityname } };
        // getLookUpDataForAmendment method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpDataForAmendment, config, function (response) {
            
            if (response.data.length > 0) {
                $scope.amendmentEntityTypes = response.data;
                $scope.setEntityType(response.data);
                $scope.IsAmendEntityTypeShow = true;
            }
            else {
                $scope.IsAmendEntityTypeShow = false;
            }
        }, function (error) {
            wacorpService.alertDialog(error.data);
        });
    };

    $scope.setEntityType = function (items) {
        if (!angular.isNullorEmpty($scope.modal.BusinessType)) {
            angular.forEach(items, function (item) {
                if ($scope.modal.AmendedBusinessTypeDesc == item.Value) {
                    $scope.amendmentEntityType = item;
                }
            });
        }
    }

    // check duration mode
    $scope.IsPerpetual = function (obj) {
        if (obj == 'rdoDureationDate') {
            $scope.modal.IsPerpetual = false;
            //$scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
        else if (obj == 'rdoDurationYear') {
            $scope.modal.IsPerpetual = false;
            $scope.modal.DurationExpireDate = null;
        }
        else {
            $scope.modal.IsPerpetual = true;
            $scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
    }

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };

    //  check whether form is valid / not
    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    // validate principals count
    //$scope.principalsCount = function (baseType) {
    //    var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
    //        return (principal.Status != principalStatus.DELETE);
    //    });
    //    return principalsList.length;
    //};

    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };


    // validate principals count
    $scope.uploadFilesCount = function (baseType, uploadList) {
        var uploadFilesList = uploadList.filter(function (uploadinfo) {
            return (uploadinfo.DocumentType == baseType);
        });
        return uploadFilesList.length;
    };

    //duration calculation
    function calcDuration() {
        $scope.modal.DurationYears = $scope.modal.DurationYears == 0 ? null : $scope.modal.DurationYears;

        $scope.modal.DurationExpireDate = wacorpService.dateFormatService($scope.modal.DurationExpireDate);

        if ($scope.modal.DurationYears > 0) {
            $scope.modal.DurationType = "rdoDureationYears";
        }
        else if ($scope.modal.DurationExpireDate != null) {
            $scope.modal.DurationType = "rdoDureationDate";
        }
        else{
            $scope.DurationType = "rdoPerpetual";
        }
        //To set duration expire date 
        if ($scope.modal.DurationType == 'rdoDureationDate') {
            $scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? null : $scope.modal.DurationExpireDate;
        } else {
            $scope.modal.DurationExpireDate = null;
        }
        $scope.DurationType = ($scope.modal.DurationYears == null && ($scope.modal.DurationExpireDate == null || $scope.modal.DurationExpireDate == "")) && $scope.modal.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
        if ($scope.DurationType == 'rdoPerpetual') {
            $scope.modal.IsPerpetual = true;
        }
        else {
            $scope.modal.IsPerpetual = false;// Assigning values to model
        }
        $scope.modal.DurationType = $scope.DurationType;// Assigning values to model
    }

    $scope.clearOtherDescription = function () {
        $scope.modal.NatureOfBusiness.OtherDescription = null;
    }

    $scope.CountryChangeDesc = function () {
        $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
         
        //if ($scope.modal.JurisdictionCountryDesc == "" || $scope.modal.JurisdictionCountryDesc == null || $scope.modal.JurisdictionCountryDesc == undefined)
        //    $scope.modal.JurisdictionCountryDesc = null;
        //};
    }

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0))
    }

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.AmendedBusinessType = angular.isNullorEmpty($scope.amendmentEntityType) ? "" : $scope.amendmentEntityType.Key;
        $scope.modal.AmendedBusinessTypeDesc = angular.isNullorEmpty($scope.amendmentEntityType) ? "" : $scope.amendmentEntityType.Value;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.NewBusinessName = $scope.modal.BusinessName;
        $scope.modal.NewDBABusinessName = $scope.modal.DBABusinessName;

        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/AmendmentofForiegnRegistrationStatement';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }

        $scope.modal.NatureOfBusiness.IsOtherNAICS = !angular.isNullorEmpty($scope.modal.NatureOfBusiness.OtherDescription) ? true : false;// Is Other NAICS check box in Nature Of Business Condition
        $scope.modal.NatureOfBusiness.BusinessID = $scope.modal.BusinessID;
        // Here JurisdictionCountry = 261 is United States.
        if ($scope.modal.JurisdictionCountry == 261) {
            var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
            var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.JurisdictionState);
            $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionState);
            $scope.modal.JurisdictionDesc = angular.copy(stateDesc);
            $scope.modal.JurisdictionStateDesc = angular.copy(stateDesc);
            $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
        }
        else {
            var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
            $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionCountry);
            $scope.modal.JurisdictionDesc = angular.copy(countryDesc);
            $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
            $scope.modal.JurisdictionStateDesc = null;
            $scope.modal.JurisdictionState = null;
        }
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

    angular.copy($scope.modal, $scope.modelDraft);
    var index = 0;
    angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
        $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
        index++;
    });

    index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
        $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
        index++;
        });
        // AmendmentSaveAsDraft method is available in constants.js
    wacorpService.post(webservices.OnlineFiling.AmendmentSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
        }
        $scope.modal.OnlineCartDraftID = response.data.ID;
        //$rootScope.BusinessType = null;
        if (iscloseDraft) {
            $location.path('/Dashboard');
        }
        else {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
        }
    }, function (response) {
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.alertDialog(response.data);
    });
}

    //Amendment Entity Type Change Radio button change click
    $scope.isFAmendmentEntityTypeChange = function (value) {
        $scope.modal.removeErrorMessage = false;
        // No radio button Click
        if (!value) {
            if ($scope.amendmentEntityType != null) {
                $scope.amendmentEntityType = null;
                var businesstypeid = $scope.modal.oldAmendmentEntity.BusinessTypeID
                //var businesstypeid = angular.isNullorEmpty($scope.amendmentEntityType) ? $scope.currentBusiness.BusinessTypeID : $scope.amendmentEntityType.Key;
                var data = { params: { businessTypeid: businesstypeid } };
                // reloadwithNewBusinessType method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.reloadwithNewBusinessType, data, function (response) {
                    $scope.modal.Indicator = response.data.Indicator;
                    $scope.modal.FilingType = response.data.FilingType;
                    $scope.modal.BusinessTypeID = businesstypeid;
                    $scope.modal.BusinessTransaction.BusinessTypeID = businesstypeid;
                    $scope.modal.IsAmendmentEntityNameChange = false;
                    $scope.modal.removeErrorMessage = true;
                    $scope.modal.BusinessName=$scope.modal.oldBusinessName;
                    if ($scope.modal.businessNames)
                    {
                        $scope.modal.businessNames.length = 0;
                    }
                    
                    $rootScope.$broadcast('onBusinessTypeChange');
                });
                $scope.modal.IsAmendmentEntityType = false;
                //
            }
        }
        // Yes radio button Click
        else {
            $scope.modal.IsAmendmentEntityType = true;
        }
    };

    //Amendment Duration Change Radio button change click
    $scope.isFAmendmentDurationChange = function (value) {
        // No radio button Click
        if (!value) {
            $scope.modal.DurationYears = $scope.modal.oldAmendmentEntity.DurationYears == 0 ? null : $scope.modal.oldAmendmentEntity.DurationYears;
            $scope.modal.DurationExpireDate = $scope.modal.oldAmendmentEntity.DurationExpireDate == "0001-01-01T00:00:00" ? null : wacorpService.dateFormatService($scope.modal.oldAmendmentEntity.DurationExpireDate);
            $scope.DurationType = ($scope.modal.oldAmendmentEntity.DurationYears == null && ($scope.modal.oldAmendmentEntity.DurationExpireDate == null || $scope.modal.oldAmendmentEntity.DurationExpireDate == "")) && $scope.modal.oldAmendmentEntity.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.oldAmendmentEntity.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.oldAmendmentEntity.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
            if ($scope.DurationType == 'rdoPerpetual') {
                $scope.modal.IsPerpetual = true;
            }
            else {
                $scope.modal.IsPerpetual = false;// Assigning values to model
            }
            $scope.modal.DurationType = $scope.DurationType;// Assigning values to model
            $scope.modal.IsAmendmentDurationChange = false;
        }
        // Yes radio button Click
        else {
            $scope.modal.IsAmendmentDurationChange = true;
        }
    };

    // check business count availability
    $scope.availableBusinessCount = function () {

        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {

            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };


    var businessNameNo = $scope.$on("isFAmendmentEntityTypeChange", function (event,data) {
        $scope.isFAmendmentEntityTypeChange(data);
    });

    $scope.$on('$destroy', function () {
        businessNameNo(); // businessNameNo method is available in this controller only.
    });

});
wacorpApp.controller('amendmentOfForiegnRegistrationStatementReviewController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService) {
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    $scope.businessLayout = "/ng-app/view/partial/BusinessInfoReview.html";
    //scope load
    $scope.Init = function () {
        $scope.modal = angular.copy($rootScope.modal);
        $scope.modal.oldAmendmentEntity = $scope.modal.oldAmendmentEntity;
        $scope.currentBusiness = angular.copy($rootScope.currentBusiness);
        getNaicsCodes(); // getNaicsCodes method is available in this controller only.
        getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in this controller only.
        $scope.ExpireDate = (wacorpService.dateFormatService($scope.modal.DurationExpireDate) == '01/01/1970'
                                   || wacorpService.dateFormatService($scope.modal.DurationExpireDate) == null)
                                   ? 'PERPETUAL' : $scope.modal.DurationExpireDate;
        $scope.IsAmendEntityTypeShow = true;
    }

    // add annual filing to cart 
    $scope.AddToCart = function () {
        
        $scope.modal.NewBusinessName = $scope.modal.BusinessName;
        $scope.modal.BusinessName = $scope.modal.oldAmendmentEntity.BusinessName;
        $scope.modal.OldBusinessName = $scope.modal.oldAmendmentEntity.BusinessName;

        $scope.modal.NewDBABusinessName = $scope.modal.DBABusinessName;
        $scope.modal.DBABusinessName = $scope.modal.oldAmendmentEntity.DBABusinessName;
        $scope.modal.OldDBABusinessName = $scope.modal.oldAmendmentEntity.DBABusinessName;

        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        var amendedData = angular.copy($scope.modal);
        amendedData.NatureOfBusiness.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusiness.NAICSCode);
        // AmendmentofForiegnRegStmtToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AmendmentofForiegnRegStmtToCart, amendedData, function (response) {
            
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $rootScope.currentBusiness = null;
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
            $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            $scope.modal = angular.copy($rootScope.modal);
            $scope.currentBusiness = angular.copy($rootScope.currentBusiness);
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

   // back to annual report flow
    $scope.back = function () {
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $rootScope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $location.path('/AmendmentofForiegnRegistrationStatement/' + $scope.modal.BusinessID);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    // get selected Naics Codes
    function getNaicsCodes() {
        var naicDesc = "";
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        naicDesc += (naicDesc == "" ? response.data[i].Value : (", " + response.data[i].Value));
                        break;
                    }
                }
            });
            $scope.modal.NatureOfBusiness.NAICSCodeDesc = naicDesc;
        });
    }

    // get selected Naics Codes for Non Profit
    function getNaicsCodesNonProfit() {
        var naicNonProfitDesc = "";
        lookupService.NaicsCodesNonProfit(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodesNonProfit.push(response.data[i]);
                        naicNonProfitDesc += (naicNonProfitDesc == "" ? response.data[i].Value : (", " + response.data[i].Value));
                        break;
                    }
                }
            });
            $scope.modal.NatureOfBusiness.NAICSCodeDesc = naicNonProfitDesc;
        });
    }

    //Add More Items functionality

    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        var amendedData = angular.copy($scope.modal);
        amendedData.NatureOfBusiness.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusiness.NAICSCode);
        
        // AmendmentofForiegnRegStmtToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AmendmentofForiegnRegStmtToCart, amendedData, function (response) {
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $rootScope.currentBusiness = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
                $location.path('/Dashboard');

        }, function (response) {
            $scope.modal = angular.copy($rootScope.modal);
            $scope.currentBusiness = angular.copy($rootScope.currentBusiness);
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});


wacorpApp.controller('registerAgentController', function ($scope) {
    //Principals Directive
    $scope.modalName = "Incorporator";
    $scope.sectionName = "Incorporator";
    $scope.Note = false;
    $scope.principalList = [];

    //Principal office
    $scope.principalOfficeSection = "Principal Place of Business";

    //Initial Board of director
    $scope.IBDmodalName = "IntialBoardofDirector";
    $scope.IBDsectionName = "Intial Board of Director";
    $scope.IBDprincipalList = [];

    $scope.submit = function (businessForm) {
        $scope.showAgentMessage = true;
        $scope.showPrincipalOfficeMessage = true;
        $scope.showPurposePowersMessage = true;
        $scope.showEntityErrorMessage = true;
        $scope.showUploadMessage = true;
        if ($scope[businessForm].PurposeAndPowers.$valid) {
            $scope.showAgentErrorMessage = false;
            $scope.showPrincipalOfficeMessage = false;
            $scope.showPurposePowersMessage = false;
            $scope.showEntityErrorMessage = false;
            $scope.showUploadMessage = false;
            // Folder Name: app Folder
            // Alert Name: Correct method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.businessForm.Correct);
        }
        else {
            // Folder Name: app Folder
            // Alert Name: Incorrect method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.businessForm.Incorrect);
        }
    };


    $scope.dropdownmodel = [];
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        scrollable: true,
        key: "Key",
        value: "Value",
        isKeyList: false
    };
    $scope.dropdowndata = [{ Key: "Alabama", Value: "AL" }, { Key: "Alaska", Value: "AK" }, { Key: "American Samoa", Value: "AS" },
                            { Key: "Arizona", Value: "AZ" }, { Key: "Arkansas", Value: "AR" }, { Key: "California", Value: "CA" }];


    $scope.countries = [{ country: "alabama", capital: "alabama" }, { country: "india", capital: "delhi" }];
});


// NOTE: Foreign Nonprofit formations disabled at line 232

wacorpApp.controller('indexController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {

    //$scope.getBusinessFilings = function () {
    //    var data = { params: { name: 'BusinessFilingType', TypeID: $scope.businesstype.Key } };
    //    wacorpService.get(webservices.OnlineFilingsLookup.OnBusinessFilingLookups, data, success, failure);
    //    function success(response) {
    //        $scope.filingTypes = response.data;
    //    }
    //    function failure(response) {
    //    }   
    //};

    $scope.messages = messages;
    $rootScope.FilingTypeID = $location.search().ID;
    $scope.gotoStep = function (step) {
        $scope.selection = step;
    };
    $scope.selection = "step1";

    //TFS 2626  TFS 2324 Default Values
    //$scope.isGrossRevenueNonProfitValid = true;
    var isGrossRevenueNonProfitValid = true;
    var isGrossRevenueNonProfitEnabled = false;
    $rootScope.IsGrossRevenueNonProfit = ($rootScope.IsGrossRevenueNonProfit != undefined ? $rootScope.IsGrossRevenueNonProfit : false);
    //TFS 2626 TFS 2324 

    $scope.init = function () {
        //if ($rootScope.data && $rootScope.data != "") {
        $scope.businessModel = $cookieStore.get('formationSearch', $scope.businessModel);
        $scope.businesstype = $cookieStore.get('formationSearchBusinessType', $scope.businesstype);
        $scope.businessModelEntity = $cookieStore.get('formationSearchCheckedType', $scope.businessModelEntity);
        $scope.getBusinessTypes($scope.businessModel); // getBusinessTypes method is available in this controller only.
        $scope.isGrossRevenueNonProfitValid = false;
        //}
    };

    $scope.getBusinessTypes = function (businessModel) {
        var ID = businessModel == codes.DOMESTIC ? businessTypeGroupIDs.DOMESTIC : businessTypeGroupIDs.FOREGIN;
        var data = { params: { name: searchTypes.BUSINESSTYPE, TypeID: ID } };
        // OnBusinessFilingLookups method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.OnBusinessFilingLookups, data, function (response) { $scope.businessTypes = response.data; }, function (response) { });
    };

    $scope.continueToFile = function (withIntialReport) {
        //TFS 2626 TFS 2324 
        $scope.showErrorMessage = false;
        if (isGrossRevenueNonProfitValid) {
            //TFS 2626 TFS 2324 
            if ($scope.businessModel == codes.DOMESTIC) {
                // I would like to file my initial report at a later time.  I acknowledge that an initial report is due within 120 days of the effective date of this formation per RCW 23.95.255. 
                if (withIntialReport) {
                    withIntialReport = false;
                }
                else {
                    withIntialReport = true;
                }

                var businessTypeID = $scope.businesstype.Key.split('`')[0];
                if ((businessTypeID == businessTypeIDs.WANONPROFITCORPORATION || businessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION || businessTypeID == businessTypeIDs.WALIMITEDLIABILITYPARTNERSHIP || businessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDLIABILITYPARTNERSHIP))
                    withIntialReport = false;
            }

            $scope.getNavigation(withIntialReport); // getNavigation method is available in this controller only.

            $cookieStore.put('formationSearch', $scope.businessModel);
            $cookieStore.put('formationSearchBusinessType', $scope.businesstype);
            $cookieStore.put('formationSearchCheckedType', $scope.businessModelEntity);
            //TFS 2626 TFS 2324 
        } else {
            $scope.showErrorMessage = true;
        };
        //TFS 2626 TFS 2324 
    };

    $scope.getNavigation = function (withinitialreport) {
        $rootScope.modal = null;
        $rootScope.BusinessTypeID = null;
        $rootScope.FilingTypeID = $location.search().ID;
        $rootScope.transactionID = null;
        $rootScope.BusinessTypeID = $scope.businesstype.Key.split('`')[0];
        $rootScope.BusinessTypeForFormation = $scope.businesstype.Key.split('`')[1];
        $rootScope.isFormationWithIR = withinitialreport;//&& $scope.selection == "step2";

        if ($scope.businessModel == 'D') {
            switch ($rootScope.BusinessTypeForFormation) {
                case 'C':
                    $location.path('/businessFormation');
                    break;
                case 'LLC':
                    $location.path('/LLCbusinessFormation');
                    break;
                case 'LLP':
                    $location.path('/LLPbusinessFormation');
                    break;
                default:
                    $location.path('/businessFormation');
            }
        }
        else {
            switch ($rootScope.BusinessTypeForFormation) {
                case 'C':
                    $location.path('/foreignbusinessFormation');
                    break;
                case 'LLC':
                    $location.path('/LLCforeignbusinessFormation');
                    break;
                case 'LLP':
                    $location.path('/LLPforeignbusinessFormation');
                    break;
                default:
                    $location.path('/foreignbusinessFormation');
            }
        }
    };

    // TFS 2626 TFS 2324 
    $scope.CheckIsGrossRevenueNonProfit = function () {
        $rootScope.IsGrossRevenueNonProfit = null;
        //$scope.isGrossRevenueNonProfitValid = false;
        isGrossRevenueNonProfitValid = false;
        $scope.isGrossRevenueNonProfitValid = false;

        if (isGrossRevenueNonProfitEnabled == true) {
            if ($('#rdoIsGrossRevenueNonProfitOver500K').is(':checked')) {
                $rootScope.IsGrossRevenueNonProfit = true;
                $scope.isGrossRevenueNonProfitValid = true;
                isGrossRevenueNonProfitValid = true;
            } else if ($('#rdoIsGrossRevenueNonProfitUnder500K').is(':checked')) {
                $rootScope.IsGrossRevenueNonProfit = false;
                $scope.isGrossRevenueNonProfitValid = true;
                isGrossRevenueNonProfitValid = true;
            } else {
                $rootScope.IsGrossRevenueNonProfit = false;
                $scope.isGrossRevenueNonProfitValid = false;
                isGrossRevenueNonProfitValid = false;
            };
        } else {
            isGrossRevenueNonProfitValid = true;
            $scope.isGrossRevenueNonProfitValid = true;
        };
    };

    $scope.CheckGrossRevenueNonProfit = function (businesstype) {
        //alert(businesstype);
        $rootScope.IsGrossRevenueNonProfit = null;
        $scope.IsGrossRevenueNonProfit = null;
        //$scope.isGrossRevenueNonProfitValid = true;
        isGrossRevenueNonProfitValid = true;
        isGrossRevenueNonProfitEnabled = false;
        isOnlineFilingDisabled = false;

        //Default Values Hide Divs
        if (typeof (document.getElementById("divIsGrossRevenueNonProfit")) !== 'undefined'
            && (document.getElementById("divIsGrossRevenueNonProfit")) !== null) {
            document.getElementById('divIsGrossRevenueNonProfit').style.display = "none";
        };

        //TFS 2514
        if (typeof (document.getElementById("divIsGrossRevenueNonProfitQuestion")) !== 'undefined'
            && (document.getElementById("divIsGrossRevenueNonProfitQuestion")) !== null) {
            document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = "none";
        };
        if (typeof (document.getElementById("divNonProfitOnlineDisable")) !== 'undefined'
            && (document.getElementById("divNonProfitOnlineDisable")) !== null) {
            document.getElementById('divNonProfitOnlineDisable').style.display = "none";
        };
        //TFS 2514

        if (businesstype != undefined) {
            if (businesstype.Value != null) {
                //clear Rdo buttons
                if (typeof (document.getElementById("rdoIsGrossRevenueNonProfitOver500K")) !== 'undefined'
                    && (document.getElementById("rdoIsGrossRevenueNonProfitOver500K")) !== null) {
                    document.getElementById("rdoIsGrossRevenueNonProfitOver500K").checked = false;
                };
                if (typeof (document.getElementById("rdoIsGrossRevenueNonProfitUnder500K")) !== 'undefined'
                    && (document.getElementById("rdoIsGrossRevenueNonProfitUnder500K")) !== null) {
                    document.getElementById("rdoIsGrossRevenueNonProfitUnder500K").checked = false;
                };
                //Check if visible
                if (businesstype.Value == "WA NONPROFIT CORPORATION"
                    || businesstype.Value == "WA NONPROFIT PROFESSIONAL SERVICE CORPORATION"
                    || businesstype.Value == "FOREIGN NONPROFIT CORPORATION"
                    || businesstype.Value == "FOREIGN NONPROFIT PROFESSIONAL SERVICE CORPORATION") {
                    isGrossRevenueNonProfitEnabled = true;
                } else {
                    isGrossRevenueNonProfitEnabled = false;
                };
            };
        };

        //check for disabled online filings
        if (
            //(disable online Express/One Click for NP)
                window.location.href.indexOf("expressAnnualReport") > -1
                || window.location.href.indexOf("oneClickAR") > -1) {
            isOnlineFilingDisabled = true;
        };

        //set visible
        if (isGrossRevenueNonProfitEnabled) {
            document.getElementById('divIsGrossRevenueNonProfit').style.display = "block";
            //TFS 2514 
            if (isOnlineFilingDisabled) {
                document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = "none";
                document.getElementById('divNonProfitOnlineDisable').style.display = "block";
            } else {
                document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = "block";
                document.getElementById('divNonProfitOnlineDisable').style.display = "none";
            };
            //TFS 2514
            $scope.isGrossRevenueNonProfitValid = false;
            isGrossRevenueNonProfitValid = false;
            //document.getElementById('btnContinue').disabled = true;  //TFS 2524 disable button default
        } else if (!isGrossRevenueNonProfitEnabled) {
            document.getElementById('divIsGrossRevenueNonProfit').style.display = "none";
            //TFS 2514 
            document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = "none";
            document.getElementById('divNonProfitOnlineDisable').style.display = "none";

            //TFS 2514
            $scope.isGrossRevenueNonProfitValid = true;
            isGrossRevenueNonProfitValid = true;
            //document.getElementById('btnContinue').disabled = false;  //TFS 2524 enable button default
        };

        $scope.CheckIsGrossRevenueNonProfit();

        if (businesstype != undefined) {
            if (businesstype.Key != null) {
                // Disable Foreign Nonprofit formations
                if (businesstype.Key.split('`')[0] == '26' || businesstype.Key.split('`')[0] == '27') {
                    document.getElementById('divNonProfitOnlineDisable').style.display = "block";
                    document.getElementById('divIsGrossRevenueNonProfitQuestion').style.display = "none";
                    };
            };
        };
    };

    $(document).ready(function () {
        //CheckGrossRevenueNonProfit($scope.businesstype);  //move this into businessSearch.js directive
        $scope.CheckGrossRevenueNonProfit($scope.businesstype);
        //$scope.CheckIsGrossRevenueNonProfit();

        let select = document.getElementById('BusinessEntityType');
        select.addEventListener('change', function () {
            if ($scope.businesstype != undefined) {
                //alert($scope.businesstype);
                //CheckGrossRevenueNonProfit($scope.businesstype)
                $scope.CheckGrossRevenueNonProfit($scope.businesstype)
                //$scope.CheckIsGrossRevenueNonProfit();
            };
        });
    });
    // TFS2626
});
wacorpApp.controller('BusinessFormationController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    /* declare scope variables */
    $scope.modal = {};
    $scope.NaicsCodes = [];
    $scope.validateErrorMessage = false;
    $scope.validateAgentErrors = false;
    $scope.principalsCount = 0;
    $scope.irPrincipalsCount = 0;
    $scope.validateOneAgent = false;
    $scope.isInitialBoardEntityName = false;
    $scope.isIncorporatorEntityName = false;

    // initialize the scope
    $scope.Init = function () {

        $scope.messages = messages;
        getNaicsCodes(); // getNaicsCodes method is available in this controller only.
        TaxExemptUploadShow(); // TaxExemptUploadShow method is available in this controller only.
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.modal = $rootScope.modal;
            //$scope.modal = $rootScope.modal;
            $scope.IsGrossRevenueNonProfit = $rootScope.modal.IsGrossRevenueNonProfit;//TFS 2628 Getting value from saved Json
        } else {
            $scope.IsGrossRevenueNonProfit = $rootScope.IsGrossRevenueNonProfit;//TFS 2628 getting value from business Search (index)
        };

        //get business information
        // here filingTypeID: 1 is ADJUSTMENTS - WAIVER GRANTED                           
        var data = { params: { businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 1, transactionID: $rootScope.transactionID, isWithIntialReport: $rootScope.isFormationWithIR } };  
        if ($rootScope.modal == null || $rootScope.modal == undefined
            || $scope.IsGrossRevenueNonProfit == null || $scope.IsGrossRevenueNonProfit == undefined) {  //TFS 2626
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $location.path('/businessFormationIndex');
            }
            // FormationCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.FormationCriteria, data, function (response) {
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                $scope.modal.DurationYears = ($scope.modal.DurationYears <= 0 || $scope.modal.DurationYears == undefined || $scope.modal.DurationYears == '0') ? '' : $scope.modal.DurationYears;
                $scope.modal.CorpAgent.AgentType = $scope.modal.CorpAgent.AgentType || "I";
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                calcDuration(); // calcDuration method is available in this controller only.
                TaxExemptUploadShow(); // TaxExemptUploadShow method is available in this controller only.
                $scope.modal.IsFormationWithIntialReport = $rootScope.isFormationWithIR || $scope.modal.IsFormationWithIntialReport;
                if ($scope.modal.IsFormationWithIntialReport)
                    $scope.modal.FormationWithInitialReport.AuthorizedPerson.PersonType = $scope.modal.FormationWithInitialReport.AuthorizedPerson.PersonType || "I";
                else
                    $scope.modal.CorpAuthorizedPerson.PersonType = $scope.modal.CorpAuthorizedPerson.PersonType || "I";
                $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode)) ? $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.split(','));
                //$scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.split(',');
                $scope.$watch(function () {
                    $scope.isRequired = ($scope.modal.IsCorporateSharesCommonStock || $scope.modal.IsCorporateSharesPreferedStock) ? false : true;
                });
                //$scope.validateOneAgent = $scope.modal.CorpAgent.AgentID == 0 && !$scope.modal.CorpAgent.IsNewAgent;
                $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                $scope.isShowReturnAddress = true;

                //TFS 2626 TFS 2324 
                if ($scope.modal.IsGrossRevenueNonProfit != null || $scope.modal.IsGrossRevenueNonProfit != undefined) {
                    $scope.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit;
                } else {
                    $scope.modal.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit;
                };
                if ($scope.modal.IsGrossRevenueNonProfit != null || $scope.modal.IsGrossRevenueNonProfit != undefined) {
                    $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit;
                } else {
                    $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit;
                }
                //TFS 2626 TFS 2324 

                //TFS 2324
                $scope.modal.IsCharitableNonProfit = $scope.modal.IsCharitableNonProfit != undefined ? $scope.modal.IsCharitableNonProfit : $scope.IsCharitableNonProfit
                $scope.modal.IsNonProfitExempt = $scope.modal.IsNonProfitExempt != undefined ? $scope.modal.IsNonProfitExempt : $scope.IsNonProfitExempt;
                $scope.modal.NonProfitReporting1 = $scope.modal.NonProfitReporting1 != undefined ? $scope.modal.NonProfitReporting1 : $scope.NonProfitReporting1;
                $scope.modal.NonProfitReporting2 = $scope.modal.NonProfitReporting2 != undefined ? $scope.modal.NonProfitReporting2 : $scope.NonProfitReporting2;
                $scope.modal.BusinessType = $scope.modal.BusinessType != undefined ? $scope.modal.BusinessType : $scope.BusinessType;
                //TFS 2324

            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
                $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode)) ? $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.split(','));
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = "";

            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);

            calcDuration(); // calcDuration method is available in this controller only.
            $scope.modal.isBusinessNameAvailable = true;
            $scope.modal.Indicator.IsValidEntityName = true;
            //OSOS--ID- 3163
            $scope.$watch(function () {
                $scope.isRequired = ($scope.modal.IsCorporateSharesCommonStock || $scope.modal.IsCorporateSharesPreferedStock) ? false : true;
            });
            $scope.isShowReturnAddress = true;

            //TFS 2626 TFS 2324 
            $scope.modal.IsGrossRevenueNonProfit = $scope.IsGrossRevenueNonProfit;
            $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit != undefined ? $scope.modal.IsGrossRevenueNonProfit : $scope.IsGrossRevenueNonProfit;
            //TFS 2626 TFS 2324 
        }
    }

    // validate the form submit for review
    $scope.Review = function (businessForm) {

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[businessForm]);

        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        $scope.modal.FormationWithInitialReport.PrincipalOffice.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.FormationWithInitialReport.PrincipalOffice.PrincipalStreetAddress);
        $scope.modal.FormationWithInitialReport.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.FormationWithInitialReport.PrincipalOffice.PrincipalMailingAddress);

        $scope.validateErrorMessage = true;
        var isUBILookup = true;
        var isDomesticUBI = true;
        var isForeignUBI = true;
        // UBI Number
        var isUBINumberValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UBINumber, $scope.modal, $scope.modal.businesstypeid) &&
                                $scope[businessForm].UBINumberForm.$valid);
        if (isUBINumberValid) {
            if ($rootScope.isLookUpClicked)
                $scope.isUbiLookUpClicked = true;
            else {
                $scope.isUbiLookUpClicked = false;
                if ($rootScope.isUseClicked)
                    $scope.isUseClicked = true;
                else
                    $scope.isUseClicked = false;
            }
        }
        else {
            if (!isUBINumberValid && $rootScope.isLookUpClicked || $rootScope.isUseClicked) {
                $scope.isUseClicked = true;
                $scope.isUbiLookUpClicked = true;
                $rootScope.$broadcast("checkUBIUse", $scope.modal.UBINumber);
            }
            else {
                $scope.isUseClicked = false;
                $scope.isUbiLookUpClicked = false;
            }
        }

        //Entity Name
        var businessNameCount = $scope.availableBusinessCount(); // availableBusinessCount method is available in this controller only.
        var isBusinessNameExists = $scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable);
        //var isBusinessNameExists = (!$scope.modal.IsNameReserved ? (($scope.modal.isBusinessNameAvailable == null || $scope.modal.isBusinessNameAvailable == undefined) ? true : $scope.modal.isBusinessNameAvailable) : true);
        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);
        if ($scope.modal.isValidUBI) {
            if ($scope.modal.entityList.length > 0) {
                //This is to check whether UBI is clicked or not
                var isUBILookup = (!$scope.modal.UBINumber || $scope.modal.UBINumber == $scope.modal.OnlineLookupUBINo);
                $scope.modal.OnlineIsUBIChecked = !isUBILookup;

                //This is to check UBI is domestic or foreign
                if ($scope.modal.BusinessType != null && $scope.modal.BusinessType.indexOf('WA ') > -1) {
                    // here UBIBusinessTypeID = 101 is Unregistered Corporations
                    var isDomesticUBI = ($scope[businessForm].UBINumberForm.$valid && $scope.modal.UBIBusinessTypeID == 101 ? true : false);
                    $scope.modal.IsDomesticUBI = !isDomesticUBI;
                }
                else {
                    // here BusinessCategoryID = 5 is FOREIGN ENTITY
                    var isForeignUBI = ($scope[businessForm].UBINumberForm.$valid && ($scope.modal.UBIBusinessTypeID == 101 || $scope.modal.BusinessCategoryID == 5) ? true : false);
                    $scope.modal.IsForeignUBI = !isForeignUBI;
                }
            }
        }

        var isEntityValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EntityName, $scope.modal, $scope.modal.BusinessTypeID) ||
                           ($scope[businessForm].EntityName.$valid
                           && businessNameValid
                           && ((!$scope.modal.IsNameReserved
                          // && (angular.isNullorEmpty($scope.modal.isBusinessNameAvailable))
                           && wacorpService.isIndicatorValid($scope.modal))
                           || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != "")))
                            );

        if (!wacorpService.isIndicatorValid($scope.modal)) {
            $rootScope.$broadcast("checkIndicator");
        }

        // registered agent
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true;
        }
        //TFS 1143

        $scope.validateAgentErrors = $scope.modal.CorpAgent.IsNewAgent;
        $scope.validateOneAgent = $scope.modal.CorpAgent.AgentID == 0 && !$scope.modal.CorpAgent.IsNewAgent;
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID)
            || (($scope[businessForm].RegisteredAgentForm != undefined
            && $scope[businessForm].RegisteredAgentForm != null
            && $scope[businessForm].RegisteredAgentForm.$valid)
            && (!$scope.modal.CorpAgent.IsNonCommercial ? $scope.modal.CorpAgent.StreetAddress.StreetAddress1 : true)
            && ($scope.modal.CorpAgent.IsNonCommercial ? $scope.validateAgentErrors : true)));

        var isRegisteredAgentValidStates = !$scope.modal.CorpAgent.StreetAddress.IsInvalidState && !$scope.modal.CorpAgent.MailingAddress.IsInvalidState && !$scope.modal.CorpAgent.StreetAddress.invalidPoBoxAddress;

        $scope.validateStreetAddress = !$scope.modal.CorpAgent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
        if (($scope.modal.CorpAgent.EmailAddress == "" || $scope.modal.CorpAgent.EmailAddress == null || $scope.modal.CorpAgent.EmailAddress == undefined)) {
            $scope.modal.IsEmailOptionChecked = false;
        }

        //TFS 2324
        //Charitable NonProfit Corp and Reporting Questions
        $scope.ValidateCharityNonProfitReporting =
            (
                (!$scope.ScreenPart($scope.modal.AllScreenParts.CharitableNonProfitReporting, $scope.modal, $scope.modal.BusinessTypeID))
                ||
                (
                    $scope.modal.isCharityAndReportingValid
                )
            );

        // PurposeAndPowers
        var isPurposeAndPowersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PurposeAndPowers, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        ($scope[businessForm].PurposeAndPowers.$valid));

        var isAttestationofSocialPurposeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AttestationOfSocialPurpose, $scope.modal, $scope.modal.BusinessTypeID)
                                                || $scope[businessForm].AttestationofSocialPurposeForm.$valid);

        var isArticalUploadValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UploadArticlesOfIncorporation, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope.modal.IsArticalsExist ? ($scope.modal.IsArticalsExist && $scope.modal.CorpUploadArticals != null && $scope.modal.CorpUploadArticals.length > 0) : true);

        //TFS 1068
        //Original Code
        //var _sharesRule1 = $scope.modal.IsArticalsExist ? true : ($scope.modal.ShareValues != '' && $scope.modal.ShareValues != null && parseInt($scope.modal.ShareValues) > 0);
        //Original Code

        var _sharesRule1 = false;
        if ($scope.modal.BusinessType.match("WA PROFESSIONAL SERVICE CORPORATION") ||
                    $scope.modal.BusinessType.match("WA SOCIAL PURPOSE CORPORATION") ||
                    $scope.modal.BusinessType.match("WA PROFIT CORPORATION")) {
            _sharesRule1 =
                //$scope.modal.IsArticalsExist && //These business types REQUIRE shares
                ($scope.modal.ShareValues != '' &&
                        $scope.modal.ShareValues != null &&
                        parseInt($scope.modal.ShareValues) > 0)
                    ? true
                    : false;
        } else if ($scope.modal.BusinessType.match("NONPROFIT")) {  //Profit Corp Has No Shares, Needs Articles of Incorp
            _sharesRule1 = isArticalUploadValid;  //valid if articles are valid
        }
        else {  //Original Code Check
            _sharesRule1 = $scope.modal.IsArticalsExist ? true :
                ($scope.modal.ShareValues != ''
                    && $scope.modal.ShareValues != null
                    && parseInt($scope.modal.ShareValues) > 0);
        }
        //TFS 1068

        //if Upload document for preffered stock is mandatory uncomment this code
        //var isPreferredStockUpload=($scope.modal.IsCorporateSharesPreferedStock ? ($scope.modal.CorpPreferredStokUploads != null && $scope.modal.CorpPreferredStokUploads.length > 0):true);

        var isCorporateSharesValid =
            (((!$scope.ScreenPart($scope.modal.AllScreenParts.CorporateShares_NewFormation,
                    $scope.modal,
                    $scope.modal.BusinessTypeID)) ||
                $scope[businessForm].CorporateShares.$valid)
                && _sharesRule1); //TFS 1068
        //&& isPreferredStockUpload;

        var isPurposeOfCorporationValid = ((!$scope.ScreenPart($scope.modal.AllScreenParts.PurposeOfCorporation, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].PurposeOfCorporationForm.$valid));

        //var isAnyOtherProvisionsValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AnyOtherProvisions, $scope.modal, $scope.modal.BusinessTypeID)
        //                                || $scope[businessForm].AnyOtherProvisionsForm.$valid);

        var isOtherProvisionsValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.OtherProvisions, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[businessForm].OtherProvisionsForm.$valid);

        var isDurationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Duration, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[businessForm].DurationForm.$valid);

        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[businessForm].EffectiveDate.$valid);

        //TFS 2672 TFS 2692 

        var isHasMemberNonProfitValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.HasMembers, $scope.modal, $scope.modal.BusinessTypeID)
                                      || (
                                            ($scope.modal.HasMemberNonProfit !== undefined) //
                                        //|| ($scope.HasMemberNonProfit)  //has members Yes selected
                                        //|| (!$scope.HasMemberNonProfit)
                                        )
                                      );  //has members no selected

        var isMemberNonProfitValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.HasMembers, $scope.modal, $scope.modal.BusinessTypeID)
                                      || ($scope.modal.HasMemberNonProfit === true)    //&& $scope.principalsCount("NonProfitMember") > 0)  //needs to be answered, does not need a member
                                      || ($scope.modal.HasMemberNonProfit === false));
        //TFS 2672 TFS 2692 

        //TFS 2628
        //Charitable NonProfit Corp and Reporting Questions
        var ValidateCharityNonProfitReporting = ((!$scope.ScreenPart($scope.modal.AllScreenParts.CharitableNonProfitReporting, $scope.modal, $scope.modal.BusinessTypeID))
                || ($scope.modal.isCharityAndReportingValid));

        var isInitialBoardOfDirectorsValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.InitialBoardOfDirectors, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope.principalsCount("InitialBoardOfDirector") > 0);

        var isIncorporatorValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Incorporator, $scope.modal, $scope.modal.BusinessTypeID)
                                      || $scope.principalsCount("Incorporator") > 0);

        var isAttestationOfStatedProfessionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AttestationOfStatedProfession, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[businessForm].AttestationOfStatedProfessionForm.$valid);

        var isRCWElectionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RCWElection, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[businessForm].RCWElectionForm.$valid);

        var isDistributionOfAssetsValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DistributionOfAssets, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[businessForm].DistributionOfAssetsForm.$valid);

        // TFS#2671; added
        var isIncorporatorSignatureAttestationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.IncorporatorSignatureAttestation, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[businessForm].IncorporatorSignatureAttestationForm.$valid);

        //var isNotInitialBoardEntityName = wacorpService.validateInitialBoardListWithEntityName($rootScope.NewEntityNameCleanUp) == false ? true : false;
        //$scope.isInitialBoardEntityName = isNotInitialBoardEntityName == false ? true : false;

        //var isNotIncorporatorEntityName = wacorpService.validateIncorporatorListWithEntityName($rootScope.NewEntityNameCleanUp) == false ? true : false;
        //$scope.isIncorporatorEntityName = isNotIncorporatorEntityName == false ? true : false;
        //var isIncorporatorSignatureConfirmation = (!$scope.ScreenPart($scope.modal.AllScreenParts.IsIncorporatorsSignatureConformation, $scope.modal, $scope.modal.BusinessTypeID)
        //                                || $scope.modal.IsIncorporatorsSignatureConformation);

        // with initial report
        if ($scope.modal.IsFormationWithIntialReport) {
            $scope.isPrincipalOfficeInWAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRPrincipalOfficeInWA, $scope.modal, $scope.modal.BusinessTypeID)
                                                || $scope[businessForm].PrincipalOffice.$valid);

            $scope.isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRGoverningPersons, $scope.modal, $scope.modal.BusinessTypeID)
                                            || $scope.irPrincipalsCount("GoverningPerson") > 0);

            $scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRNatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID)
                                                   || (!$scope.modal.FormationWithInitialReport.NatureOfBusiness.IsOtherNAICS ? $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.FormationWithInitialReport.NatureOfBusiness.IsOtherNAICS && !$scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription ? false : true)));
            //|| !($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription.length <= 0)));
        }
        else {
            $scope.isPrincipalOfficeInWAValid = true;
            $scope.isGoverningPersonValid = true;
            $scope.validateNatureOfBusiness = true;
        }

        var isAuthorizedPersonValidate = (!($scope.ScreenPart($scope.modal.AllScreenParts.AuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID) ||
                                           ($scope.ScreenPart($scope.modal.AllScreenParts.IRAuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID) && $scope.modal.IsFormationWithIntialReport)) ||
                                            $scope[businessForm].AuthorizedPersonForm.$valid);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist
            && $scope.modal.UploadDocumentsList != null
            && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        var isCorrespondenceAddressValid = $scope[businessForm].CorrespondenceAddress.$valid;
        var isFormValidate = isPurposeAndPowersValid
            && isRegisteredAgentValid
            && isAttestationofSocialPurposeValid
            && isArticalUploadValid
            && isDistributionOfAssetsValid
            && isOtherProvisionsValid
            && isCorporateSharesValid
            && isDurationValid
            && isEffectiveDateValid
            && isInitialBoardOfDirectorsValid
            && isIncorporatorValid
            && isAttestationOfStatedProfessionValid
            && isRCWElectionValid // TFS#2688; added RCW validation
            && isIncorporatorSignatureAttestationValid // TFS#2671/2324
            && isHasMemberNonProfitValid
            && isMemberNonProfitValid //TFS 2672
            && ValidateCharityNonProfitReporting  //TFS 2628
            && isAuthorizedPersonValidate
            && $scope.isPrincipalOfficeInWAValid
            && $scope.isGoverningPersonValid
            && $scope.validateNatureOfBusiness
            && isEntityValid
            && isPurposeOfCorporationValid
            && isAdditionalUploadValid
            && isUBILookup
            && isDomesticUBI
            && isForeignUBI
            && isRegisteredAgentValidStates
            && isCorrespondenceAddressValid
            && isUBINumberValid
            && !$scope.isUbiLookUpClicked
            && !$scope.isUseClicked;
        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            $scope.validateAgentErrors = false;
            $scope.validateOneAgent = false;
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = new Date();
            $rootScope.modal = $scope.modal;
            $location.path('/Review');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    //duration calculation
    function calcDuration() {
        $scope.modal.DurationYears = $scope.modal.DurationYears == 0 ? null : $scope.modal.DurationYears;
        //To set duration expire date 
        if ($scope.modal.DurationType == 'rdoDureationDate') {
            $scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? null : $scope.modal.DurationExpireDate;
        } else {
            $scope.modal.DurationExpireDate = null;
        }
        $scope.modal.DurationType = ($scope.modal.DurationYears == null && ($scope.modal.DurationExpireDate == null || $scope.modal.DurationExpireDate == "")) && $scope.modal.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
        if ($scope.modal.DurationType == 'rdoPerpetual') {
            $scope.modal.IsPerpetual = true;
        }
    }

    function TaxExemptUploadShow() {
        $scope.isTaxExemptUploadShow = $scope.modal.BusinessTypeID != businessTypeIDs.WAPROFITCORPORATION;
    };

    // lookup search
    $scope.searchBusinessNames = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                businessName: $scope.modal.BusinessName
            }
        };

        // GetBusinessNames method is available in constants.js
        wacorpService.get(webservices.Common.GetBusinessNames, config, function (response) {
            $scope.businessNames = response.data;
            $scope.searchlookupText = "Lookup";
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog('Failed');
            $scope.searchlookupText = "Lookup";
        });
    };

    // check business count availability
    $scope.availableBusinessCount = function () {

        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {
            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };

    // check duration mode
    $scope.IsPerpetual = function (obj) {
        if (obj == 'rdoDureationDate') {
            $scope.modal.IsPerpetual = false;
            //$scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
        else if (obj == 'rdoDureationYears') {
            $scope.modal.IsPerpetual = false;
            $scope.modal.DurationExpireDate = null;
        }
        else {
            $scope.modal.IsPerpetual = true;
            $scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
    }

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };

    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
        });
    }

    $scope.principalsCount = function (baseType) {

        //TFS 2692
        //Org code
        //var principalsList = $scope.modal.CorpPrincipalList.filter(function (principal) {   
        //    return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
        //});
        //return principalsList.length;
        //Org code

        //choosing list for partial
        switch (baseType) {
            case 'NonProfitMember':
                //alert("Switch Passed");  //TFS 2692 TESTING
                var principalsMembersList = $scope.modal.PrincipalMemberList.filter(function (principal) {
                    return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
                });
                return principalsMembersList.length;
                break;
            default:
                var principalsList = $scope.modal.CorpPrincipalList.filter(function (principal) {
                    return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
                });
                return principalsList.length;
        }
        //TFS 2692

        //return principalsList.length;
    };

    $scope.irPrincipalsCount = function (baseType) {
        //TFS 2672 TFS 2692  Org Code
        //var principalsList = $scope.modal.FormationWithInitialReport.PrincipalsList.filter(function (principal) {
        //    return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
        //});
        //return principalsList.length;
        //TFS 2672 TFS 2692  Org Code
        //choosing partial list
        switch (baseType) {
            case 'NonProfitMember':
                var principalsMembersList = $scope.modal.FormationWithInitialReport.PrincipalMemberList.filter(function (principal) {
                    return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
                });
                break;
            default:
                var principalsList = $scope.modal.FormationWithInitialReport.PrincipalsList.filter(function (principal) {
                    return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
                });
                break;
        }
        return principalsList.length;
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    $scope.clearOtherDescription = function () {
        $scope.modal.NatureOfBusiness.OtherDescription = null;
    }

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription.length <= 0))
    }

    $scope.checkOtherDescription = function () {
        if (!$scope.modal.FormationWithInitialReport.NatureOfBusiness.IsOtherNAICS) {
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription = null;
        }
    }

    function removLeadingZero(arr) {
        var result = "", clear = false;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] === "0") {
                if (i > 0) {
                    result += arr[i];
                } else {
                    clear = true;
                }
            } else {
                result += arr[i];
            }
        }
        return clear == true ? "" : result;
    }

    $scope.checkLeadingZero = function (txtDurationYears) {
        var item = txtDurationYears.replace(/^\s+|\s+$/g, '');
        var arr = item.split('');
        if (item === "0") {
            $scope.modal.DurationYears = "";
        }
        else if (arr.length > 0 && arr[0] === "0") {
            $scope.modal.DurationYears = removLeadingZero(arr);
        }
    };

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/businessFormation';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");
        $scope.modelDraft = {};

        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true;
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });

        // DomesticForamtionSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.DomesticForamtionSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode;
            }
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.removeCommas = function (value) {
        $scope.modal.ShareValues = $scope.modal.ShareValues != "0" && $scope.modal.ShareValues != "" ? $scope.modal.ShareValues.replace(",", "") : $scope.modal.ShareValues;
    }

    $scope.onlyNumbersPaste = function (value) {
        // TFS 3116 - only Numbers Paste
        $scope.modal.ShareValues = $scope.modal.ShareValues.replace(/\D/g, "");
    }
});
wacorpApp.controller('foreignbusinessFormationController', function ($scope, $location, $rootScope, lookupService, wacorpService, $timeout) {
    $scope.modal = {};
    $scope.CountriesList = [];
    $scope.StatesList = [];
    $scope.principalsCount = 0;
    $scope.NaicsCodes = [];
    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.CorpPrincipalList.filter(function (principal) {
            return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    var data = {
        params: {
            // here filingTypeID: 1 is ADJUSTMENTS - WAIVER GRANTED                           
            businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 1, transactionID: $rootScope.transactionID
        }
    };
    if ($rootScope.modal != null || $rootScope.modal != undefined) {
        $rootScope.modal = $rootScope.modal;
        //$scope.modal = $rootScope.modal;
    }

    if ($rootScope.modal == undefined || $rootScope.modal == null || $rootScope.modal == 'undefined' || $rootScope.modal == '') {
        // FormationCriteria method is available in constants.js
        wacorpService.get(webservices.OnlineFiling.FormationCriteria, data, function (response) {
            $scope.modal = response.data;
            $scope.modal.DurationYears = ($scope.modal.DurationYears <= 0 || $scope.modal.DurationYears == undefined || $scope.modal.DurationYears == '0') ? '' : $scope.modal.DurationYears;
            $scope.modal.IsPerpetual = !$scope.modal.IsPerpetual ? ($scope.modal.DurationYears == null && $scope.modal.DurationExpireDate == null) : $scope.modal.IsPerpetual;
            calcDuration(); // calcDuration method is available in this controller only.
            $scope.modal.CorpAgent.AgentType = $scope.modal.CorpAgent.AgentType || "I";
            $scope.modal.CorpAuthorizedPerson.PersonType = $scope.modal.CorpAuthorizedPerson.PersonType || "I";
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            $scope.modal.DateBeganDoingBusinessInWA = wacorpService.dateFormatService($scope.modal.DateBeganDoingBusinessInWA);
            $scope.modal.DateOfFormationInHomeJurisdiction = wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);

            $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
            $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
            $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
            $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0 || $scope.modal.JurisdictionCountry == "") ? usaCode : $scope.modal.JurisdictionCountry.toString();
            $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
            $scope.modal.JurisdictionState = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0) ? null : $scope.modal.JurisdictionState.toString();
            $scope.modal.CorpNatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.CorpNatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.CorpNatureOfBusiness.NAICSCode)) ? $scope.modal.CorpNatureOfBusiness.NAICSCode : $scope.modal.CorpNatureOfBusiness.NAICSCode.split(','));
            
            //$scope.modal.CorpNatureOfBusiness.NAICSCode = $scope.modal.CorpNatureOfBusiness.NAICSCode != null ? $scope.modal.CorpNatureOfBusiness.NAICSCode.split(',') : [];
            $scope.uploadFiles = [];
            if ($scope.modal.DateBeganDoingBusinessInWAType == null || $scope.modal.DateBeganDoingBusinessInWAType == undefined || $scope.modal.DateBeganDoingBusinessInWAType=="")
                 $scope.modal.DateBeganDoingBusinessInWAType = 'rdoDateBeganInWA';
            $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
            $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
            $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
            $scope.isShowReturnAddress = true;
        }, function (response) { });
    }
    else {
        $scope.modal = $rootScope.modal;
        if ($scope.modal.CorpNatureOfBusiness.NAICSCode != null && $scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.CorpNatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.CorpNatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.CorpNatureOfBusiness.NAICSCode)) ? $scope.modal.CorpNatureOfBusiness.NAICSCode : $scope.modal.CorpNatureOfBusiness.NAICSCode.split(','));
        }
        $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
        $scope.modal.DateBeganDoingBusinessInWA = wacorpService.dateFormatService($scope.modal.DateBeganDoingBusinessInWA);
        $scope.modal.DateOfFormationInHomeJurisdiction = wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);
        calcDuration(); // calcDuration method is available in this controller only.
        $scope.isShowReturnAddress = true;

        // OSOS ID--3192
        $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0) ? "" : $scope.modal.JurisdictionCountry.toString();

    }


    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    $scope.searchBusinessNames = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                businessName: $scope.modal.BusinessName
            }
        };
        // GetBusinessNames method is available in constants.js
        wacorpService.get(webservices.Common.GetBusinessNames, config, function (response) {
            $scope.businessNames = response.data;
            $scope.searchlookupText = "Lookup";
        }, function (response) { $scope.searchlookupText = "Lookup"; });
    };

    $scope.GetReservedBusiness = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                registrationID: parseInt($scope.NameReservedID)
            }
        };
        // GetReservedBusiness method is available in constants.js
        wacorpService.get(webservices.Common.GetReservedBusiness, config, function (response) {
            if (response.data.BusinessName != null)
                $scope.modal.BusinessName = response.data.BusinessName;
            else
                // Folder Name: app Folder
                // Alert Name: noReserverBusiness method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.BusinessFormation.noReserverBusiness);
        }, function (response) { });
    };

    $scope.isemptyCheckShowCommentsandNote = function () {
        return $scope.showComments && angular.isNullorEmpty($scope.model.Note);
    };

    // check business count availability
    $scope.availableBusinessCount = function () {
        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {

            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };

    $scope.Review = function (businessForm) {
        $scope.validateErrorMessage = true;
        var isUBILookup = true;
        var isDomesticUBI = true;
        var isForeignUBI = true;
        var indicatorFlag=false;
        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[businessForm]);
        if (!$scope.modal.IsDBAInUse &&( $scope.modal.DBABusinessName == null || $scope.modal.DBABusinessName == ''))
             indicatorFlag = wacorpService.isIndicatorValid($scope.modal) ? true : false;
        $scope.validateAgentErrors = $scope.modal.CorpAgent.IsNewAgent;
        $scope.validateOneAgent = $scope.modal.CorpAgent.AgentID == 0 && !$scope.modal.CorpAgent.IsNewAgent;
         
        // UBI Number
        var isubinumbervalid = (!$scope.ScreenPart($scope.modal.AllScreenParts.ubinumber, $scope.modal, $scope.modal.businesstypeid) &&
                                $scope[businessForm].UBINumberForm.$valid);
        if (isubinumbervalid) {
            if ($rootScope.isLookUpClicked)
                $scope.isUbiLookUpClicked = true;
            else {
                $scope.isUbiLookUpClicked = false;
                if ($rootScope.isUseClicked)
                    $scope.isUseClicked = true;
                else
                    $scope.isUseClicked = false;
            }
        }
        else {
            if (!isubinumbervalid && $rootScope.isLookUpClicked || $rootScope.isUseClicked) {
                $scope.isUseClicked = true;
                $scope.isUbiLookUpClicked = true;
                $rootScope.$broadcast("checkUBIUse", $scope.modal.UBINumber);
            }
            else {
                $scope.isUbiLookUpClicked = false;
                $scope.isUseClicked = false;
            }
        }
            
        //This is for UBI Look up

        if ($scope.modal.isValidUBI) {
            if ($scope.modal.entityList.length > 0) {
                //This is to check whether UBI is clicked or not
                var isUBILookup = (!$scope.modal.UBINumber || $scope.modal.UBINumber == $scope.modal.OnlineLookupUBINo);
                $scope.modal.OnlineIsUBIChecked = !isUBILookup;

                //This is to check UBI is domestic or foreign
                if ($scope.modal.BusinessType != null && $scope.modal.BusinessType.indexOf('WA ') > -1) {
                    // here UBIBusinessTypeID = 101 is Unregistered Corporations
                    var isDomesticUBI = ($scope[businessForm].UBINumberForm.$valid && $scope.modal.UBIBusinessTypeID == 101 ? true : false);
                    $scope.modal.IsDomesticUBI = !isDomesticUBI;
                }
                else {
                    // here BusinessCategoryID = 5 is FOREIGN ENTITY
                    var isForeignUBI = ($scope[businessForm].UBINumberForm.$valid && ($scope.modal.UBIBusinessTypeID == 101 || $scope.modal.BusinessCategoryID == 5) ? true : false);
                    $scope.modal.IsForeignUBI = !isForeignUBI;
                }
            }
        }

        //Entity Name
        var businessNameCount = $scope.availableBusinessCount();// availableBusinessCount method is available in this controller only.

        var isBusinessNameExists = $scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable);

        //var isBusinessNameExists = (!$scope.modal.IsNameReserved ? (($scope.modal.isBusinessNameAvailable == null || $scope.modal.isBusinessNameAvailable == undefined) ? true : $scope.modal.isBusinessNameAvailable) : true)

        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);
        var isEntityValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EntityName, $scope.modal, $scope.modal.BusinessTypeID) ||
                             ($scope[businessForm].EntityName.$valid
                              && (($scope.modal.IsDBAInUse && $scope.modal.DBABusinessName != null && $scope.modal.DBABusinessName != '') ? (businessNameValid || $scope.modal.IsDBAInUse) : businessNameValid)
                             && ((!$scope.modal.IsNameReserved
                             //&& (angular.isNullorEmpty($scope.modal.isBusinessNameAvailable))
                             && wacorpService.isIndicatorValid($scope.modal))
                             || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != ""))));
        if ($scope.modal.IsDBAInUse && ($scope.modal.DBABusinessName != null || $scope.modal.DBABusinessName != '' || $scope.modal.DBABusinessName != undefined)) {
            $rootScope.$broadcast("checkDBAIndicator");

            }
            else if (!indicatorFlag) {
                $rootScope.$broadcast("checkIndicator");
            }
        

        var isDBAValid = !$scope.modal.IsDBAInUse ||
                          (
                          (!$scope.ScreenPart($scope.modal.AllScreenParts.DbaName, $scope.modal, $scope.modal.BusinessTypeID)
                         || ($scope[businessForm].DBAName.$valid) && $scope.modal.isDBANameAvailable && $scope.modal.IsDBAInUse) || $scope.modal.IsNameReserved);

        //var isDBAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DbaName, $scope.modal, $scope.modal.BusinessTypeID)
        //                    || ($scope[businessForm].DBAName.$valid) && $scope.modal.isDBANameAvailable && $scope.modal.IsDBAInUse) || $scope.modal.IsNameReserved || $scope.modal.isBusinessNameAvailable;

        //Name In Home Jurisdiction   TFS ticket 11761
        //var isNameInHomeJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.NameInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                    $scope[businessForm].NameInHomeJurisdictionForm.$valid);

        var isJurisdictionFormValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Jurisdiction, $scope.modal, $scope.modal.BusinessTypeID) ||
                                            $scope[businessForm].JurisdictionForm.$valid);

        // principal office
        var isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
                                            $scope[businessForm].PrincipalOffice.$valid);

        // registered agent
        $scope.validateAgentErrors = $scope.modal.CorpAgent.IsNewAgent;
        $scope.validateOneAgent = $scope.modal.CorpAgent.AgentID == 0 && !$scope.modal.CorpAgent.IsNewAgent;
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
           (($scope[businessForm].RegisteredAgentForm.$valid) && (!$scope.modal.CorpAgent.IsNonCommercial ? $scope.modal.CorpAgent.StreetAddress.StreetAddress1 : true) && ($scope.modal.CorpAgent.IsNonCommercial ? $scope.validateAgentErrors : true)));

        var isRegisteredAgentValidStates = !$scope.modal.CorpAgent.StreetAddress.IsInvalidState && !$scope.modal.CorpAgent.MailingAddress.IsInvalidState && !$scope.modal.CorpAgent.StreetAddress.invalidPoBoxAddress;
        $scope.validateStreetAddress = !$scope.modal.CorpAgent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        //Governing Person 
        var isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount("GoverningPerson") > 0);

        //>Date of Formation in Home Jurisdiction
        var isDOFHomeJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DateOfFormationInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[businessForm].DOFHomeJurisdiction.$valid);

        var isDateBeganDBInWA = (!$scope.ScreenPart($scope.modal.AllScreenParts.DateBeganDoingBusinessInWA, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[businessForm].DateBeganDoingBusinessInWA.$valid);

        // Nature of business
        var isNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.CorpNatureOfBusiness.IsOtherNAICS ? $scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.CorpNatureOfBusiness.IsOtherNAICS && !$scope.modal.CorpNatureOfBusiness.OtherDescription ? false : true)));
        //($scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0 ||($scope.modal.CorpNatureOfBusiness.OtherDescription == null ? false : $scope.modal.CorpNatureOfBusiness.OtherDescription.length > 0)));

        var isNatureOfBusinessNonProfit = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.CorpNatureOfBusiness.IsOtherNAICS ? $scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.CorpNatureOfBusiness.IsOtherNAICS && !$scope.modal.CorpNatureOfBusiness.OtherDescription ? false : true)));

        //($scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0 ||
        //($scope.modal.CorpNatureOfBusiness.OtherDescription == null ? false : $scope.modal.CorpNatureOfBusiness.OtherDescription.length > 0)));

        // Duration
        var isDurationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Duration, $scope.modal, $scope.modal.BusinessTypeID)
                                      || $scope[businessForm].DurationForm.$valid);

        //Upload Certificate of Existence
        var isArticalUploadValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UploadCertificateOfExistence, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope.modal.IsArticalsExist && ($scope.modal.IsArticalsExist && $scope.modal.CorpUploadArticals != null
            && $scope.modal.CorpUploadArticals.length > constant.ZERO));

        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[businessForm].EffectiveDate.$valid);

        var isAuthorizedPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[businessForm].AuthorizedPersonForm.$valid);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null
            && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        var isCorrespondenceAddressValid = $scope[businessForm].CorrespondenceAddress.$valid;
        var isFormValid = isEntityValid && isJurisdictionFormValid && isPrincipalOfficeValid && isRegisteredAgentValid && isGoverningPersonValid
                             && isDOFHomeJurisdictionValid && isNatureOfBusiness && isDateBeganDBInWA && isNatureOfBusinessNonProfit && isArticalUploadValid && isEffectiveDateValid
                             && isAuthorizedPersonValid && isDurationValid && isAdditionalUploadValid && isUBILookup && isDomesticUBI && isCorrespondenceAddressValid && isForeignUBI && isDBAValid
                             && !$scope.modal.invalidDBAIndicator && isRegisteredAgentValidStates && isubinumbervalid && !$scope.isUbiLookUpClicked && !$scope.isUseClicked;

        //isNameInHomeJurisdictionValid && isUBINumberValid &&

        if (isFormValid) {
            $scope.validateErrorMessage = false;
            $scope.validateAgentErrors = false;
            $scope.validateOneAgent = false;
            $scope.modal.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalMailingAddress);
            $scope.modal.PrincipalOffice.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalStreetAddress);
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	            $scope.modal.IsEmailOptionChecked = false;
            }
            var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);

            if (countryDesc == $scope.unitedstates) {
                var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.JurisdictionState);
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionState);
                $scope.modal.JurisdictionDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionStateDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
            }
            else {
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionCountry);
                $scope.modal.JurisdictionDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionStateDesc = null;
            }
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = new Date();
            $rootScope.modal = $scope.modal;
            $location.path('/foreignReview');
        }
        else {
            //if (isBusinessNameExists && !isEntityValid && !$scope.modal.IsDBAInUse) {
            //    $timeout(function () {
            //        angular.element('#id-txtBusiessName').triggerHandler('blur');
            //    }, 300);
            //}
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };


    $scope.selectedJurisdiction = function (items, selectedVal) {
        var result = "";
        angular.forEach(items, function (item) {
            if (selectedVal == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }


    $scope.addYearsToCurrentDate = function () {
        var myDate = new Date();
        myDate.setFullYear(myDate.getFullYear() + parseInt($scope.modal.DurationYears));
        $scope.modal.DurationExpireDate = myDate;
    };
    $scope.selectBusiness = function (businessName) {
        $scope.modal.BusinessName = businessName;
    };
    $scope.CountryChangeDesc = function () {
        $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);

    };
    $scope.Init = function () {
        $scope.CountryChangeDesc(); // CountryChangeDesc method is available inthis controller only.
        $scope.messages = messages;
        $scope.unitedstates = "UNITED STATES";
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
        });
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            $scope.NaicsCodesNonProfit = response.data;
        });

        var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
            $scope.CountriesList = response.data;

            $timeout(function () {
                $("#id-JurisdictionCountry").val($scope.modal.JurisdictionCountry);
            }, 1000);

        }, function (response) {
        });

        var lookupStatesParams = { params: { name: 'ForeignJurisdictionStates' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
            $scope.StatesList = response.data;
            $timeout(function () {
                var state = $scope.modal.JurisdictionState;
                $("#id-JurisdictionState").val(state == 0 ? $scope.modal.JurisdictionState = state.toString().replace(0, "") : (state == null ? $scope.modal.JurisdictionState = "" : $scope.modal.JurisdictionState));
            }, 1000);

        }, function (response) {
        });

        if ($scope.modal.EffectiveDateType == 'DateOfFiling')
            $scope.modal.EffectiveDate = "";

        $scope.NaicsCodes = [];
        $scope.NaicsCodesNonProfit = [];
        $scope.validateErrorMessage = false;
        $scope.validateAgentErrors = false;
        $scope.validateOneAgent = false;
    }
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };

    //duration calculation
    function calcDuration() {
        $scope.modal.DurationYears = $scope.modal.DurationYears == 0 ? null : $scope.modal.DurationYears;
        //To set duration expire date 
        if ($scope.modal.DurationType == 'rdoDureationDate') {
            $scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? null : $scope.modal.DurationExpireDate;
        } else {
            $scope.modal.DurationExpireDate = null;
        }
        $scope.modal.DurationType = ($scope.modal.DurationYears == null && ($scope.modal.DurationExpireDate == null || $scope.modal.DurationExpireDate == "")) && $scope.modal.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
        if ($scope.modal.DurationType == 'rdoPerpetual') {
            $scope.modal.IsPerpetual = true;
        }
    }

    // check duration mode
    $scope.IsPerpetual = function (obj) {
        if (obj == 'rdoDureationDate') {
            $scope.modal.IsPerpetual = false;
            //$scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
        else if (obj == 'rdoDureationYears') {
            $scope.modal.IsPerpetual = false;
            $scope.modal.DurationExpireDate = null;
        }
        else {
            $scope.modal.IsPerpetual = true;
            $scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
    }

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.CorpNatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.CorpNatureOfBusiness.OtherDescription == null ? true : $scope.modal.CorpNatureOfBusiness.OtherDescription.length <= 0))
    }

    function removLeadingZero(arr) {
        var result = "", clear = false;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] === "0") {
                if (i > 0) {
                    result += arr[i];
                } else {
                    clear = true;
                }
            } else {
                result += arr[i];
            }
        }
        return clear == true ? "" : result;
    }

    $scope.checkLeadingZero = function (txtDurationYears) {
        var val = txtDurationYears.replace(/^\s+|\s+$/g, '');
        var arr = [];
        if (val === "0") {
            $scope.modal.DurationYears = "";
        } else {
            arr = val.split('');
        }
        if (arr.length > 0 && arr[0] === "0") {
            $scope.modal.DurationYears = removLeadingZero(arr);
        }
    };

    $scope.clearOtherDescription = function () {
        $scope.modal.CorpNatureOfBusiness.OtherDescription = null;
    }

    //to trim empty spaces for NOB Other
    $scope.validateOtherNOB = function () {
        $scope.modal.CorpNatureOfBusiness.OtherDescription = $scope.modal.CorpNatureOfBusiness.OtherDescription ? angular.copy($scope.modal.CorpNatureOfBusiness.OtherDescription.trim()) : (($scope.modal.CorpNatureOfBusiness.OtherDescription == undefined || $scope.modal.CorpNatureOfBusiness.OtherDescription == "") ? $scope.modal.CorpNatureOfBusiness.OtherDescription = null : $scope.modal.CorpNatureOfBusiness.OtherDescription);
    }

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/ /g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/foreignbusinessFormation';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.CorpNatureOfBusiness.NAICSCode != null && $scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.CorpNatureOfBusiness.NAICSCode = $scope.modal.CorpNatureOfBusiness.NAICSCode.join(",");
        }

        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // ForeignFormationSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.ForeignFormationSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.CorpNatureOfBusiness.NAICSCode != null && $scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.CorpNatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.CorpNatureOfBusiness.NAICSCode) ? [] : $scope.modal.CorpNatureOfBusiness.NAICSCode;
            }
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }
});

wacorpApp.controller('LLCbusinessFormationController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    $scope.modal = {};
    $scope.modal.businessNames = [];
    $scope.messages = messages;
    $scope.NaicsCodes = [];
    $scope.entityModal = '=';
    getNaicsCodes();
    $scope.review = false;
    $scope.validateErrorMessage = false;
    $scope.validateAgentErrors = false;
    $scope.validateOneAgent = false;
    $scope.isExecutorEntityName = false;
    $scope.modal.LLCAgent = {
        AgentID: 0, EntityName: null, FirstName: null, LastName: null, IsNonCommercial: false,
        EmailAddress: null, ConfirmEmailAddress: null, AgentType: "I", AgentTypeID: 0,
        StreetAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                FilerID: 0, UserID: 0, CreatedBy: 0,
                IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null
            },
            FullAddress: null, ID: 0, StreetAddress1: null, StreetAddress2: null, City: null, State: "WA", OtherState: null,
            Country: "USA", Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        MailingAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                FilerID: 0, UserID: 0,
                CreatedBy: 0, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null
            },
            FullAddress: null, ID: 0, StreetAddress1: null, StreetAddress2: null, City: null,
            State: "WA", OtherState: null, Country: "USA", Zip5: null, Zip4: null, PostalCode: null, County: 'USA',
            CountyName: null
        },
        IsUserRegisteredAgent: false, PhoneNumber: null, IsRegisteredAgentConsent: true, Title: null, IsSameAsMailingAddress: false, CreatedBy: null,//TFS 1143  original -> IsRegisteredAgentConsent: false
        AgentCreatdDate: null, AgentCreatdIP: null, IsNewAgent: false
    };


    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };
    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
        });
    }
    $scope.irPrincipalsCount = 0;
    $scope.irPrincipalsCount = function (baseType) {
        var principalsList = $scope.modal.FormationWithInitialReport.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };
    $scope.principalsCount = 0;
    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.LLCPrincipalList.filter(function (principal) {
            return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    $scope.modal.LLCPrincipalList = [];
    if ($rootScope.modal != null || $rootScope.modal != undefined) {
        $rootScope.modal = $rootScope.modal;
        //$scope.modal = $rootScope.modal;
    }

    var data = {
        params: {
            businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 1, transactionID: $rootScope.transactionID, isWithIntialReport: $rootScope.isFormationWithIR
        }
    };

    if ($rootScope.modal == undefined || $rootScope.modal == null || $rootScope.modal == 'undefined' || $rootScope.modal == '') {

        if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
            $location.path('/businessFormationIndex');
        }
        // LLCFormationCriteria method is available in constants.js
        wacorpService.get(webservices.OnlineFiling.LLCFormationCriteria, data, function (response) {

            $scope.modal = response.data;
            $scope.modal.DurationYears = ($scope.modal.DurationYears <= 0 || $scope.modal.DurationYears == undefined || $scope.modal.DurationYears == '0') ? '' : $scope.modal.DurationYears;
            //$scope.modal.DurationExpireDate = wacorpService.dateFormatService($scope.modal.DurationExpireDate);
            $scope.modal.IsFormationWithIntialReport = $rootScope.isFormationWithIR || $scope.modal.IsFormationWithIntialReport;
            $scope.businessTypeID = $rootScope.BusinessTypeID != null ? $rootScope.BusinessTypeID : $scope.modal.BusinessTypeID;
            $scope.filingTypeID = $rootScope.FilingTypeID;
            $scope.modal.LLCAgent.AgentType = $scope.modal.LLCAgent.AgentType || "I";
            $scope.modal.LLCAuthorizedPerson.PersonType = $scope.modal.LLCAuthorizedPerson.PersonType || "I";
            $scope.modal.FormationWithInitialReport.AuthorizedPerson.PersonType = $scope.modal.FormationWithInitialReport.AuthorizedPerson.PersonType || "I";
            $scope.review = false;
            calcDuration(); // calcDuration method is available in this controller only
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
            //$scope.showComments =true;
            $scope.modal.IsPerpetual = !$scope.modal.IsPerpetual ? ($scope.modal.DurationYears == null && $scope.modal.DurationExpireDate == null) : $scope.modal.IsPerpetual;
            $scope.uploadFiles = [];
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode)) ? $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.split(','));

            //$scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.split(',');
            $scope.$watch(function () {
                $scope.isRequired = ($scope.modal.IsCorporateSharesCommonStock || $scope.modal.IsCorporateSharesPreferedStock) ? false : true;
            });
            $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
            $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
            $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
            $scope.isShowReturnAddress = true;
        }, function (response) { });
    }
    else {
        $scope.modal = $rootScope.modal;
        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode)) ? $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.split(','));
        if ($scope.modal.EffectiveDateType == 'DateOfFiling')
            $scope.modal.EffectiveDate = "";
        //  $scope.principalList = $rootScope.modal.LLCPrincipalList;
        calcDuration(); // calcDuration method is available in this controller only.
        $scope.modal.isBusinessNameAvailable = true;
        $scope.modal.Indicator.IsValidEntityName = true;
        $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
        $scope.isShowReturnAddress = true;
    }
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    $scope.searchBusinessNames = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                businessName: $scope.modal.BusinessName
            }
        };
        // GetBusinessNames method is available in constants.js
        wacorpService.get(webservices.Common.GetBusinessNames, config, function (response) {
            $scope.businessNames = response.data;
            $scope.searchlookupText = "Lookup";
        }, function (response) { $scope.searchlookupText = "Lookup"; });
    };

    $scope.GetReservedBusiness = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                registrationID: parseInt($scope.NameReservedID)
            }
        };
        // GetReservedBusiness method is available in constants.js
        wacorpService.get(webservices.Common.GetReservedBusiness, config, function (response) {
            if (response.data.BusinessName != null)
                $scope.modal.BusinessName = response.data.BusinessName;
            else
                // Folder Name: app Folder
                // Alert Name: noReserverBusiness method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.BusinessFormation.noReserverBusiness);
        }, function (response) { });
    };

    $scope.isemptyCheckShowCommentsandNote = function () {
        return $scope.showComments && angular.isNullorEmpty($scope.model.Note);
    };

    // check business count availability
    $scope.availableBusinessCount = function () {
        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {

            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };

    $scope.Review = function (businessForm) {

        $scope.showEntityErrorMessage = true;
        $scope.validateErrorMessage = true;
        var isUBILookup = true;
        var isDomesticUBI = true;
        var isForeignUBI = true;


        //$rootScope.$broadcast('test');Geetha

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[businessForm]);
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        $scope.modal.PrincipalOffice.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalStreetAddress);
        $scope.modal.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalMailingAddress);
        // UBI Number
        var isUBINumberValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UBINumber, $scope.modal, $scope.modal.BusinessTypeID) &&
                                $scope[businessForm].UBINumberForm.$valid);

        if (isUBINumberValid) {
            if ($rootScope.isLookUpClicked)
                $scope.isUbiLookUpClicked = true;
            else {
                $scope.isUbiLookUpClicked = false;
                if ($rootScope.isUseClicked)
                    $scope.isUseClicked = true;
                else
                    $scope.isUseClicked = false;
            }
        }
        else {
            if (!isUBINumberValid && $rootScope.isLookUpClicked || $rootScope.isUseClicked)
            {
                $scope.isUseClicked = true;
                $scope.isUbiLookUpClicked = true;
                $rootScope.$broadcast("checkUBIUse",$scope.modal.UBINumber);
            }
            else {
                $scope.isUseClicked = false;
                $scope.isUbiLookUpClicked = false;
            }
        }

        //This is for UBI Look up
        if ($scope.modal.isValidUBI) {
            if ($scope.modal.entityList.length > 0) {
                //This is to check whether UBI is clicked or not
                var isUBILookup = (!$scope.modal.UBINumber || $scope.modal.UBINumber == $scope.modal.OnlineLookupUBINo);
                $scope.modal.OnlineIsUBIChecked = !isUBILookup;

                //This is to check UBI is domestic or foreign
                if ($scope.modal.BusinessType != null && $scope.modal.BusinessType.indexOf('WA ') > -1) {
                    // here UBIBusinessTypeID = 101 is Unregistered Corporations
                    var isDomesticUBI = ($scope[businessForm].UBINumberForm.$valid && $scope.modal.UBIBusinessTypeID == 101 ? true : false);
                    $scope.modal.IsDomesticUBI = !isDomesticUBI;
                }
                else {
                    // here BusinessCategoryID = 5 is FOREIGN ENTITY
                    var isForeignUBI = ($scope[businessForm].UBINumberForm.$valid && ($scope.modal.UBIBusinessTypeID == 101 || $scope.modal.BusinessCategoryID == 5) ? true : false);
                    $scope.modal.IsForeignUBI = !isForeignUBI;
                }
            }
        }

        //Entity Name
        var businessNameCount = $scope.availableBusinessCount();
        var isBusinessNameExists = $scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable);

        //var isBusinessNameExists = (!$scope.modal.IsNameReserved ? (($scope.modal.isBusinessNameAvailable == null || $scope.modal.isBusinessNameAvailable == undefined) ? true : $scope.modal.isBusinessNameAvailable) : true);

        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);
        var isEntityValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EntityName, $scope.modal, $scope.modal.BusinessTypeID) ||
                             ($scope[businessForm].EntityName.$valid
                             && businessNameValid
                             && ((!$scope.modal.IsNameReserved
                             //&& $scope.modal.isBusinessNameAvailable == ""
                             && wacorpService.isIndicatorValid($scope.modal))
                             || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != "")))
                              );

        if (!wacorpService.isIndicatorValid($scope.modal))
        {
            $rootScope.$broadcast("checkIndicator");
        }

        $scope.validateAgentErrors = $scope.modal.LLCAgent.IsNewAgent;
        $scope.validateOneAgent = $scope.modal.LLCAgent.AgentID == 0 && !$scope.modal.LLCAgent.IsNewAgent;

        //// PurposeAndPowers
        //var isPurposeAndPowersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PurposeAndPowers, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                ($scope[businessForm].CorpPurposeAndPowersEntity.$valid && $scope.modal.CorpPurposeAndPowersEntity.UploadArticals != null
        //                                && $scope.modal.CorpPurposeAndPowersEntity.UploadArticals.length > 0));

        // registered agent
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
            (($scope[businessForm].RegisteredAgentForm != undefined && $scope[businessForm].RegisteredAgentForm != null && $scope[businessForm].RegisteredAgentForm.$valid) && (!$scope.modal.LLCAgent.IsNonCommercial ? $scope.modal.LLCAgent.StreetAddress.StreetAddress1 : true) && ($scope.modal.LLCAgent.IsNonCommercial ? $scope.validateAgentErrors : true)));
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143


        //Please dont remove this comments
        //($scope[businessForm].RegisteredAgent.$valid)  --> this line of code is to validate the Textboxes Div
        //(!$scope.modal.LLCAgent.IsNonCommercial ? $scope.modal.LLCAgent.StreetAddress.StreetAddress1 != "" : true)  --> this line of code is when we have Commercial agent and didnt give addresss(this will bind to grid) street address will be empty becuase in Commerical RA Address is not manidatory
        //($scope.modal.LLCAgent.IsNonCommercial ? $scope.validateAgentErrors : true)  --> this line of code when we have Non Commercial RA and didnt enter any data in search(this is Basic search)

        var isRegisteredAgentValidStates = !$scope.modal.LLCAgent.StreetAddress.IsInvalidState && !$scope.modal.LLCAgent.MailingAddress.IsInvalidState && !$scope.modal.LLCAgent.StreetAddress.invalidPoBoxAddress && !$scope.modal.LLCAgent.StreetAddress.invalidPoBoxAddress;

        $scope.validateStreetAddress = !$scope.modal.LLCAgent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
        if (($scope.modal.LLCAgent.EmailAddress == "" || $scope.modal.LLCAgent.EmailAddress == null || $scope.modal.LLCAgent.EmailAddress == undefined)) {
	        // $rootScope.$broadcast('onEmailEmpty');
	        $scope.modal.IsEmailOptionChecked = false;
        }

        var isAttestationofSocialPurposeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AttestationOfSocialPurpose, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[businessForm].AttestationOfSocialPurpose.$valid);

        var isCertificateUploadValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UploadCertificateOfFormation, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope.modal.IsArticalsExist ? ($scope.modal.CertificateOfFormation != null && $scope.modal.CertificateOfFormation.length > 0) : true);

        var isCorporateSharesValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.CorporateShares_NewFormation, $scope.modal, $scope.modal.BusinessTypeID)
            //|| ($scope.modal.IsCorporateSharesPreferedStock ? ($scope.modal.PreferredStokUploads != null && $scope.modal.PreferredStokUploads.length > 0) : true)
            && $scope[businessForm].CorporateShares.$valid);

        var isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].PrincipalOffice.$valid);

        var isDurationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Duration, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].Duration.$valid);

        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].EffectiveDate.$valid);

        var isExecutorValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Executor, $scope.modal, $scope.modal.BusinessTypeID) ||
                                      $scope.principalsCount("Executor") > 0);

        var isPLLCAttestationFormValidate = $scope[businessForm].PLLCAttestationForm.$valid;
        var isCorrespondenceAddressValid = $scope[businessForm].CorrespondenceAddress.$valid;

        //var isNotExecutorEntityName = wacorpService.validateExecutorListWithEntityName($rootScope.NewEntityNameCleanUp) == false ? true : false;
        //$scope.isExecutorEntityName = isNotExecutorEntityName == false ? true : false;

        // with inital report
        if ($scope.modal.IsFormationWithIntialReport) {
            // principal office in wa
            $scope.isPrincipalOfficeInWAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRPrincipalOfficeInWA, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                $scope[businessForm].PrincipalOffice.$valid);
            // governing persons
            $scope.isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRGoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                            $scope.irPrincipalsCount("GoverningPerson") > 0);

            // nature of business
            //$scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRNatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
            //                                    $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0);
            $scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRNatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID)
                                               || (!$scope.modal.FormationWithInitialReport.NatureOfBusiness.IsOtherNAICS ? $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.FormationWithInitialReport.NatureOfBusiness.IsOtherNAICS && !$scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription ? false : true)));
            //!($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription.length <= 0)));
            $scope.isCorrespondenceAddress = $scope[businessForm].CorrespondenceAddress.$valid;
        }
        else {
            $scope.isPrincipalOfficeInWAValid = true;
            $scope.isGoverningPersonValid = true;
            $scope.validateNatureOfBusiness = true;
            $scope.isCorrespondenceAddressValid = true;

        }

        var isAuthorizedPersonValidate = (!($scope.ScreenPart($scope.modal.AllScreenParts.AuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID) ||
                                           ($scope.ScreenPart($scope.modal.AllScreenParts.IRAuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID) && $scope.modal.IsFormationWithIntialReport)) ||
                                            $scope[businessForm].AuthorizedPersonForm.$valid);
        // Bug Net Id: 71835
        var isOtherProvisionsValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.OtherProvisions, $scope.modal, $scope.modal.BusinessTypeID)
                                     || $scope[businessForm].OtherProvisionsForm.$valid);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isFormValidate = isRegisteredAgentValid && isAttestationofSocialPurposeValid && isCertificateUploadValid
                            && isCorporateSharesValid && isPrincipalOfficeValid && isDurationValid && isEffectiveDateValid && isExecutorValid
                            && isAuthorizedPersonValidate && isPLLCAttestationFormValidate && isEntityValid  
                            && $scope.isPrincipalOfficeInWAValid && $scope.isGoverningPersonValid && $scope.validateNatureOfBusiness && isOtherProvisionsValid && isAdditionalUploadValid
                            && isUBILookup && isDomesticUBI && isCorrespondenceAddressValid && isForeignUBI && isRegisteredAgentValidStates && !$scope.isUbiLookUpClicked && !$scope.isUseClicked;
        if (isFormValidate) {

            $scope.validateErrorMessage = false;
            $scope.validateAgentErrors = false;
            $scope.validateOneAgent = false;
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = new Date();
            $rootScope.modal = $scope.modal;
            $location.path('/LLCReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    $scope.isValidIndicator = function ($event) {

        var indicators = $scope.modal.Indicator.IndicatorsCSV;
        var isValid = 0;
        var obj = $event.currentTarget;

        var entityName;
        if (indicators != null && indicators != "null" && indicators != "NULL" && indicators != undefined && indicators != "undefined" && indicators != '') {
            if ($(obj).attr('data-isupdate') != undefined && $(obj).attr('data-isupdate') && $(obj).attr('data-isupdate') != "false" && $(obj).attr('data-isupdate') != "False") {
                entityName = $scope.modal.BusinessName + ' ' + $scope.modal.Indicator.IndicatorsCSV;
                entityName = entityName.toLowerCase().replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '');
            }
            else {
                entityName = $scope.modal.BusinessName.toLowerCase().replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '');
            }
            angular.forEach($scope.modal.Indicator.Indicators, function (value) {
                value = value.replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                isValid = new RegExp("^" + value + "\\s").test(entityName) ? isValid + 1 : isValid;
            });

            if (isValid == 0) {
                angular.forEach($scope.modal.Indicator.Indicators, function (value) {
                    value = value.replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                    isValid = new RegExp("\\s" + value + "\\s").test(entityName) ? isValid + 1 : isValid;
                });
            }
            if (isValid == 0) {
                angular.forEach($scope.modal.Indicator.Indicators, function (value) {
                    value = value.replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                    isValid = new RegExp("\\s" + value + "$").test(entityName) ? isValid + 1 : isValid;
                });
            }
        }
        else {
            isValid = 1; //For all entities we are not going to have Indicators, that's the reason default we are considering as true.
        }


        $scope.indicatorValidMessage = isValid > 0 ? "" : "The entity name requested does not contain the necessary designation. Please input one of the required designations (" + $(obj).attr('data-indicators') + ").";// TFS ID 12017
    };
    $scope.isValidEntityname = function ($event) {

        var obj = $event.currentTarget;
        return $(obj).attr('data-isnamevalid') == "true" || $(obj).attr('data-isnamevalid') == "True" ? "" : "Please perform an " + $(obj).attr('data-selectionName').toLowerCase() + " lookup to confirm that the desired entity name is valid and available.";// TFS ID 12015
    }

    $scope.IsPerpetual = function (obj) {
        if (obj == 'rdoDureationDate') {
            $scope.modal.IsPerpetual = false;
            //$scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
        else if (obj == 'rdoDureationYears') {
            $scope.modal.IsPerpetual = false;
            $scope.modal.DurationExpireDate = null;
        }
        else {
            $scope.modal.IsPerpetual = true;
            $scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
    }

    //$scope.addYearsToCurrentDate = function () {
    //    var myDate = new Date();
    //    myDate.setFullYear(myDate.getFullYear() + parseInt($scope.modal.DurationYears));
    //    $scope.modal.DurationExpireDate = myDate;
    //};

    $scope.selectBusiness = function (businessName) {
        $scope.modal.BusinessName = businessName;
    };
    //duration calculation
    function calcDuration() {
        $scope.modal.DurationYears = $scope.modal.DurationYears == 0 ? null : $scope.modal.DurationYears;

        //To set duration expire date
        if ($scope.modal.DurationType == 'rdoDureationDate') {
            $scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? null : $scope.modal.DurationExpireDate;
        } else {
            $scope.modal.DurationExpireDate = null;
        }

        $scope.modal.DurationType = ($scope.modal.DurationYears == null && ($scope.modal.DurationExpireDate == null || $scope.modal.DurationExpireDate == "")) && $scope.modal.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
        if ($scope.modal.DurationType == 'rdoPerpetual') {
            $scope.modal.IsPerpetual = true;
        }
    };

    $scope.clearOtherDescription = function () {
        $scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription = null;
    };

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription.length <= 0))
    }

    function removLeadingZero(arr) {
        var result = "", clear = false;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] === "0") {
                if (i > 0) {
                    result += arr[i];
                } else {
                    clear = true;
                }
            } else {
                result += arr[i];
            }
        }
        return clear == true ? "" : result;
    }

    $scope.checkLeadingZero = function (txtDurationYears) {
        var val = txtDurationYears.replace(/^\s+|\s+$/g, '');
        var arr = [];
        if (val === "0") {
            $scope.modal.DurationYears = "";
        } else {
            arr = val.split('');
        }
        if (arr.length > 0 && arr[0] === "0") {
            $scope.modal.DurationYears = removLeadingZero(arr);
        }
    };

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/ /g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/LLCbusinessFormation';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");
        }

        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // LLCFormationSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.LLCFormationSaveAsDraft, $scope.modelDraft, function (response) {

            if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode;
            }
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.removeCommas = function (value) {

        $scope.modal.ShareValues = $scope.modal.ShareValues != "0" && $scope.modal.ShareValues != "" ? $scope.modal.ShareValues.replace(",", "") : $scope.modal.ShareValues;
    }

    $scope.onlyNumbersPaste = function (value) {
        // TFS 3116 - only Numbers Paste
        $scope.modal.ShareValues =  $scope.modal.ShareValues.replace(/\D/g, "") ;
    }
});
wacorpApp.controller('LLCforeignbusinessFormationController', function ($scope, $location, $rootScope, lookupService, wacorpService, $filter, $timeout) {
    $scope.modal = {};
    $scope.CountriesList;
    $scope.StatesList;
    $scope.principalsCount = 0;
    $scope.NaicsCodes = [];

    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.LLCPrincipalList.filter(function (principal) {
            return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    $scope.Init = function () {
        $scope.unitedstates = "UNITED STATES";
        $scope.CountryChangeDesc(); // CountryChangeDesc method is available in this controller only.
        getNaicsCodes(); // getNaicsCodes method is available in this controller only.
        $scope.messages = messages;


        var lookupStatesParams = { params: { name: 'ForeignJurisdictionStates' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
            $scope.StatesList = response.data;
            //angular.copy(response.data, $scope.StatesList);
            $timeout(function () {
                var state = $scope.modal.JurisdictionState;
                $("#id-JurisdictionState").val(state == 0 ? $scope.modal.JurisdictionState = state.toString().replace(0, "") : (state == null ? $scope.modal.JurisdictionState = "" : $scope.modal.JurisdictionState));
            }, 1000);

        }, function (response) {
        });

        var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {

            $scope.CountriesList = response.data;
            //angular.copy(response.data, $scope.CountriesList);
            $timeout(function () {
                $("#id-JurisdictionCountry").val($scope.modal.JurisdictionCountry);
            }, 1000);

        }, function (response) {
        });

        

        if ($scope.modal.EffectiveDateType == 'DateOfFiling')
            $scope.modal.EffectiveDate = "";

        $scope.validateErrorMessage = false;
        $scope.validateAgentErrors = false;
        $scope.validateOneAgent = false;
    }

    var data = {
        params: {
            // here filingTypeID: 1 is ADJUSTMENTS - WAIVER GRANTED                           
            businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 1, transactionID: $rootScope.transactionID
        }
    };
    //if ($rootScope.modal != null || $rootScope.modal != undefined) {
    //    $rootScope.modal = $rootScope.modal;
    //}
    if ($rootScope.modal == undefined || $rootScope.modal == null || $rootScope.modal == 'undefined' || $rootScope.modal == '') {
        // LLCFormationCriteria method is available in constants.js
        wacorpService.get(webservices.OnlineFiling.LLCFormationCriteria, data, function (response) {
            $scope.modal = response.data;
            $scope.modal.DurationYears = ($scope.modal.DurationYears <= 0 || $scope.modal.DurationYears == undefined || $scope.modal.DurationYears == '0') ? '' : $scope.modal.DurationYears;
            $scope.modal.IsPerpetual = !$scope.modal.IsPerpetual ? ($scope.modal.DurationYears == null && $scope.modal.DurationExpireDate == null) : $scope.modal.IsPerpetual;
            calcDuration(); // calcDuration method is available in this controller only.
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            $scope.modal.LLCAgent.AgentType = $scope.modal.LLCAgent.AgentType || "I";
            $scope.modal.LLCAuthorizedPerson.PersonType = $scope.modal.LLCAuthorizedPerson.PersonType || "I";
            $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.DateOfFormationInHomeJurisdiction = wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);
            $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
            $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
            $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0 || $scope.modal.JurisdictionCountry == "") ? usaCode : $scope.modal.JurisdictionCountry.toString();
            $scope.modal.JurisdictionState = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0) ? null : $scope.modal.JurisdictionState.toString();
            $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.DateBeganDoingBusinessInWA = wacorpService.dateFormatService($scope.modal.DateBeganDoingBusinessInWA);
            $scope.modal.NatureOfBusiness.IsOtherNAICS = $scope.modal.NatureOfBusiness.OtherDescription != null ? true : false;// Is Other NAICS check box in Nature Of Business Condition
            $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.NatureOfBusiness.NAICSCode)) ? $scope.modal.NatureOfBusiness.NAICSCode : $scope.modal.NatureOfBusiness.NAICSCode.split(','));
            if ($scope.modal.DateBeganDoingBusinessInWAType == null || $scope.modal.DateBeganDoingBusinessInWAType == undefined || $scope.modal.DateBeganDoingBusinessInWAType=="")
                $scope.modal.DateBeganDoingBusinessInWAType = 'rdoDateBeganInWA';
            $scope.uploadFiles = [];
            $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
            $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
            $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
            $scope.isShowReturnAddress = true;
        }, function (response) { });
    }
    else {
        $scope.modal = $rootScope.modal;
        $scope.modal.NatureOfBusiness.IsOtherNAICS = $scope.modal.NatureOfBusiness.OtherDescription != null ? true : false;// Is Other NAICS check box in Nature Of Business Condition
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.NatureOfBusiness.NAICSCode)) ? $scope.modal.NatureOfBusiness.NAICSCode : $scope.modal.NatureOfBusiness.NAICSCode.split(','));
        }

        if($scope.modal.DateOfFormationInHomeJurisdiction == "0001-01-01T00:00:00")
        {
            $scope.modal.DateOfFormationInHomeJurisdiction =  "";
        }

        calcDuration();
       
        //if (angular.isDate($scope.modal.DateOfFormationInHomeJurisdiction))
        //{           
        //    $scope.modal.DateOfFormationInHomeJurisdiction = "";
        //} 
        $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
        $scope.modal.DateOfFormationInHomeJurisdiction = wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);
        $scope.modal.DateBeganDoingBusinessInWA = wacorpService.dateFormatService($scope.modal.DateBeganDoingBusinessInWA);
        $scope.isShowReturnAddress = true;

        // OSOS ID--3192
        $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0) ? "" : $scope.modal.JurisdictionCountry.toString();

    }


    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {


        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    $scope.searchBusinessNames = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                businessName: $scope.modal.BusinessName
            }
        };
        //GetBusinessNames method is available in constants.js
        wacorpService.get(webservices.Common.GetBusinessNames, config, function (response) {
            $scope.businessNames = response.data;
            $scope.searchlookupText = "Lookup";
        }, function (response) { $scope.searchlookupText = "Lookup"; });
    };

    $scope.GetReservedBusiness = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                registrationID: parseInt($scope.NameReservedID)
            }
        };
        // GetReservedBusiness method is available in constants.js
        wacorpService.get(webservices.Common.GetReservedBusiness, config, function (response) {
            if (response.data.BusinessName != null)
                $scope.modal.BusinessName = response.data.BusinessName;
            else
                // Folder Name: app Folder
                // Alert Name: noReserverBusiness method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.BusinessFormation.noReserverBusiness);
        }, function (response) { });
    };

    $scope.isemptyCheckShowCommentsandNote = function () {
        return $scope.showComments && angular.isNullorEmpty($scope.model.Note);
    };

    // check business count availability
    $scope.availableBusinessCount = function () {
        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {

            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };

    $scope.Review = function (businessForm) {
        $scope.validateErrorMessage = true;
        var isUBILookup = true;
        var isDomesticUBI = true;
        var isForeignUBI = true;
        var indicatorFlag = false;
        $scope.validateAgentErrors = $scope.modal.LLCAgent.IsNewAgent;
        $scope.validateOneAgent = $scope.modal.LLCAgent.AgentID == 0 && !$scope.modal.LLCAgent.IsNewAgent;

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[businessForm]);

        if (!$scope.modal.IsDBAInUse && ($scope.modal.DBABusinessName == null || $scope.modal.DBABusinessName == ''))
            indicatorFlag = wacorpService.isIndicatorValid($scope.modal) ? true : false;

        // UBI Number
        var isUBINumberValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UBINumber, $scope.modal, $scope.modal.BusinessTypeID) ||
                                $scope[businessForm].UBINumberForm.$valid);

        if (isUBINumberValid) {
            if ($rootScope.isLookUpClicked)
                $scope.isUbiLookUpClicked = true;
            else {
                $scope.isUbiLookUpClicked = false;
                if ($rootScope.isUseClicked)
                    $scope.isUseClicked = true;
                else
                    $scope.isUseClicked = false;
            }
        }
        else {
            if (!isUBINumberValid && $rootScope.isLookUpClicked || $rootScope.isUseClicked) {
                $scope.isUseClicked = true;
                $scope.isUbiLookUpClicked = true;
                $rootScope.$broadcast("checkUBIUse", $scope.modal.UBINumber);
            }
            else {
                $scope.isUbiLookUpClicked = false;
                $scope.isUseClicked = false;
            }
        }
            

        //This is for UBI Look up
        if ($scope.modal.isValidUBI) {

            if ($scope.modal.entityList.length > 0) {
                //This is to check whether UBI is clicked or not
                var isUBILookup = (!$scope.modal.UBINumber || $scope.modal.UBINumber == $scope.modal.OnlineLookupUBINo);
                $scope.modal.OnlineIsUBIChecked = !isUBILookup;

                //This is to check UBI is domestic or foreign
                if ($scope.modal.BusinessType != null && $scope.modal.BusinessType.indexOf('WA ') > -1) {
                    // here UBIBusinessTypeID = 101 is Unregistered Corporations
                    var isDomesticUBI = ($scope[businessForm].UBINumberForm.$valid && $scope.modal.UBIBusinessTypeID == 101 ? true : false);
                    $scope.modal.IsDomesticUBI = !isDomesticUBI;
                }
                else {
                    // here BusinessCategoryID = 5 is FOREIGN ENTITY
                    var isForeignUBI = ($scope[businessForm].UBINumberForm.$valid && ($scope.modal.UBIBusinessTypeID == 101 || $scope.modal.BusinessCategoryID == 5) ? true : false);
                    $scope.modal.IsForeignUBI = !isForeignUBI;
                }
            }

        }

        //Entity Name
        var businessNameCount = $scope.availableBusinessCount(); // availableBusinessCount method is available in this controller only.

        var isBusinessNameExists = $scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable);
        //var isBusinessNameExists = (!$scope.modal.IsNameReserved ? (($scope.modal.isBusinessNameAvailable == null || $scope.modal.isBusinessNameAvailable == undefined) ? true : $scope.modal.isBusinessNameAvailable) : true);

        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);
        var isEntityValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EntityName, $scope.modal, $scope.modal.BusinessTypeID) ||
                             ($scope[businessForm].EntityName.$valid
                             && (($scope.modal.IsDBAInUse && $scope.modal.DBABusinessName != null && $scope.modal.DBABusinessName != '') ? (businessNameValid || $scope.modal.IsDBAInUse) : businessNameValid)
                             && ((!$scope.modal.IsNameReserved
                             //&& (angular.isNullorEmpty($scope.modal.isBusinessNameAvailable))
                             && wacorpService.isIndicatorValid($scope.modal))
                             || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != "")))
                              );
        if ($scope.modal.IsDBAInUse && ($scope.modal.DBABusinessName != null || $scope.modal.DBABusinessName != '' || $scope.modal.DBABusinessName != undefined)) {
            $rootScope.$broadcast("checkDBAIndicator");

        }
        else if (!indicatorFlag) {
            $rootScope.$broadcast("checkIndicator");
        }
        var isDBAValid = !$scope.modal.IsDBAInUse ||
                          (
                          (!$scope.ScreenPart($scope.modal.AllScreenParts.DbaName, $scope.modal, $scope.modal.BusinessTypeID)
                         || ($scope[businessForm].DBAName.$valid) && $scope.modal.isDBANameAvailable && $scope.modal.IsDBAInUse) || $scope.modal.IsNameReserved);

        //var isDBAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DbaName, $scope.modal, $scope.modal.BusinessTypeID)
        //                  || ($scope[businessForm].DBAName.$valid) && $scope.modal.isDBANameAvailable && $scope.modal.IsDBAInUse) || $scope.modal.IsNameReserved || $scope.modal.isBusinessNameAvailable;

        $scope.validateAgentErrors = $scope.modal.LLCAgent.IsNewAgent;
        $scope.validateOneAgent = $scope.modal.LLCAgent.AgentID == 0 && !$scope.modal.LLCAgent.IsNewAgent;
        //Name In Home Jurisdiction TFS ticket 11761
        //var isNameInHomeJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.NameInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                    $scope[businessForm].NameInHomeJurisdictionForm.$valid);

        //Jurisdiction
        var isJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Jurisdiction, $scope.modal, $scope.modal.BusinessTypeID) ||
                                            $scope[businessForm].JurisdictionForm.$valid);


        // principal office
        var isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
                                            $scope[businessForm].PrincipalOffice.$valid);


        // registered agent
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) || (($scope[businessForm].RegisteredAgentForm.$valid) && (!$scope.modal.LLCAgent.IsNonCommercial ? $scope.modal.LLCAgent.StreetAddress.StreetAddress1 : true) && ($scope.modal.LLCAgent.IsNonCommercial ? $scope.validateAgentErrors : true)));

        var isRegisteredAgentValidStates = !$scope.modal.LLCAgent.StreetAddress.IsInvalidState && !$scope.modal.LLCAgent.MailingAddress.IsInvalidState && !$scope.modal.LLCAgent.StreetAddress.invalidPoBoxAddress;

        $scope.validateStreetAddress = !$scope.modal.LLCAgent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        //Governing Person 
        var isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount("GoverningPerson") > 0);

        //>Date of Formation in Home Jurisdiction
        var isDOFHomeJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DateOfFormationInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[businessForm].DOFHomeJurisdiction.$valid);


        var isDateBeganDBInWA = (!$scope.ScreenPart($scope.modal.AllScreenParts.DateBeganDoingBusinessInWA, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[businessForm].DateBeganDoingBusinessInWA.$valid);

        //Duration/PeriodOfDurationInHomeJurisdiction
        var isDurationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PeriodOfDurationInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID)
                                || $scope[businessForm].DurationForm.$valid);


        //Nature of business
        var isNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID)
                                    || (!$scope.modal.NatureOfBusiness.IsOtherNAICS ? $scope.modal.NatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.NatureOfBusiness.IsOtherNAICS && !$scope.modal.NatureOfBusiness.OtherDescription ? false : true)));
        //($scope.modal.NatureOfBusiness.NAICSCode.length > 0 || ($scope.modal.NatureOfBusiness.OtherDescription == null ? false :$scope.modal.NatureOfBusiness.OtherDescription.length > 0)));

        // Effective Date Valid
        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].EffectiveDate.$valid);


        //Upload Certificate of Existence
        var isArticalUploadValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UploadCertificateOfExistence, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope.modal.IsArticalsExist && ($scope.modal.CertificateOfFormation != null && $scope.modal.CertificateOfFormation.length > constant.ZERO));

        var isAuthorizedPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].AuthorizedPersonForm.$valid);

        var isDateOfFormationInHomeJurisdictionValid = (($scope.modal.DateOfFormationInHomeJurisdiction == null || typeof ($scope.modal.DateOfFormationInHomeJurisdiction) == typeof (undefined) || $scope.modal.DateOfFormationInHomeJurisdiction == "") ? false : true);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        var isCorrespondenceAddressValid = $scope[businessForm].CorrespondenceAddress.$valid;

        var isFormValid = isJurisdictionValid && isPrincipalOfficeValid && isRegisteredAgentValid && isGoverningPersonValid && isEffectiveDateValid && isDateOfFormationInHomeJurisdictionValid
                             && isAuthorizedPersonValid && isEntityValid && isDBAValid && isDateBeganDBInWA && isNatureOfBusiness && isArticalUploadValid && isAdditionalUploadValid
                             && isRegisteredAgentValidStates && isDurationValid
                             && isUBILookup && isDomesticUBI && isCorrespondenceAddressValid && isForeignUBI && !$scope.modal.invalidDBAIndicator && !$scope.isUbiLookUpClicked && !$scope.isUseClicked;//isNameInHomeJurisdictionValid && isUBINumberValid && 

        if (isFormValid) {
            $scope.validateErrorMessage = false;
            $scope.validateAgentErrors = false;
            $scope.validateOneAgent = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.CorrespondenceAddress.FullAddress = wacorpService.fullAddressService($scope.modal.CorrespondenceAddress);
            $scope.modal.PrincipalOffice.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalStreetAddress);
            $scope.modal.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalMailingAddress);
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	            $scope.modal.IsEmailOptionChecked = false;
            }

            var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.

            if (countryDesc == $scope.unitedstates) {
                var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.JurisdictionState); // selectedJurisdiction method is available in this controller only.
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionState);
                $scope.modal.JurisdictionDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionStateDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
            }
            else {
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionCountry);
                $scope.modal.JurisdictionDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionStateDesc = null;
            }
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = new Date();
            $rootScope.modal = $scope.modal;
            $location.path('/LLCforeignReview');
        }
        else {
            //if (isBusinessNameExists && !isEntityValid && !$scope.modal.IsDBAInUse) {
            //    $timeout(function () { 
            //        angular.element('#id-txtBusiessName').triggerHandler('blur');
            //    }, 300);
               
            //}
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };

    $scope.selectedJurisdiction = function (items, selectedVal) {
        var result = "";
        angular.forEach(items, function (item) {
            if (selectedVal == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }

    $scope.addYearsToCurrentDate = function () {
        var myDate = new Date();
        myDate.setFullYear(myDate.getFullYear() + parseInt($scope.modal.DurationYears));
        $scope.modal.DurationExpireDate = myDate;
    };
    $scope.selectBusiness = function (businessName) {
        $scope.modal.BusinessName = businessName;
    };
    $scope.CountryChangeDesc = function () {
        $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.
        if ($scope.modal.JurisdictionCountryDesc.toUpperCase() == 'UNITED STATES') {
            $scope.modal.JurisdictionState = '';
        };
    }

        function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
            lookupService.NaicsCodes(function (response) {
                $scope.NaicsCodes = response.data;
            });
        }

        $scope.dropdownsettings = {
            scrollableHeight: '200px',
            key: "Value",
            value: "Key",
            scrollable: true,
            isKeyList: false,
            selectall: false
        };
        //duration calculation
        function calcDuration() {
            $scope.modal.DurationYears = $scope.modal.DurationYears == 0 ? null: $scope.modal.DurationYears;

            //To set duration expire date 
            if ($scope.modal.DurationType == 'rdoDureationDate') {
                $scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? null: $scope.modal.DurationExpireDate;
            } else {
                $scope.modal.DurationExpireDate = null;
            }

            $scope.modal.DurationType = ($scope.modal.DurationYears == null && ($scope.modal.DurationExpireDate == null || $scope.modal.DurationExpireDate == "")) && $scope.modal.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
            if ($scope.modal.DurationType == 'rdoPerpetual') {
                $scope.modal.IsPerpetual = true;
            }
        }
    // check duration mode
        $scope.IsPerpetual = function (obj) {
            if (obj == 'rdoDureationDate') {
                $scope.modal.IsPerpetual = false;
                //$scope.modal.DurationExpireDate = null;
                $scope.modal.DurationYears = null;
            }
            else if (obj == 'rdoDureationYears') {
                $scope.modal.IsPerpetual = false;
                $scope.modal.DurationExpireDate = null;
            }
            else {
                $scope.modal.IsPerpetual = true;
                $scope.modal.DurationExpireDate = null;
                $scope.modal.DurationYears = null;
            }
        }

    //to trim empty spaces for NOB Other
        $scope.validateOtherNOB = function () {
            
            $scope.modal.NatureOfBusiness.OtherDescription = $scope.modal.NatureOfBusiness.OtherDescription ? angular.copy($scope.modal.NatureOfBusiness.OtherDescription.trim()) : (($scope.modal.NatureOfBusiness.OtherDescription == undefined || $scope.modal.NatureOfBusiness.OtherDescription == "") ? $scope.modal.NatureOfBusiness.OtherDescription = null : $scope.modal.NatureOfBusiness.OtherDescription);
        }

        $scope.clearOtherDescription = function () {
            $scope.modal.NatureOfBusiness.OtherDescription = null;
        }

        $scope.natureOfBussinesVal = function () {
            return ($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && (($scope.modal.NatureOfBusiness.OtherDescription == undefined || $scope.modal.NatureOfBusiness.OtherDescription == null) ? true: $scope.modal.NatureOfBusiness.OtherDescription.length <= 0))
        };

        function removLeadingZero(arr) {
            var result = "", clear = false;
            for (i = 0; i < arr.length; i++) {
                if (arr[i]=== "0") {
                    if (i > 0) {
                        result += arr[i];
                    } else {
                        clear = true;
                    }
                } else {
                    result += arr[i];
                }
            }
            return clear == true ? "": result;
        }

        $scope.checkLeadingZero = function (txtDurationYears) {
            var item = txtDurationYears.replace(/^\s+|\s+$/g, '');
            var arr = item.split('');
            if (item === "0") {
                $scope.modal.DurationYears = "";
            }
            else if (arr.length > 0 && arr[0]=== "0") {
                $scope.modal.DurationYears = removLeadingZero(arr);
            }
        };
        //Save into Draft
        $scope.SaveAsDraft = function (iscloseDraft) {
            $scope.isShowReturnAddress = true;
            $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
            $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/ /g, ''): $scope.modal.UBINumber;
            $scope.modal.OnlineNavigationUrl = '/LLCforeignbusinessFormation';
            $scope.modal.CartStatus = 'Incomplete';
            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
            }
            $scope.modelDraft = { };
            
            //TFS 1143 submitting filing means you have said agent consents
            if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
                $scope.modal.Agent.IsRegisteredAgentConsent =
                    true;
            }
            if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
                $scope.modal.IsRegisteredAgentConsent = true; 
            }
            //TFS 1143

            angular.copy($scope.modal, $scope.modelDraft);
            var index = 0;
            angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
                $scope.modelDraft['AllScreenParts[' + index + '].Key']= key;
                $scope.modelDraft['AllScreenParts[' + index + '].Value']= value;
                index++;
            });

            index = 0;
            angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
                $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key']= key;
                $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value']= value;
                index++;
            });
            // LLCForeignFormationSaveAsDraft method is available in constants.js
            wacorpService.post(webservices.OnlineFiling.LLCForeignFormationSaveAsDraft, $scope.modelDraft, function (response) {
                if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                    $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ?[]: $scope.modal.NatureOfBusiness.NAICSCode;
                }
                $scope.modal.OnlineCartDraftID = response.data.ID;
                $rootScope.BusinessType = null;
                if (iscloseDraft) {
                    $location.path('/Dashboard');
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: SaveDraftSuccess method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
                }
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        }
    });
wacorpApp.controller('LLCReviewController', function ($scope, $q, $http, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    $scope.NaicsCodes = [];
    $scope.modal = $rootScope.modal;
    getNaicsCodes();
    checkModel();
    $scope.AddToCart = function () {
        
        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");
        var uri = webservices.OnlineFiling.AddToCartLLC; // AddToCartLLC method is available in constants.js
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("<div>").html($("section.content-body").html());
        var $initialReportReviewHTML = $("<div>").html($("section.content-body").html());
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove, .initialReport").remove();
        $initialReportReviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove, .formation").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace("&nbsp;REVIEW", " ").replace(" Review", " ");
        $scope.modal.InitialReportReviewHTML = $initialReportReviewHTML.html().replace("&nbsp;REVIEW", " ").replace(" Review", " ");

        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
               $rootScope.isFormationWithIR = null;
               $location.path('/shoppingCart');
              
           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };

    $scope.back = function () {  
        $rootScope.modal = $scope.modal;
        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
        {
            $rootScope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");
        }
        $location.path('/LLCbusinessFormation');
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // get selected Naics Codes
    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCodeDesc += $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    }
    //Check Model
    function checkModel() {
       var flag = (($rootScope.modal == null || $rootScope.modal == undefined)
                && ($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null)
                && ($rootScope.transactionID == undefined || $rootScope.transactionID == null));              
        if (flag) {
            $location.path('/businessFormationIndex');
        }
    }

    $scope.AddMoreItems = function () {
        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");
        var uri = webservices.OnlineFiling.AddToCartLLC; // AddToCartLLC method is available in constants.js
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
               $rootScope.isFormationWithIR = null;
              // if ($scope.modal.BusinessTransaction.TransactionId > 0)
               $location.path('/Dashboard');

           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };
});
wacorpApp.controller('LLPbusinessFormationController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    /* declare scope variables */
    $scope.modal = {

    };
    $scope.NaicsCodes = [];
    $scope.validateErrorMessage = false;
    $scope.validateAgentErrors = false;
    $scope.principalsCount = 0;
    $scope.irPrincipalsCount = 0;
    $scope.isGeneralPartnerEntityName = false;
    // initialize the scope
    $scope.Init = function () {
        $scope.messages = messages;
        getNaicsCodes(); // getNaicsCodes method is available in this controller only.

        //get business information
        // here filingTypeID: 1 is ADJUSTMENTS - WAIVER GRANTED                           
        var data = { params: { businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 1, transactionID: $rootScope.transactionID, isWithIntialReport: $rootScope.isFormationWithIR } };
        if ($rootScope.modal == null || $rootScope.modal == undefined) {

            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $location.path('/businessFormationIndex');

            }
            // LLPFormationCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.LLPFormationCriteria, data, function (response) {

                $scope.modal = response.data;
                $scope.modal.DurationYears = ($scope.modal.DurationYears <= 0 || $scope.modal.DurationYears == undefined || $scope.modal.DurationYears == '0') ? '' : $scope.modal.DurationYears;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                $scope.modal.IsFormationWithIntialReport = $rootScope.isFormationWithIR || $scope.modal.IsFormationWithIntialReport;
                if ($scope.modal.IsFormationWithIntialReport)
                    $scope.modal.FormationWithInitialReport.AuthorizedPerson.PersonType = $scope.modal.FormationWithInitialReport.AuthorizedPerson.PersonType || "I";
                else
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
                $scope.modal.Agent.AgentType = $scope.modal.Agent.AgentType || "I";
                $scope.modal.IsLLLPElection = $scope.modal.IsLLLPElection ? $scope.modal.IsLLLPElection : false;
                $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                $scope.modal.NumberOfPartners = ($scope.modal.NumberOfPartners <= 0 || $scope.modal.NumberOfPartners == undefined || $scope.modal.NumberOfPartners == '0') ? '' : $scope.modal.NumberOfPartners;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode)) ? $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.split(','));

                if ($scope.modal.Indicator.OldNote == null || $scope.modal.Indicator.OldNote == undefined || $scope.modal.Indicator.OldNote == "")
                    $scope.modal.Indicator.OldNote = $scope.modal.Indicator.Note;
                if ($rootScope.IsLLPShoppingCart && $scope.modal.Indicator.OldIndicators != null) {
                    $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.split(',');
                }
                else if ($scope.modal.Indicator.OldIndicators == null || $scope.modal.Indicator.OldIndicators == undefined || $scope.modal.Indicator.OldIndicators == "")
                    $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.Indicators;

                //$scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.split(',');
                $scope.uploadFiles = [];
                calcDuration(); // calcDuration method is available in this controller only.
                $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                $scope.isShowReturnAddress = true;

                if ($scope.modal.IsLLLPElection) {
                    isLLLPElectionReview(); // isLLLPElectionReview method is available in this controller only.
                }

            }, function (response) { });
        }
        else
        {
            $scope.modal = $rootScope.modal;
            if ($scope.modal.Indicator.OldIndicators != null) {
                if (!$.isArray($scope.modal.Indicator.OldIndicators))
                    $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.split(',');
                else {
                }
            }


            if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
                $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode)) ? $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.split(','));

            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = "";
            calcDuration(); // calcDuration method is available in this controller only.
            $scope.modal.isBusinessNameAvailable = true;
            $scope.modal.Indicator.IsValidEntityName = true;
            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            $scope.isShowReturnAddress = true;
        }

    }

    // validate the form submit for review
    $scope.Review = function (businessForm) {
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        $scope.modal.FormationWithInitialReport.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.FormationWithInitialReport.PrincipalOffice.PrincipalMailingAddress);

        $scope.validateErrorMessage = true;

        var isUBILookup = true;
        var isDomesticUBI = true;
        var isForeignUBI = true;

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[businessForm]);

        var isUBINumberValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UBINumber, $scope.modal, $scope.modal.businesstypeid) &&
                                $scope[businessForm].UBINumberForm.$valid);

        if (isUBINumberValid) {
            if ($rootScope.isLookUpClicked)
                $scope.isUbiLookUpClicked = true;
            else {
                $scope.isUbiLookUpClicked = false;
                if ($rootScope.isUseClicked)
                    $scope.isUseClicked = true;
                else
                    $scope.isUseClicked = false;
            }
        }
        else {
            if (!isUBINumberValid && $rootScope.isLookUpClicked || $rootScope.isUseClicked) {
                $scope.isUseClicked = true;
                $scope.isUbiLookUpClicked = true;
                $rootScope.$broadcast("checkUBIUse", $scope.modal.UBINumber);
            }
            else {
                $scope.isUseClicked = false;
                $scope.isUbiLookUpClicked = false;
            }
        }

        if($scope.modal.isValidUBI)
        {
            if ($scope.modal.entityList.length > 0) {
                //This is to check whether UBI is clicked or not
                var isUBILookup = (!$scope.modal.UBINumber || $scope.modal.UBINumber == $scope.modal.OnlineLookupUBINo);
                $scope.modal.OnlineIsUBIChecked = !isUBILookup;

                //This is to check UBI is domestic or foreign
                if ($scope.modal.BusinessType != null && $scope.modal.BusinessType.indexOf('WA ') > -1) {
                    // here UBIBusinessTypeID = 101 is Unregistered Corporations
                    var isDomesticUBI = ($scope[businessForm].UBINumberForm.$valid && $scope.modal.UBIBusinessTypeID == 101 ? true : false);
                    $scope.modal.IsDomesticUBI = !isDomesticUBI;
                }
                else {
                    // here BusinessCategoryID = 5 is FOREIGN ENTITY
                    var isForeignUBI = ($scope[businessForm].UBINumberForm.$valid && ($scope.modal.UBIBusinessTypeID == 101 || $scope.modal.BusinessCategoryID == 5) ? true : false);
                    $scope.modal.IsForeignUBI = !isForeignUBI;
                }
            }
        }

        //Entity Name
        var businessNameCount = $scope.availableBusinessCount();
        var isBusinessNameExists = $scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable);
        // var isBusinessNameExists = (!$scope.modal.IsNameReserved ? (($scope.modal.isBusinessNameAvailable == null || $scope.modal.isBusinessNameAvailable == undefined) ? true : $scope.modal.isBusinessNameAvailable) : true);
        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);
        var isEntityValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EntityName, $scope.modal, $scope.modal.BusinessTypeID) ||
                           ($scope[businessForm].EntityName.$valid
                           && (businessNameValid || $scope.modal.IsDBAInUse)
                           && ((!$scope.modal.IsNameReserved
                           //&& (angular.isNullorEmpty($scope.modal.isBusinessNameAvailable))
                           && wacorpService.isIndicatorValid($scope.modal))
                           || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != "")))
                            );
        if (!wacorpService.isIndicatorValid($scope.modal)) {
            $rootScope.$broadcast("checkIndicator");
        }

        var isDBAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DbaName, $scope.modal, $scope.modal.BusinessTypeID)
                           || ($scope[businessForm].DBAName.$valid) && $scope.modal.isDBANameAvailable && $scope.modal.IsDBAInUse) || $scope.modal.IsNameReserved || $scope.modal.isBusinessNameAvailable;


        // registered agent
        $scope.validateAgentErrors = $scope.modal.Agent.IsNewAgent;
        $scope.validateOneAgent = $scope.modal.Agent.AgentID == 0 && !$scope.modal.Agent.IsNewAgent;
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
            (($scope[businessForm].RegisteredAgentForm != undefined && $scope[businessForm].RegisteredAgentForm != null && $scope[businessForm].RegisteredAgentForm.$valid) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 : true) && ($scope.modal.Agent.IsNonCommercial ? $scope.validateAgentErrors : true)));

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;
        $scope.modal.Agent.IsRegisteredAgentConsent = true; //TFS 1143 submitting filing means you have said agent consents
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        $scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial && !isRegisteredAgentValid ? true : false;
        //var isArticalUploadValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UploadCertificateOfLimitedPartnership, $scope.modal, $scope.modal.BusinessTypeID)
        //   || $scope.modal.IsArticalsExist ? ($scope.modal.IsArticalsExist && $scope.modal.CertificateOfLimitedPartnership != null && $scope.modal.CertificateOfLimitedPartnership.length > 0) : true);

        //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
        if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	        $scope.modal.IsEmailOptionChecked = false;
        }

        var isUploadCertificateOfLimitedLiabilityPartnership = (!$scope.ScreenPart($scope.modal.AllScreenParts.UploadCertificateOfLimitedPartnership, $scope.modal, $scope.modal.BusinessTypeID)
           || $scope.modal.IsArticalsExist ? ($scope.modal.UploadCertificateOfLimitedPartnership != null && $scope.modal.UploadCertificateOfLimitedPartnership.length >0) : true);

        var isEffectiveDateValid = !$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID)
                                    || $scope[businessForm].EffectiveDate.$valid;

        var isGeneralPartnersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartners, $scope.modal, $scope.modal.BusinessTypeID)
                                   || $scope.principalsCount("GeneralPartner") > 0);

        $scope.isGeneralPartnersSignatureConfirmationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartnersSignatureConfirmation, $scope.modal, $scope.modal.BusinessTypeID)
                                   || ($scope.modal.GeneralPartnersSignatureConfirmation == true || $scope.modal.GeneralPartnersSignatureConfirmation == "true"));

        var isAttestationOfStatedProfessionValid = !$scope.ScreenPart($scope.modal.AllScreenParts.AttestationOfStatedProfession, $scope.modal, $scope.modal.BusinessTypeID)
                                    || $scope[businessForm].AttestationOfStatedProfessionForm.$valid;

        //var isNotGeneralPartnerEntityName = wacorpService.validateGeneralPartnerWithEntityName($rootScope.NewEntityNameCleanUp) == false ? true : false;
        //$scope.isGeneralPartnerEntityName = isNotGeneralPartnerEntityName == false ? true : false;

        var isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].PrincipalOffice.$valid);
        var isCorrespondenceAddressValid = $scope[businessForm].CorrespondenceAddress.$valid;
        // with inital report
        if ($scope.modal.IsFormationWithIntialReport) {

            $scope.isPrincipalOfficeInWAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRPrincipalOfficeInWA, $scope.modal, $scope.modal.BusinessTypeID)
                                                || $scope[businessForm].PrincipalOffice.$valid);

            $scope.isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRGoverningPersons, $scope.modal, $scope.modal.BusinessTypeID)
                                             || $scope.irPrincipalsCount("GoverningPerson") > 0);


            $scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.IRNatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID)
                 ||(!$scope.modal.FormationWithInitialReport.NatureOfBusiness.IsOtherNAICS ? $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0: ($scope.modal.FormationWithInitialReport.NatureOfBusiness.IsOtherNAICS && !$scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription  ? false: true)));
            //|| !($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription.length <= 0)));
            $scope.isCorrespondenceAddress = $scope[businessForm].CorrespondenceAddress.$valid;
        }
        else {
            $scope.isPrincipalOfficeInWAValid = true;
            $scope.isGoverningPersonValid = true;
            $scope.validateNatureOfBusiness = true;
        }
        
        var isAuthorizedPersonValidate = (!($scope.ScreenPart($scope.modal.AllScreenParts.AuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID) ||
                                          ($scope.ScreenPart($scope.modal.AllScreenParts.IRAuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID) && $scope.modal.IsFormationWithIntialReport)) ||
                                           $scope[businessForm].AuthorizedPersonForm.$valid);
        var isDurationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Duration, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].Duration.$valid);

        var isNumberOfPartners = (!$scope.ScreenPart($scope.modal.AllScreenParts.NumberOfPartners, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].NumberOfPartnersForm.$valid);

        $scope.isOneNumberOfPartners = (!$scope.ScreenPart($scope.modal.AllScreenParts.NumberOfPartners, $scope.modal, $scope.modal.BusinessTypeID) || ($scope.modal.NumberOfPartners > 1));

        var isBusinessPartnerShipEngages = (!$scope.ScreenPart($scope.modal.AllScreenParts.PartnershipEngages, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].PartnerShipEngagesForm.$valid);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isFormValid = isRegisteredAgentValid && isEffectiveDateValid && isGeneralPartnersValid && $scope.isGeneralPartnersSignatureConfirmationValid
                           && $scope.isPrincipalOfficeInWAValid && $scope.isGoverningPersonValid && $scope.validateNatureOfBusiness && $scope.isOneNumberOfPartners
                           && isEntityValid && isDBAValid && isDurationValid && isUploadCertificateOfLimitedLiabilityPartnership && isPrincipalOfficeValid && isNumberOfPartners && isBusinessPartnerShipEngages
                           && isAdditionalUploadValid && isUBILookup && isDomesticUBI && isCorrespondenceAddressValid && isForeignUBI && isAuthorizedPersonValidate && isRegisteredAgentValidStates
                           && !$scope.isUbiLookUpClicked && !$scope.isUseClicked;


        if (isFormValid) {
            $scope.modal.NumberOfPartners = $scope.modal.NumberOfPartners > 1 ? parseInt($scope.modal.NumberOfPartners) : $scope.modal.NumberOfPartners;
            $scope.validateErrorMessage = false;
            $scope.validateAgentErrorMessage = false;
            $scope.validateprincipalErrorMessage = false;
            $scope.isHavingPrincipals = false;
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = new Date();
            $rootScope.modal = $scope.modal;
            $location.path('/LLPReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // lookup search
    $scope.searchBusinessNames = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                businessName: $scope.modal.BusinessName
            }
        };
        // GetBusinessNames method is available in constants.js
        wacorpService.get(webservices.Common.GetBusinessNames, config, function (response) {
            $scope.businessNames = response.data;
            $scope.searchlookupText = "Lookup";
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog('Failed');
            $scope.searchlookupText = "Lookup";
        });
    };

    // check business count availability
    $scope.availableBusinessCount = function () {
        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {

            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };

    $scope.isValidIndicator = function ($event) {

        var indicators = $scope.modal.Indicator.IndicatorsCSV;
        var isValid = 0;
        var obj = $event.currentTarget;

        var entityName;
        if (indicators != null && indicators != "null" && indicators != "NULL" && indicators != undefined && indicators != "undefined" && indicators != '') {
            if ($(obj).attr('data-isupdate') != undefined && $(obj).attr('data-isupdate') && $(obj).attr('data-isupdate') != "false" && $(obj).attr('data-isupdate') != "False") {
                entityName = $scope.modal.BusinessName + ' ' + $scope.modal.Indicator.IndicatorsCSV;
                entityName = entityName.toLowerCase().replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '');
            }
            else {
                entityName = $scope.modal.BusinessName.toLowerCase().replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '');
            }
            angular.forEach($scope.modal.Indicator.Indicators, function (value) {
                value = value.replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                isValid = new RegExp("^" + value + "\\s").test(entityName) ? isValid + 1 : isValid;
            });

            if (isValid == 0) {
                angular.forEach($scope.modal.Indicator.Indicators, function (value) {
                    value = value.replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                    isValid = new RegExp("\\s" + value + "\\s").test(entityName) ? isValid + 1 : isValid;
                });
            }
            if (isValid == 0) {
                angular.forEach($scope.modal.Indicator.Indicators, function (value) {
                    value = value.replace(/[,|.|{|}|(|)|-|;|'|\"]/g, '').toLowerCase();
                    isValid = new RegExp("\\s" + value + "$").test(entityName) ? isValid + 1 : isValid;
                });
            }
        }
        else {
            isValid = 1; //For all entities we are not going to have Indicators, that's the reason default we are considering as true.
        }


        $scope.indicatorValidMessage = isValid > 0 ? "" : "The entity name requested does not contain the necessary designation. Please input one of the required designations (" + $(obj).attr('data-indicators') + ").";// TFS ID 12017
    };

    // check entity name 
    $scope.isValidEntityname = function ($event) {

        var obj = $event.currentTarget;
        return $(obj).attr('data-isnamevalid') == "true" || $(obj).attr('data-isnamevalid') == "True" ? "" : "Please perform an " + $(obj).attr('data-selectionName').toLowerCase() + " lookup to confirm that the desired entity name is valid and available.";// TFS ID 12015
    }

    $scope.IsPerpetual = function (obj) {
        if (obj == 'rdoDureationDate') {
            $scope.modal.IsPerpetual = false;
            //$scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
        else if (obj == 'rdoDureationYears') {
            $scope.modal.IsPerpetual = false;
            $scope.modal.DurationExpireDate = null;
        }
        else {
            $scope.modal.IsPerpetual = true;
            $scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
    }

    //duration calculation
    function calcDuration() {
        $scope.modal.DurationYears = $scope.modal.DurationYears == 0 ? null : $scope.modal.DurationYears;

        //To set duration expire date 
        if ($scope.modal.DurationType == 'rdoDureationDate') {
            $scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? null : $scope.modal.DurationExpireDate;
        } else {
            $scope.modal.DurationExpireDate = null;
        }
        $scope.modal.DurationType = ($scope.modal.DurationYears == null && ($scope.modal.DurationExpireDate == null || $scope.modal.DurationExpireDate == "")) && $scope.modal.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
        if ($scope.modal.DurationType == 'rdoPerpetual') {
            $scope.modal.IsPerpetual = true;
        }
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };

    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
        });
    }

    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    $scope.irPrincipalsCount = function (baseType) {
        var principalsList = $scope.modal.FormationWithInitialReport.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    $scope.clearOtherDescription = function () {
        $scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription = null;
    };

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.FormationWithInitialReport.NatureOfBusiness.OtherDescription.length <= 0))
    };

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/ /g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/LLPbusinessFormation';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");
        $scope.modelDraft = {};
        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        if ($scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined && $scope.modal.Indicator.OldIndicators.length > 0) {

            $scope.modelDraft.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.join();
        }
        // LLPFormationSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.LLPFormationSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode;
            }
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.checkLeadingZero = function (txtDurationYears) {
        var val = txtDurationYears.replace(/^\s+|\s+$/g, '');
        var arr = [];
        if (val === "0") {
            $scope.modal.DurationYears = "";
        } else {
            arr = val.split('');
        }
        if (arr.length > 0 && arr[0] === "0") {
            $scope.modal.DurationYears = removLeadingZero(arr);
        }
    };

    $scope.checkForNoOfPartners = function () {
        if ($scope.modal.NumberOfPartners > 1) {
            $scope.isOneNumberOfPartners = true;
        }
        else {
            $scope.isOneNumberOfPartners = false;
        }
    };

    //var newNote = 'The name must contain the words "Limited Liability Limited Partnership", "LLLP", or "L.L.L.P." The name is limited to a maximum of 255 characters. If you wish to use a name longer than 255 characters, your application must be filed in paper form instead of electronically.';
    var newNote = helptext.Corporations.LLLP;
    $scope.IsLLLPElection = function (obj) {
        if (obj) {
            var _addIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _addindicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            var _addIndicatorArray=[];
            if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP")
            {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _addIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _addIndicatorArray;
            }
            else
                _addIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _addIndicatorsCSV.indexOf("LLLP");
            if (indexCSV <= 0) {
                //_addIndicatorsCSV = _addIndicatorsCSV + ",LLLP";
                _addIndicatorsCSV = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsCSV = _addIndicatorsCSV;

            var indexDsisplay = _addindicatorsDisplay.indexOf("LLLP");
            if (indexDsisplay <= 0) {
                //_addindicatorsDisplay = _addindicatorsDisplay + ", LLLP";
                _addindicatorsDisplay = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsDisplay = _addindicatorsDisplay

            var index = _addIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_addIndicatorArray.push("LLLP");
                _addIndicatorArray = [];
                if ($scope.modal.BusinessType == "WA LIMITED PARTNERSHIP")
                {
                    var indicators = _addindicatorsDisplay.split(',');
                    angular.forEach(indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP")
                {
                    angular.forEach($scope.modal.Indicator.Indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = newNote;
            $scope.modal.Indicator.Indicators = _addIndicatorArray;
        }
        else {
            var _removeIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _removeIndicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            var _removeIndicatorArray=[];
            if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP")
            {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _removeIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _removeIndicatorArray;
            }
            else
                _removeIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _removeIndicatorsCSV.indexOf("LLLP");
            if (indexCSV >= 0) {
                //_removeIndicatorsCSV = _removeIndicatorsCSV.replace(',LLLP', '');
                _removeIndicatorsCSV = _removeIndicatorsCSV.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsCSV = _removeIndicatorsCSV;

            var indexDisplay = _removeIndicatorsDisplay.indexOf("LLLP");
            if (indexDisplay >= 0) {
                //_removeIndicatorsDisplay = _removeIndicatorsDisplay.replace(', LLLP', '');
                _removeIndicatorsDisplay = _removeIndicatorsDisplay.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsDisplay = _removeIndicatorsDisplay;


            var index = _removeIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_removeIndicatorArray.splice(index, 1);
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "WA LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            else if (index > 0)
            {
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "WA LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = $scope.modal.Indicator.OldNote;
            $scope.modal.Indicator.Indicators = _removeIndicatorArray;
        }
        $("#id-txtBusiessName").trigger("blur");
    }

    //isLLLPElectionReview
    function isLLLPElectionReview() {
        if ($scope.modal.IsLLLPElection) {
            var _addIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _addindicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            var _addIndicatorArray = [];
            if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP")
            {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _addIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _addIndicatorArray;
            }
            else
                _addIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _addIndicatorsCSV.indexOf("LLLP");
            if (indexCSV <= 0) {
                //_addIndicatorsCSV = _addIndicatorsCSV + ",LLLP";
                _addIndicatorsCSV = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsCSV = _addIndicatorsCSV;

            var indexDsisplay = _addindicatorsDisplay.indexOf("LLLP");
            if (indexDsisplay <= 0) {
                //_addindicatorsDisplay = _addindicatorsDisplay + ", LLLP";
                _addindicatorsDisplay = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsDisplay = _addindicatorsDisplay

            var index = _addIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_addIndicatorArray.push("LLLP");
                _addIndicatorArray = [];
                if ($scope.modal.BusinessType == "WA LIMITED PARTNERSHIP")
                {
                    var indicators = _addindicatorsDisplay.split(',');
                    angular.forEach(indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.Indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }

            }
            $scope.modal.Indicator.Note = newNote;
            $scope.modal.Indicator.Indicators = _addIndicatorArray;
        }
        else {
            var _removeIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _removeIndicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            var _removeIndicatorArray = [];
            if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP")
            {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _removeIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _removeIndicatorArray;
            }
            else
                _removeIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV= _removeIndicatorsCSV.indexOf("LLLP");
            if (indexCSV >= 0) {
                //_removeIndicatorsCSV = _removeIndicatorsCSV.replace(',LLLP', '');
                _removeIndicatorsCSV = _removeIndicatorsCSV.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsCSV = _removeIndicatorsCSV;

            var indexDisplay = _removeIndicatorsDisplay.indexOf("LLLP");
            if (indexDisplay >= 0) {
                //_removeIndicatorsDisplay = _removeIndicatorsDisplay.replace(', LLLP', '');
                _removeIndicatorsDisplay = _removeIndicatorsDisplay.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsDisplay = _removeIndicatorsDisplay;

            var index = _removeIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_removeIndicatorArray.splice(index, 1);
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "WA LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            else if (index >= 1)
            {
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "WA LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "WA LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = $scope.modal.Indicator.OldNote;
            $scope.modal.Indicator.Indicators = _removeIndicatorArray;
        }
    };


});

wacorpApp.controller('LLPforeignbusinessFormationController', function ($scope, $location, $rootScope, lookupService, wacorpService, $timeout) {
    $scope.modal = {};
    $scope.CountriesList = [];
    $scope.StatesList = [];
    $scope.NaicsCodes = [];
    $scope.principalsCount = 0;
    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType == baseType && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };
    var data = {
        params: {
            // here filingTypeID: 1 is ADJUSTMENTS - WAIVER GRANTED                           
            businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 1, transactionID: $rootScope.transactionID
        }
    };
    if ($rootScope.modal != null || $rootScope.modal != undefined) {
        $rootScope.amendedAnnualReportModal = $rootScope.modal;
        //$rootScope.modal = null;
    }
    if ($rootScope.modal == undefined || $rootScope.modal == null || $rootScope.modal == 'undefined' || $rootScope.modal == '') {
        // LLPFormationCriteria method is available in constants.js
        wacorpService.get(webservices.OnlineFiling.LLPFormationCriteria, data, function (response) {
            $scope.modal = response.data;
            if ($scope.modal.DateBeganDoingBusinessInWAType == null || $scope.modal.DateBeganDoingBusinessInWAType == undefined || $scope.modal.DateBeganDoingBusinessInWAType == "")
                $scope.modal.DateBeganDoingBusinessInWAType = 'rdoDateBeganInWA';

            $scope.modal.IsLLLPElection = $scope.modal.IsLLLPElection ? $scope.modal.IsLLLPElection : false;
            $scope.modal.DurationYears = ($scope.modal.DurationYears <= 0 || $scope.modal.DurationYears == undefined || $scope.modal.DurationYears == '0') ? '' : $scope.modal.DurationYears;
            $scope.modal.Agent.AgentType = $scope.modal.Agent.AgentType || "I";
            $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
            $scope.modal.DateOfFormationInHomeJurisdiction = wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);
            $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
            $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
            $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0 || $scope.modal.JurisdictionCountry == "") ? usaCode : $scope.modal.JurisdictionCountry.toString();
            $scope.modal.JurisdictionState = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0) ? null : $scope.modal.JurisdictionState.toString();
            $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.DateBeganDoingBusinessInWA = wacorpService.dateFormatService($scope.modal.DateBeganDoingBusinessInWA);
            $scope.modal.NatureOfBusiness.IsOtherNAICS = $scope.modal.NatureOfBusiness.OtherDescription != null ? true : false;// Is Other NAICS check box in Nature Of Business Condition
            $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.NatureOfBusiness.NAICSCode)) ? $scope.modal.NatureOfBusiness.NAICSCode : $scope.modal.NatureOfBusiness.NAICSCode.split(','));
            if ($scope.modal.Indicator.OldNote == null || $scope.modal.Indicator.OldNote == undefined || $scope.modal.Indicator.OldNote == "")
                $scope.modal.Indicator.OldNote = $scope.modal.Indicator.Note;
            if ($rootScope.IsLLPForeignShoppingCart && $scope.modal.Indicator.OldIndicators != null) {
                $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.split(',');
            }
            else if ($scope.modal.Indicator.OldIndicators == null || $scope.modal.Indicator.OldIndicators == undefined || $scope.modal.Indicator.OldIndicators == "")
                $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.Indicators;

            $scope.uploadFiles = [];
            calcDuration(); // calcDuration method is available in constants.js
            $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
            $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
            $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
            $scope.isShowReturnAddress = true;
            if ($scope.modal.IsLLLPElection) {
                isLLLPElectionReview(); // isLLLPElectionReview method is available in constants.js
            }
        }, function (response) { });
    }
    else {
        $scope.modal = $rootScope.modal;
        if ($scope.modal.Indicator.OldIndicators != null) {
            if (!$.isArray($scope.modal.Indicator.OldIndicators))
                $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.split(',');
            else { }
        }

        $scope.modal.NatureOfBusiness.IsOtherNAICS = $scope.modal.NatureOfBusiness.OtherDescription != null ? true : false;// Is Other NAICS check box in Nature Of Business Condition
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : ((angular.isArray($scope.modal.NatureOfBusiness.NAICSCode)) ? $scope.modal.NatureOfBusiness.NAICSCode : $scope.modal.NatureOfBusiness.NAICSCode.split(','));
        }
        if ($scope.modal.EffectiveDateType == 'DateOfFiling')
            $scope.modal.EffectiveDate = "";
        calcDuration();  // calcDuration method is available in constants.js

        $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
        $scope.modal.DateOfFormationInHomeJurisdiction = wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);
        $scope.modal.DateBeganDoingBusinessInWA = wacorpService.dateFormatService($scope.modal.DateBeganDoingBusinessInWA);
        $scope.isShowReturnAddress = true;

        // OSOS ID--3192
        $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0) ? "" : $scope.modal.JurisdictionCountry.toString();

    }


    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    $scope.searchBusinessNames = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                businessName: $scope.modal.BusinessName
            }
        };
        // GetBusinessNames method is available in constants.js
        wacorpService.get(webservices.Common.GetBusinessNames, config, function (response) {
            $scope.businessNames = response.data;
            $scope.searchlookupText = "Lookup";
        }, function (response) { $scope.searchlookupText = "Lookup"; });
    };

    $scope.GetReservedBusiness = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                registrationID: parseInt($scope.NameReservedID)
            }
        };
        // GetReservedBusiness method is available in constants.js
        wacorpService.get(webservices.Common.GetReservedBusiness, config, function (response) {
            if (response.data.BusinessName != null)
                $scope.modal.BusinessName = response.data.BusinessName;
            else
                // Folder Name: app Folder
                // Alert Name: noReserverBusiness method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.BusinessFormation.noReserverBusiness);
        }, function (response) { });
    };

    $scope.isemptyCheckShowCommentsandNote = function () {
        return $scope.showComments && angular.isNullorEmpty($scope.model.Note);
    };

    $scope.IsPerpetual = function (obj) {
        if (obj == 'rdoDureationDate') {
            $scope.modal.IsPerpetual = false;
            //$scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
        else if (obj == 'rdoDureationYears') {
            $scope.modal.IsPerpetual = false;
            $scope.modal.DurationExpireDate = null;
        }
        else {
            $scope.modal.IsPerpetual = true;
            $scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
    }

    //duration calculation
    function calcDuration() {
        $scope.modal.DurationYears = $scope.modal.DurationYears == 0 ? null : $scope.modal.DurationYears;

        //To set duration expire date 
        if ($scope.modal.DurationType == 'rdoDureationDate') {
            $scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? null : $scope.modal.DurationExpireDate;
        } else {
            $scope.modal.DurationExpireDate = null;
        }
        $scope.modal.DurationType = ($scope.modal.DurationYears == null && ($scope.modal.DurationExpireDate == null || $scope.modal.DurationExpireDate == "")) && $scope.modal.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
        if ($scope.modal.DurationType == 'rdoPerpetual') {
            $scope.modal.IsPerpetual = true;
        }
    };

    // check business count availability
    $scope.availableBusinessCount = function () {
        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {

            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };

    $scope.Review = function (businessForm) {
        $scope.validateErrorMessage = true;
        $scope.validateAgentErrors = $scope.modal.Agent.IsNewAgent;
        $scope.validateOneAgent = $scope.modal.Agent.AgentID == 0 && !$scope.modal.Agent.IsNewAgent;
        var isUBILookup = true;
        var isDomesticUBI = true;
        var isForeignUBI = true;
        var indicatorFlag = false;
        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[businessForm]);
        if (!$scope.modal.IsDBAInUse && ($scope.modal.DBABusinessName == null || $scope.modal.DBABusinessName == ''))
            indicatorFlag = wacorpService.isIndicatorValid($scope.modal) ? true : false;

        // UBI Number
        var isUBINumberValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UBINumber, $scope.modal, $scope.modal.BusinessTypeID) ||
                                $scope[businessForm].UBINumberForm.$valid);

        if (isUBINumberValid) {
            if ($rootScope.isLookUpClicked)
                $scope.isUbiLookUpClicked = true;
            else {
                $scope.isUbiLookUpClicked = false;
                if ($rootScope.isUseClicked)
                    $scope.isUseClicked = true;
                else
                    $scope.isUseClicked = false;
            }
        }
        else {
            if (!isUBINumberValid && $rootScope.isLookUpClicked || $rootScope.isUseClicked) {
                $scope.isUseClicked = true;
                $scope.isUbiLookUpClicked = true;
                $rootScope.$broadcast("checkUBIUse", $scope.modal.UBINumber);
            }
            else {
                $scope.isUbiLookUpClicked = false;
                $scope.isUseClicked = false;
            }
        }

        //This is for UBI Look up
        if ($scope.modal.isValidUBI) {
            if ($scope.modal.entityList.length > 0) {
                //This is to check whether UBI is clicked or not
                var isUBILookup = (!$scope.modal.UBINumber || $scope.modal.UBINumber == $scope.modal.OnlineLookupUBINo);
                $scope.modal.OnlineIsUBIChecked = !isUBILookup;

                //This is to check UBI is domestic or foreign
                if ($scope.modal.BusinessType != null && $scope.modal.BusinessType.indexOf('WA ') > -1) {
                    // here UBIBusinessTypeID = 101 is Unregistered Corporations
                    var isDomesticUBI = ($scope[businessForm].UBINumberForm.$valid && $scope.modal.UBIBusinessTypeID == 101 ? true : false);
                    $scope.modal.IsDomesticUBI = !isDomesticUBI;
                }
                else {
                    // here BusinessCategoryID = 5 is FOREIGN ENTITY
                    var isForeignUBI = ($scope[businessForm].UBINumberForm.$valid && ($scope.modal.UBIBusinessTypeID == 101 || $scope.modal.BusinessCategoryID == 5) ? true : false);
                    $scope.modal.IsForeignUBI = !isForeignUBI;
                }
            }
        }
        //Entity Name
        var businessNameCount = $scope.availableBusinessCount(); // availableBusinessCount method is available in this controller only.
        var isBusinessNameExists = $scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable);
        //var isBusinessNameExists = (!$scope.modal.IsNameReserved ? (($scope.modal.isBusinessNameAvailable == null || $scope.modal.isBusinessNameAvailable == undefined) ? true : $scope.modal.isBusinessNameAvailable) : true);

        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);
        var isEntityValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EntityName, $scope.modal, $scope.modal.BusinessTypeID) ||
                             ($scope[businessForm].EntityName.$valid
                             && (($scope.modal.IsDBAInUse && $scope.modal.DBABusinessName != null && $scope.modal.DBABusinessName != '') ? (businessNameValid || $scope.modal.IsDBAInUse) : businessNameValid)
                             && ((!$scope.modal.IsNameReserved
                             //&& (angular.isNullorEmpty($scope.modal.isBusinessNameAvailable))
                             && wacorpService.isIndicatorValid($scope.modal))
                             || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != "")))
                              );

        var isDBAValid = !$scope.modal.IsDBAInUse ||
                          (
                          (!$scope.ScreenPart($scope.modal.AllScreenParts.DbaName, $scope.modal, $scope.modal.BusinessTypeID)
                         || ($scope[businessForm].DBAName.$valid) && $scope.modal.isDBANameAvailable && $scope.modal.IsDBAInUse) || $scope.modal.IsNameReserved);
        if ($scope.modal.IsDBAInUse && ($scope.modal.DBABusinessName != null || $scope.modal.DBABusinessName != '' || $scope.modal.DBABusinessName != undefined)) {
            $rootScope.$broadcast("checkDBAIndicator");//DBA Name Indicator

        }
        else if (!indicatorFlag) {
            $rootScope.$broadcast("checkIndicator");//Entity Name Indicator
        }

        //var isDBAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DbaName, $scope.modal, $scope.modal.BusinessTypeID)
        //                  || ($scope[businessForm].DBAName.$valid) && $scope.modal.isDBANameAvailable && $scope.modal.IsDBAInUse) || $scope.modal.IsNameReserved || $scope.modal.isBusinessNameAvailable;

        //Name In Home Jurisdiction  TFS ticket 11761
        //var isNameInHomeJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.NameInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                    $scope[businessForm].NameInHomeJurisdictionForm.$valid);


        var isDOFHomeJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DateOfFormationInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[businessForm].DOFHomeJurisdiction.$valid);

        var isDateBeganDBInWA = (!$scope.ScreenPart($scope.modal.AllScreenParts.DateBeganDoingBusinessInWA, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope[businessForm].DateBeganDoingBusinessInWA.$valid);

        //Jurisdiction
        var isJurisdictionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Jurisdiction, $scope.modal, $scope.modal.BusinessTypeID) ||
                                            $scope[businessForm].JurisdictionForm.$valid);

        // principal office
        var isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
                                            $scope[businessForm].PrincipalOffice.$valid);

        // registered agent
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
           (($scope[businessForm].RegisteredAgentForm.$valid) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 : true) && ($scope.modal.Agent.IsNonCommercial ? $scope.validateAgentErrors : true)));
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;

        $scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial && !isRegisteredAgentValid ? true : false;
		
        //Governing Person 
        var isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount("GoverningPerson") > 0);

        // Effective Date Valid
        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].EffectiveDate.$valid);

        //Upload Certificate of Existence  //This code is commented as per PCC TFS ID: Task 14173
        var isArticalUploadValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UploadCertificateOfExistence, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope.modal.IsArticalsExist && ($scope.modal.UploadCertificateOfLimitedPartnership != null && $scope.modal.UploadCertificateOfLimitedPartnership.length > constant.ZERO));


        var isAuthorizedPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AuthorizedPerson, $scope.modal, $scope.modal.BusinessTypeID) || $scope[businessForm].AuthorizedPersonForm.$valid);

        // nature of business
        var validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
                                           (!$scope.modal.NatureOfBusiness.IsOtherNAICS ? $scope.modal.NatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.NatureOfBusiness.IsOtherNAICS && !$scope.modal.NatureOfBusiness.OtherDescription ? false : true)));

        //($scope.modal.NatureOfBusiness.NAICSCode.length > 0 || ($scope.modal.NatureOfBusiness.OtherDescription == null ? false :$scope.modal.NatureOfBusiness.OtherDescription.length > 0)));

        var isDurationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PeriodOfDurationInHomeJurisdiction, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[businessForm].DurationForm.$valid);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        var isCorrespondenceAddressValid = $scope[businessForm].CorrespondenceAddress.$valid;
        var isFormValid = isJurisdictionValid && isPrincipalOfficeValid && isRegisteredAgentValid && isGoverningPersonValid && isDurationValid
                              && isEffectiveDateValid && isAuthorizedPersonValid && validateNatureOfBusiness && isArticalUploadValid && isDateBeganDBInWA
                              && isAdditionalUploadValid && isDOFHomeJurisdictionValid && isUBILookup && isDomesticUBI && isEntityValid && isDBAValid && isCorrespondenceAddressValid && isForeignUBI
                              && !$scope.modal.invalidDBAIndicator && isRegisteredAgentValidStates; // isUBINumberValid  && isNameInHomeJurisdictionValid &&

        if (isFormValid) {
            $scope.validateErrorMessage = false;
            $scope.validateAgentErrors = false;
            $scope.validateOneAgent = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalMailingAddress);
            $scope.modal.PrincipalOffice.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalStreetAddress);
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	            $scope.modal.IsEmailOptionChecked = false;
            }
            var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.
            if (countryDesc == $scope.unitedstates) {
                var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.JurisdictionState); // selectedJurisdiction method is available in this controller only.
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionState);
                $scope.modal.JurisdictionDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionStateDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
            }
            else {
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionCountry);
                $scope.modal.JurisdictionDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionStateDesc = null;
                $scope.modal.JurisdictionState = null;
            }
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = new Date();
            $rootScope.modal = $scope.modal;
            $location.path('/LLPforeignReview');
        }
        else {

            //if (isBusinessNameExists && !isEntityValid && !$scope.modal.IsDBAInUse) {
            //    $timeout(function () {
            //        angular.element('#id-txtBusiessName').triggerHandler('blur');
            //    }, 300);
            //}
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };

    $scope.selectedJurisdiction = function (items, selectedVal) {
        var result = "";
        angular.forEach(items, function (item) {
            if (selectedVal == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }

    $scope.addYearsToCurrentDate = function () {
        var myDate = new Date();
        myDate.setFullYear(myDate.getFullYear() + parseInt($scope.modal.DurationYears));
        $scope.modal.DurationExpireDate = myDate;
    };
    $scope.selectBusiness = function (businessName) {
        $scope.modal.BusinessName = businessName;
    };

    $scope.CountryChangeDesc = function () {
        $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.

    };
    $scope.Init = function () {

        $scope.unitedstates = "UNITED STATES";
        $scope.CountryChangeDesc(); // CountryChangeDesc method is available in this controller only
        $scope.messages = messages;
        getNaicsCodes(); // getNaicsCodes method is available in this controller only
        var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
            $scope.CountriesList = response.data;
            $timeout(function () {
                $("#id-JurisdictionCountry").val($scope.modal.JurisdictionCountry);
            }, 1000);
        }, function (response) {
        });

        var lookupStatesParams = { params: { name: 'ForeignJurisdictionStates' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
            $scope.StatesList = response.data;

            $timeout(function () {
                var state = $scope.modal.JurisdictionState;
                $("#id-JurisdictionState").val(state == 0 ? $scope.modal.JurisdictionState = state.toString().replace(0, "") : (state == null ? $scope.modal.JurisdictionState = "" : $scope.modal.JurisdictionState));
            }, 1000);

        }, function (response) {
        });
        if ($scope.modal.EffectiveDateType == 'DateOfFiling')
            $scope.modal.EffectiveDate = "";




        $scope.validateErrorMessage = false;
        $scope.validateAgentErrors = false;
        $scope.validateOneAgent = false;

    }

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };

    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
        });
    }

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && (($scope.modal.NatureOfBusiness.OtherDescription == undefined || $scope.modal.NatureOfBusiness.OtherDescription == null) ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0))
    };

    function removLeadingZero(arr) {
        var result = "", clear = false;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] === "0") {
                if (i > 0) {
                    result += arr[i];
                } else {
                    clear = true;
                }
            } else {
                result += arr[i];
            }
        }
        return clear == true ? "" : result;
    }

    $scope.checkLeadingZero = function (txtDurationYears) {
        var item = txtDurationYears.replace(/^\s+|\s+$/g, '');
        var arr = item.split('');
        if (item === "0") {
            $scope.modal.DurationYears = "";
        }
        else if (arr.length > 0 && arr[0] === "0") {
            $scope.modal.DurationYears = removLeadingZero(arr);
        }
    };

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/ /g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/LLPforeignbusinessFormation';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $scope.modelDraft = {};
        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        if ($scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined && $scope.modal.Indicator.OldIndicators.length > 0) {
            $scope.modelDraft.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.join();
        }
        // LLPForeignFormationSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.LLPForeignFormationSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
            }
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)SSS
            wacorpService.alertDialog(response.data);
        });
    }

    var newNote = helptext.Corporations.LLLP;
    $scope.IsLLLPElection = function (obj) {
        if (obj) {
            var _addIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _addindicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            //var _addIndicatorArray = $scope.modal.Indicator.Indicators;
            var _addIndicatorArray = [];

            if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _addIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _addIndicatorArray;
            }
            else
                _addIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _addIndicatorsCSV.indexOf("LLLP");
            if (indexCSV <= 0) {
                //_addIndicatorsCSV = _addIndicatorsCSV + ",LLLP";
                _addIndicatorsCSV = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }

            $scope.modal.Indicator.IndicatorsCSV = _addIndicatorsCSV;

            var indexDsisplay = _addindicatorsDisplay.indexOf("LLLP");
            if (indexDsisplay <= 0) {
                //_addindicatorsDisplay = _addindicatorsDisplay + ", LLLP";
                _addindicatorsDisplay = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }

            $scope.modal.Indicator.IndicatorsDisplay = _addindicatorsDisplay

            var index = _addIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_addIndicatorArray.push("LLLP");
                _addIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    var indicators = _addindicatorsDisplay.split(',');
                    angular.forEach(indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.Indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = newNote;
            $scope.modal.Indicator.Indicators = _addIndicatorArray;
        }
        else {
            var _removeIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _removeIndicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            //var _removeIndicatorArray = $scope.modal.Indicator.Indicators;
            var _removeIndicatorArray = [];

            if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _removeIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _removeIndicatorArray;
            }
            else
                _removeIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _removeIndicatorsCSV.indexOf("LLLP");
            if (indexCSV >= 0) {
                //_removeIndicatorsCSV = _removeIndicatorsCSV.replace(',LLLP', '');
                _removeIndicatorsCSV = _removeIndicatorsCSV.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsCSV = _removeIndicatorsCSV;

            var indexDisplay = _removeIndicatorsDisplay.indexOf("LLLP");
            if (indexDisplay >= 0) {
                //_removeIndicatorsDisplay = _removeIndicatorsDisplay.replace(', LLLP', '');
                _removeIndicatorsDisplay = _removeIndicatorsDisplay.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsDisplay = _removeIndicatorsDisplay;


            var index = _removeIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_removeIndicatorArray.splice(index, 1);
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }

            }
            else if (index > 0) {
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = $scope.modal.Indicator.OldNote;
            $scope.modal.Indicator.Indicators = _removeIndicatorArray;
        }
        $("#id-txtBusiessName").trigger("blur");
    }

    //isLLLPElectionReview
    function isLLLPElectionReview() {
        if ($scope.modal.IsLLLPElection) {
            var _addIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _addindicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            //var _addIndicatorArray = $scope.modal.Indicator.Indicators;
            var _addIndicatorArray = [];

            if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _addIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _addIndicatorArray;
            }
            else
                _addIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _addIndicatorsCSV.indexOf("LLLP");
            if (indexCSV <= 0) {
                //_addIndicatorsCSV = _addIndicatorsCSV + ",LLLP";
                _addIndicatorsCSV = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsCSV = _addIndicatorsCSV;

            var indexDsisplay = _addindicatorsDisplay.indexOf("LLLP");
            if (indexDsisplay <= 0) {
                //_addindicatorsDisplay = _addindicatorsDisplay + ", LLLP";
                _addindicatorsDisplay = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsDisplay = _addindicatorsDisplay

            var index = _addIndicatorArray.indexOf("LLLP");
            if (index <= 0) {

                //_addIndicatorArray.push("LLLP");
                _addIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    var indicators = _addindicatorsDisplay.split(',');
                    angular.forEach(indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.Indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = newNote;
            $scope.modal.Indicator.Indicators = _addIndicatorArray;
        }
        else {
            var _removeIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _removeIndicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            //var _removeIndicatorArray = $scope.modal.Indicator.Indicators;
            var _removeIndicatorArray = [];

            if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _removeIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _removeIndicatorArray;
            }
            else
                _removeIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _removeIndicatorsCSV.indexOf("LLLP");
            if (indexCSV >= 0) {
                //_removeIndicatorsCSV = _removeIndicatorsCSV.replace(',LLLP', '');
                _removeIndicatorsCSV = _removeIndicatorsCSV.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsCSV = _removeIndicatorsCSV;

            var indexDisplay = _removeIndicatorsDisplay.indexOf("LLLP");
            if (indexDisplay >= 0) {
                //_removeIndicatorsDisplay = _removeIndicatorsDisplay.replace(', LLLP', '');
                _removeIndicatorsDisplay = _removeIndicatorsDisplay.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsDisplay = _removeIndicatorsDisplay;

            var index = _removeIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_removeIndicatorArray.splice(index, 1);
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            else if (index > 1) {
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = $scope.modal.Indicator.OldNote;
            $scope.modal.Indicator.Indicators = _removeIndicatorArray;
        }
    };

    $scope.clearOtherDescription = function () {
        $scope.modal.NatureOfBusiness.OtherDescription = null;
    }

    //to trim empty spaces for NOB Other
    $scope.validateOtherNOB = function () {

        $scope.modal.NatureOfBusiness.OtherDescription = $scope.modal.NatureOfBusiness.OtherDescription ? angular.copy($scope.modal.NatureOfBusiness.OtherDescription.trim()) : (($scope.modal.NatureOfBusiness.OtherDescription == undefined || $scope.modal.NatureOfBusiness.OtherDescription == "") ? $scope.modal.NatureOfBusiness.OtherDescription = null : $scope.modal.NatureOfBusiness.OtherDescription);
    }
});
wacorpApp.controller('LLPReviewController', function ($scope, $q, $http, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    $scope.NaicsCodes = [];
    $scope.modal = $rootScope.modal;
    getNaicsCodes();
    checkModel();
    $scope.AddToCart = function () {

        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length>0)
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");


        if ($scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined && $scope.modal.Indicator.OldIndicators.length > 0) {
            $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.join();
        }
        var uri = webservices.OnlineFiling.AddToCartLLP; // AddToCartLLP method is available in constants.js
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("<div>").html($("section.content-body").html());
        var $initialReportReviewHTML = $("<div>").html($("section.content-body").html());
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove, .initialReport").remove();
        $initialReportReviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove, .formation").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace("&nbsp;REVIEW", " ").replace(" Review", " ");
        $scope.modal.InitialReportReviewHTML = $initialReportReviewHTML.html().replace("&nbsp;REVIEW", " ").replace(" Review", " ");

        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
               $rootScope.isFormationWithIR = null;
               $location.path('/shoppingCart');
             
           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };

    $scope.back = function () {
        $rootScope.modal = $scope.modal;
        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $rootScope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");
        $rootScope.modal.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? '' : $scope.modal.EffectiveDate;
        $location.path('/LLPbusinessFormation');
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

   
    // get selected Naics Codes
    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCodeDesc += $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    }

    //Check Model
    function checkModel() {
        var flag = (($rootScope.modal == null || $rootScope.modal == undefined)
                 && ($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null)
                 && ($rootScope.transactionID == undefined || $rootScope.transactionID == null));
        if (flag) {
            $location.path('/businessFormationIndex');
        }
    }
    $scope.AddMoreItems = function () {

        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");

        var uri = webservices.OnlineFiling.AddToCartLLP; // AddToCartLLP method is available in constants.js
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
               $rootScope.isFormationWithIR = null;
               //if ($scope.modal.BusinessTransaction.TransactionId > 0)
                   $location.path('/Dashboard');

           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };
});
wacorpApp.controller('foreignReviewController', function ($scope, $http, $location, $rootScope,lookupService, wacorpService) {
    $scope.Init = function () {
        $scope.modal = $rootScope.modal; $scope.NaicsCodes = []; $scope.NaicsCodesNonProfit = [];
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.CorpNatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        $scope.modal.CorpNatureOfBusiness.NAICSCodeDesc += $scope.modal.CorpNatureOfBusiness.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            var principalsList = $scope.modal.CorpNatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodesNonProfit.push(response.data[i]);
                        $scope.modal.CorpNatureOfBusiness.NAICSCodeDesc += $scope.modal.CorpNatureOfBusiness.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    };
    $scope.AddToCart = function () {
        var uri = webservices.OnlineFiling.AddToCart; // AddToCart method is available in constants.js
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace("&nbsp;REVIEW", " ").replace(" Review", " ");

        if ($scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.CorpNatureOfBusiness.NAICSCode = $scope.modal.CorpNatureOfBusiness.NAICSCode.join(",");

        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
               $location.path('/shoppingCart');
               
           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };

    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    $scope.back = function () {  
        $rootScope.modal = $scope.modal;
        if ($scope.modal.CorpNatureOfBusiness.NAICSCode != null && $scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0) {
            $rootScope.modal.CorpNatureOfBusiness.NAICSCode = $scope.modal.CorpNatureOfBusiness.NAICSCode != null ? $scope.modal.CorpNatureOfBusiness.NAICSCode.join(",") : [];
        }
        $location.path('/foreignbusinessFormation').search('ID', '1')
    };

    $scope.AddMoreItems = function () {
        var uri = webservices.OnlineFiling.AddToCart; // AddToCart method is available in constants.js
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        if ($scope.modal.CorpNatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.CorpNatureOfBusiness.NAICSCode = $scope.modal.CorpNatureOfBusiness.NAICSCode.join(",");

        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
               //if ($scope.modal.BusinessTransaction.TransactionId > 0)
               $location.path('/Dashboard');

           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };
});
wacorpApp.controller('LLCforeignReviewController', function ($scope, $http, $location, $rootScope, lookupService) {
    $scope.Init = function () {
        $scope.unitedstates = "UNITED STATES";
        $scope.modal = $rootScope.modal;
        $scope.NaicsCodes = [];
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        $scope.modal.NatureOfBusiness.NAICSCodeDesc += $scope.modal.NatureOfBusiness.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    };
    $scope.AddToCart = function () {
        var uri = webservices.OnlineFiling.AddToCartLLC; // AddToCartLLC method is available in constants.js
        if ($scope.modal.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace("&nbsp;REVIEW", " ").replace(" Review", " ");

        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
               $location.path('/shoppingCart');
              
           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };

    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };
    $scope.back = function () {
        $rootScope.modal = $scope.modal;
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0)
            $rootScope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        $location.path('/LLCforeignbusinessFormation').search('ID', '1')
    };
    $scope.AddMoreItems = function () {
        var uri = webservices.OnlineFiling.AddToCartLLC; // AddToCartLLC method is available in constants.js
        if ($scope.modal.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
               //if ($scope.modal.BusinessTransaction.TransactionId > 0)
                   $location.path('/Dashboard');

           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };
});
wacorpApp.controller('LLPforeignReviewController', function ($scope, $http, $location, $rootScope, lookupService) {
    $scope.Init = function () {
        $scope.modal = $rootScope.modal;
        $scope.NaicsCodes = [];
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        $scope.modal.NatureOfBusiness.NAICSCodeDesc += $scope.modal.NatureOfBusiness.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    };
    $scope.AddToCart = function () {
        var uri = webservices.OnlineFiling.AddToCartLLP; // AddToCartLLP method is available in constants.js
        if ($scope.modal.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        if ($scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined && $scope.modal.Indicator.OldIndicators.length > 0) {
            $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.join();
        }
        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace("&nbsp;REVIEW", " ").replace(" Review", " ");

        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
               $location.path('/shoppingCart');
               
           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };

    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    $scope.back = function () {
      
        $rootScope.modal = $scope.modal;
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $rootScope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $location.path('/LLPforeignbusinessFormation').search('ID', '1')
    };
    $scope.AddMoreItems = function () {
        var uri = webservices.OnlineFiling.AddToCartLLP; // AddToCartLLP method is available in constants.js
        if ($scope.modal.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        var data = $scope.modal;
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: uri,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
           function (response) {
               $rootScope.modal = null;
               $rootScope.BusinessType = null;
              // if ($scope.modal.BusinessTransaction.TransactionId > 0)
                   $location.path('/Dashboard');

           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };
});
wacorpApp.controller('shoppingCartController', function ($scope, $rootScope, $location, $http, wacorpService, lookupService, $timeout, $filter) {
    $scope.model = {};
    $scope.AdditionalFee;
    $scope.ExpediteAmount;
    $scope.AddCurrentARFeeList = [];

    $scope.GetAdditionalFee = function () {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.ItemizedServiceFeesList(function (response) {
            $.each(response.data, function (key, value) {
                if (value.Key == 'Processing') {
                    $scope.ExpediteAmount = value.Value;
                }
            });
        });
    };

    $scope.GetAdditionalFee(); // GetAdditionalFee method is available in this controller only.
    // load shopping cart items
    $scope.init = function () {
        $rootScope.modal = null;
        $rootScope.transactionID = null;
        $scope.getData($rootScope.repository.loggedUser.userid, function (data) {
            $scope.model.cartItems = data;
            if (data.length > 0) {
                var flag = true;
                angular.forEach($scope.model.cartItems, function (item, index) {
                    // checkPaymentAmount method is available in constants.js
                    wacorpService.post(webservices.ShoppingCart.checkPaymentAmount, item,
                      function (response) {
                          response.data.UBI = response.data.UBI || "";
                          $scope.model.cartItems[index] = response.data;
                          if (typeof $rootScope.payment != typeof undefined && $rootScope.payment != null && $rootScope.payment.cartItems.length > 0) {
                              angular.forEach($rootScope.payment.cartItems, function (item1) {
                                  if ($scope.model.cartItems[index].ID == item1.ID && item1.isSelect) {
                                      $scope.model.cartItems[index].isSelect = item1.isSelect;
                                      $scope.selectChange($scope.model.cartItems[index]); // selectChange method is available in this controller only.
                                  }
                              });
                          }
                      });
                });
                if (typeof $rootScope.payment == typeof undefined || $rootScope.payment == null || $rootScope.payment.cartItems.length == 0) {
                    //wacorpService.alertDialog($scope.messages.ShoppingCartAlertMessage.AlertMessage);
                }
            }

            if ($scope.model.cartItems.length > 0) {

                var cartItems = $scope.model.cartItems.sort(function (a, b) {
                    return a.FilingType - b.FilingType || a.UBI.localeCompare(b.UBI);
                });

                //$scope.filteredItems = $filter('filter')(cartItems, function (item) { return item.UBI && item.CFTRegistrationNumber});

                var filteredUBIs = cartItems;

                $scope.duplicateUBI = [];
                for (var i = 0; i < filteredUBIs.length ; i++) {
                    for (var j = i + 1; j < filteredUBIs.length ; j++) {

                        if (filteredUBIs[i].CFTRegistrationNumber && filteredUBIs[i].CFTRegistrationNumber === filteredUBIs[j].CFTRegistrationNumber && filteredUBIs[i].FilingType === filteredUBIs[j].FilingType && $scope.duplicateUBI.indexOf(filteredUBIs[i].CFTRegistrationNumber) == -1)
                        {
                            $scope.duplicateUBI.push(filteredUBIs[i].CFTRegistrationNumber);
                        }
                        else if ((!filteredUBIs[i].CFTRegistrationNumber && filteredUBIs[i].UBI && filteredUBIs[i].UBI === filteredUBIs[j].UBI && filteredUBIs[i].FilingType === filteredUBIs[j].FilingType && $scope.duplicateUBI.indexOf(filteredUBIs[i].UBI) == -1))
                        {
                            $scope.duplicateUBI.push(filteredUBIs[i].UBI);
                        }
                       
                    }
                }
                return $scope.duplicateUBI;
            }
        });

    };

    $scope.getData = function (id, callback) {
        var config = { params: { UserId: id } };
        // getCartItems method is available in constants.js
        wacorpService.get(webservices.ShoppingCart.getCartItems, config,
           function (response) {
               if (callback)
                   callback(response.data);
           },
           function (response) {
               // Service Folder: services
               // File Name: wacorpService.js (you can search with file name in solution explorer)
               wacorpService.alertDialog(response.data);
           }
       );
    };

    // expedite change
    $scope.expediteChange = function (item) {
        if (item.isSelect) {
            item.FilingAmount = parseInt(item.FilingFee) + parseInt(item.PracessingAmount);
        }
        else {
            if ((parseInt(item.FilingAmount)) != 0 && (parseInt(item.FilingFee) + parseInt(item.PracessingAmount)) == item.FilingAmount) {
                item.FilingAmount = parseInt(item.FilingAmount) - parseInt(item.PracessingAmount);
            }
        }
    };


    // calculate total cart amount based on selected items
    $scope.calcTotal = function () {
        var total = 0;
        angular.forEach($scope.model.cartItems, function (item) {
            total += item.isSelect ? item.FilingAmount + item.PracessingAmount : 0;
        })
        return total;
    }

    // select All cart items
    $scope.selectAll = function () {
        angular.forEach($scope.model.cartItems, function (item) {
            item.isSelect = $scope.model.selectAll;
            // $scope.expediteChange(item);
        });
    };

    // item checkbox click
    $scope.selectChange = function (item) {
        var flag = true;
        //  $scope.expediteChange(item);
        angular.forEach($scope.model.cartItems, function (item) {
            if (!item.isSelect) {
                flag = false;
                return;
            }
        });
        $scope.model.selectAll = flag;
    };

    $scope.isCartItemSelected = function () {
        var flag = false;
        angular.forEach($scope.model.cartItems, function (item) {
            if (item.isSelect) {
                flag = true;
                return;
            }
        });
        return !flag;
    };

    //Use to clear out any rootScope values that are being held onto
    $scope.ClearRootScope = function () {
        //IsGrossRevenueNonProfit
        $rootScope.IsGrossRevenueNonProfit = undefined;
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.modal.IsGrossRevenueNonProfit = undefined;
        };
        //IsGrossRevenueNonProfit
    };

    // edit cart item
    $scope.edit = function (id, FilingType, BusinessTypeId) {
        $scope.ClearRootScope();
        
        $rootScope.transactionID = id;
        var flag = (FilingType.toLowerCase() === 'business formation' || FilingType.toLowerCase() === 'foreign registration statement'
            || FilingType.toLowerCase() === 'certificate of formation' || FilingType.toLowerCase() === 'articles of incorporation'
            || FilingType.toLowerCase() === 'certificate of limited partnership' || FilingType.toLowerCase() === 'certificate of limited liability limited partnership'
            || FilingType.toLowerCase() === 'certificate of formation with initial report' || FilingType.toLowerCase() === 'articles of incorporation with initial report'
            || FilingType.toLowerCase() === 'certificate of limited partnership with initial report' || FilingType.toLowerCase() === 'certificate of limited liability limited partnership with initial report'
            );


        var flagBusinessAmendment = (FilingType.toLowerCase() === 'business amendment' || FilingType.toLowerCase() === 'articles of amendment'
            || FilingType.toLowerCase() === 'amended certificate of limited liability partnership' || FilingType.toLowerCase() === 'amended certificate of prof limited liability partnership'
            || FilingType.toLowerCase() === 'amended certificate of formation' || FilingType.toLowerCase() === 'amended certificate of limited partnership'
            || FilingType.toLowerCase() === 'amended certificate of prof limited liability limited partnership' || FilingType.toLowerCase() === 'amendment'
            || FilingType.toLowerCase() === 'amended certificate of prof limited partnership' || FilingType.toLowerCase() === 'amended declaration of trust'
            || FilingType.toLowerCase() === 'amended certificate of limited liability limited partnership'
            );

        if (flag) {
            var data = { ID: BusinessTypeId };
            if ($rootScope.repository.loggedUser != undefined)
                $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
            $http({
                method: 'POST',
                url: webservices.Lookup.getBusinessFilingType,  // shoppingCartPayment method is available in constants.js
                data: data
            }).then(function (response) {
                var businessType = response.data != undefined ? response.data.split('_')[0] : '';
                var formationType = response.data != undefined ? response.data.split('_')[1] : '';
                if (businessType === "\"C")
                    if (formationType === "0\"")
                        $location.path('/businessFormation').search('ID', '1');
                    else
                        $location.path('/foreignbusinessFormation').search('ID', '1');
                else if (businessType === "\"LLC")
                    if (formationType === "0\"")
                        $location.path('/LLCbusinessFormation').search('ID', '1');
                    else
                        $location.path('/LLCforeignbusinessFormation').search('ID', '1');
                else if (businessType === "\"LLP")
                    if (formationType === "0\"") {
                        $rootScope.IsLLPShoppingCart = true;
                        $location.path('/LLPbusinessFormation').search('ID', '1');
                    }
                    else {
                        IsLLPForeignShoppingCart = true;
                        $location.path('/LLPforeignbusinessFormation').search('ID', '1');
                    }
            },
            function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data.ErrorDescription);
            });
        }
        else if (FilingType.toLowerCase() === 'annual report') {
            $location.path('/AnnualReport');
        }
        else if (FilingType.toLowerCase() === 'initial report') {
            $location.path('/InitialReport');
        }
        else if (FilingType.toLowerCase() === 'amended annual report') {
            $location.path('/AmendedAnnualReport');
        }
        else if (FilingType.toLowerCase() === 'statement of change') {
            $location.path('/StatementofChange');
        }
        else if (FilingType.toLowerCase() === 'commercial statement of change') {
            $location.path('/CommercialStatementofChange');
        }
        else if (FilingType.toLowerCase() === 'statement of resignation') {
            $location.path('/StatementofTermination');
        }
        else if (FilingType.toLowerCase() === 'commercial termination statement') {
            $location.path('/CommercialStatementofTermination');
        }
        else if (FilingType.toLowerCase() === 'commercial listing statement') {
            $location.path('/CommercialListingStatement');
        }
        else if (FilingType.toLowerCase() === 'reinstatement') {
            $location.path('/Reinstatement');
        }
        else if (FilingType.toLowerCase() === 'requalification') {
            $rootScope.IsRequalification = true;
            $location.path('/Requalification');
        }
        else if (FilingType.toLowerCase() === 'amendment of foreign registration statement') {
            $location.path('/AmendmentofForiegnRegistrationStatement');
        }
        else if (FilingType.toLowerCase() === 'statement of withdrawal') {
            $location.path('/StatementofWithdrawal');
        }
        else if (FilingType.toLowerCase() === 'voluntary termination') {
            $location.path('/VoluntaryTermination');
        }
        else if (FilingType.toLowerCase() === 'certificate of dissolution') {
            $location.path('/CertificateOfDissolution');
        }
        else if (FilingType.toLowerCase() === 'articles of dissolution') {
            $location.path('/ArticlesOfDissolution');
        }
        else if (flagBusinessAmendment) {
            $location.path('/BusinessAmendment/0');
        }
        else if (FilingType.toLowerCase() === 'certified copies' || FilingType.toLowerCase() === 'records / certificate request' || FilingType.toLowerCase() === 'records/certificate request') {
            $location.path('/CopyRequest/Edit');
        }
        else if (FilingType.toLowerCase() === 'charitable organization registration') {
            $rootScope.IsShoppingCart = true;
            localStorage.setItem("isOptional", false);
            $location.path('/charitiesRegistration');
        }
        else if (FilingType.toLowerCase() === 'charitable organization renewal') {
            $rootScope.IsShoppingCart = true;
            localStorage.setItem("isOptional", false);
            $location.path('/charitiesRenewal');
        }
        else if (FilingType.toLowerCase() === 'charitable organization amendment') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesAmendment');
        }
        else if (FilingType.toLowerCase() === 'charitable organization optional registration') {
            $rootScope.IsShoppingCart = true;
            localStorage.setItem("isOptional", true);
            $location.path('/charitiesOptionalRegistration');
        }
        else if (FilingType.toLowerCase() === 'charitable organization optional renewal') {
            $rootScope.IsShoppingCart = true;
            localStorage.setItem("isOptional", true);
            $location.path('/charitiesOptionalRenewal');
        }
        else if (FilingType.toLowerCase() === 'charitable organization optional amendment') {
            $rootScope.IsShoppingCart = true;
            localStorage.setItem("isOptional", true);
            $location.path('/charitiesOptionalAmendment');
        }
        else if (FilingType.toLowerCase() === 'charitable organization optional closure') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesOptionalClosure');
        }
        else if (FilingType.toLowerCase() === 'close charitable organization') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesClosure');
        }
        else if (FilingType.toLowerCase() === 'commercial fundraiser registration') {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserRegistration');
        }
        else if (FilingType.toLowerCase() === 'commercial fundraiser renewal') {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserRenewal/0');
        }
        else if (FilingType.toLowerCase() === 'commercial fundraiser amendment') {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserAmendment/0');
        }
        else if (FilingType.toLowerCase() === 'commercial fundraiser closure') {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserClosure/0');
        }
        else if (FilingType.toLowerCase() === 'charitable trust renewal') {
            $rootScope.IsShoppingCart = true;
            $location.path('/trusteeRenewal/0');
        }
        else if (FilingType.toLowerCase() === 'charitable trust closure') {
            $rootScope.IsShoppingCart = true;
            $location.path('/trusteeClosure/0');
        }
            // here BusinessTypeId = 7 is CHARITABLE ORGANIZATION
        else if (FilingType.toLowerCase() === 're-registration' && BusinessTypeId == 7) {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesReRegistration/0');
            // here BusinessTypeId = 8 is CHARITABLE TRUST
        } else if (FilingType.toLowerCase() === 're-registration' && BusinessTypeId == 8) {
            $rootScope.IsShoppingCart = true;
            $location.path('/trustReRegistration/0');
            // here BusinessTypeId = 10 is COMMERCIAL FUNDRAISER
        } else if (FilingType.toLowerCase() === 're-registration' && BusinessTypeId == 10) {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserReRegistration/0');
        }
        else if (FilingType.toLowerCase() === 'records / certificate request') {
            $location.path('/CopyRequest/0');
        }
        else if (FilingType.toLowerCase() === 'fundraising service contract registration') {
            $rootScope.IsShoppingCart = true;
            $location.path('/submitFundraisingServiceContract/0');
        }
        else if (FilingType.toLowerCase() === 'fundraising service contract amendment') {
            $rootScope.IsShoppingCart = true;
            $location.path('/submitFundraisingServiceContractAmendment/0');
        }
        else if (FilingType.toLowerCase() === 'express pdf certificate of existence') {
            $location.path('/ExpressPDFCertificate/Edit');
        }
    };

    $scope.delete = function (id, index, currentItem) {
        // Folder Name: app Folder
        // Alert Name: ConfirmMessage method is available in alertMessages.js
        wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {

            var config = { params: { ID: id } };
            // cartItemDelete method is available in constants.js
            wacorpService.get(webservices.ShoppingCart.cartItemDelete, config,
               function (response) {
                   if (response != null && response.data != null && response.data == "1") {
                       var itemIndex = $scope.model.cartItems.indexOf(currentItem);
                       $scope.model.cartItems.splice(itemIndex, 1);
                       $scope.InItDelete(); // InItDelete method is available in this controller only.
                       //}
                       // Folder Name: app Folder
                       // Alert Name: deleteSuccessful method is available in alertMessages.js
                       wacorpService.alertDialog(messages.deleteSuccessful);
                   }
                   else if (response != null && response.data != null && response.data == "2") {
                       // Folder Name: app Folder
                       // Alert Name: DeleteCartItemAlreadyProcessed method is available in alertMessages.js
                       wacorpService.alertDialog(messages.ShoppingCart.DeleteCartItemAlreadyProcessed);
                   }
                   else if (response != null && response.data != null && response.data == "3") {
                       // Folder Name: app Folder
                       // Alert Name: DeleteCartItemAlreadyDone method is available in alertMessages.js
                       wacorpService.alertDialog(messages.ShoppingCart.DeleteCartItemAlreadyDone);
                   }
                   else if (response != null && response.data != null && response.data == "4") {
                       // Folder Name: app Folder
                       // Alert Name: DeleteCartItemAlreadyDone method is available in alertMessages.js
                       wacorpService.alertDialog(messages.ShoppingCart.DeleteCartItemUnCommitedTrnsIdProcessed);
                   }
                   else {
                       wacorpService.alertDialog(response.data);
                   }
               },
               function (response) {
                   // Service Folder: services
                   // File Name: wacorpService.js (you can search with file name in solution explorer)
                   wacorpService.alertDialog(response.data);
               }
           );
        });
    };

    $scope.backtoDashboard = function () {
        $location.path('/Dashboard');
    };

    // check out on-click
    $scope.checkOut = function () {
        //OSOS ID--2948--'Undefined' error received in User's Shopping cart when processing multiple filings
        $scope.selectedCarditemsCount = $filter('filter')($scope.model.cartItems, function (item) { return item.isSelect==true });
        var _selectedCarditemsCount = $scope.selectedCarditemsCount;

        if (_selectedCarditemsCount.length > 5) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog("Please limit your checkout selection to 5 or less items per payment transaction. You can do so by selecting/deselecting items with the checkbox on the left of your screen.");
            return false;
        }
        else {
            $scope.ReinstatementARDueChackOut(); // ReinstatementARDueChackOut method is available in this controller only.
            localStorage.removeItem("isOptional")
            //$rootScope.payment = {};
            //$rootScope.payment.cartItems = angular.copy($scope.model.cartItems);
            //$location.path("/cartitems");
        }
    };

    $scope.isFilingHasExpDate = function (item) {
        var found = $.inArray(item.FilingType, FilingTypeHavingExpDate) > -1;
        if (found) {
            item.IsExpedite = true;
            $scope.expediteChange(item);  // expediteChange method is available in this controller only.
        }
        return found;
    };

    //Reinstatement AR Due Chack Out
    $scope.ReinstatementARDueChackOut = function () {
        $scope.AddCurrentARFeeList = [];
        angular.forEach($scope.model.cartItems, function (item) {
            if (item.isAddCurrentARFee && item.isSelect && item.AddCurrentARFee != "Y") {
                $scope.AddCurrentARFeeList.push(item);
            }
        });
        if ($scope.AddCurrentARFeeList.length != 0) {
            $("#divAddCurrentARDueList").modal('toggle');
        }
        else {
            $scope.CallcheckOutProcess(); // CallcheckOutProcess method is available in this controller only.
        }
    };
    //select YES
    $scope.selectAddCurrentARFeeYes = function () {
        var newList = [];

        angular.forEach($scope.AddCurrentARFeeList, function (Value, Key) {
            if (Value.isAddCurrentYear) {
                Value.AddCurrentARFee = "Y";
                newList.push(Value);
            }
        });

        if (newList.length > 0) {
            $("#divAddCurrentARDueList").modal('toggle');
            // webservices.ShoppingCart.checkAmountReactiveUpdateForEntity: checkAmountReactiveUpdateForEntity method is available in constants.js
            wacorpService.post(webservices.ShoppingCart.checkAmountReactiveUpdateForEntity, { CartItems: newList },
                function (response) {

                    angular.forEach(response.data, function (Value, Key) {
                        var item = $filter('filter')($scope.model.cartItems, { ID: Value.ID });
                        if (item.length == 1) {
                            item[0].FilingAmount = Value.FilingAmount;
                            item[0].FilingFee = Value.FilingAmount;
                            item[0].DocumentsList = Value.DocumentsList;
                            item[0].LastARFiledDate = Value.LastARFiledDate;
                        }
                    });

                    $timeout(function () {
                        $scope.CallcheckOutProcess(); // CallcheckOutProcess method is available in this controller only.
                    }, 1000);
                },
                function (error) {

                }
           );
        }
        else {
            // Folder Name: app Folder
            // Alert Name: AtLeastOneItem method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.ShoppingCartAlertMessage.AtLeastOneItem);
        }

    }

    //select No
    $scope.selectAddCurrentARFeeNo = function () {

        $("#divAddCurrentARDueList").modal('toggle');
        $timeout(function () {
            $scope.CallcheckOutProcess(); // CallcheckOutProcess method is available in this controller only.
        }, 500);

    }

    $scope.SelectAddCurrentYear = function () {
        $scope.AddCurrentARFeeList.isAddCurrentYear = true;
    }

    $scope.SelectReinistateAll = function (e) {
        angular.forEach($scope.AddCurrentARFeeList, function (Value, Key) {
            Value.isAddCurrentYear = $scope.model.SelectReinistateAll;
        });
    }

    // check out on-click
    $scope.CallcheckOutProcess = function () {
        $rootScope.payment = {};
        if ($scope.model.cartItems.length > 0) {

            var cartItems = $scope.model.cartItems.sort(function (a, b) {
                return a.FilingType - b.FilingType || a.UBI.localeCompare(b.UBI);
            });

            $scope.filteredItems = $filter('filter')(cartItems, function (item) { return item.isSelect });

            var selectedUBIs = $scope.filteredItems;

            for (var i = 0; i < selectedUBIs.length ; i++) {

                for (var j = i + 1; j < selectedUBIs.length ; j++) {

                    if (selectedUBIs[i].CFTRegistrationNumber && selectedUBIs[i].CFTRegistrationNumber === selectedUBIs[j].CFTRegistrationNumber && selectedUBIs[i].FilingType === selectedUBIs[j].FilingType) {
                        $rootScope.payment.cartItems = angular.copy($scope.model.cartItems);
                        angular.forEach($rootScope.payment.cartItems, function (item1) {
                            item1.isSelect = false;
                        });
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog("You have selected duplicate filing for payment processing.");
                        return false;
                    }
                    else if ((!selectedUBIs[i].CFTRegistrationNumber && selectedUBIs[i].UBI && selectedUBIs[i].UBI === selectedUBIs[j].UBI && selectedUBIs[i].FilingType === selectedUBIs[j].FilingType)) {
                        $rootScope.payment.cartItems = angular.copy($scope.model.cartItems);
                        angular.forEach($rootScope.payment.cartItems, function (item1) {
                            item1.isSelect = false;
                        });
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog("You have selected duplicate filing for payment processing.");
                        return false;
                    }
                  
                }
            }
        }
        $rootScope.payment.cartItems = angular.copy($scope.model.cartItems);
        $location.path("/cartitems");
    }   

        
    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };


    function UBICallBackToProceed() {
        $rootScope.payment.cartItems = angular.copy($scope.model.cartItems);
        $location.path("/cartitems");
        return false;
    }


    $scope.InItDelete = function () {
        //$rootScope.modal = null;
        //$rootScope.transactionID = null;
        //$scope.getData($rootScope.repository.loggedUser.userid, function (data) {
        //    $scope.model.cartItems = data;
        //    if (data.length > 0) {
        //        var flag = true;
        //        angular.forEach($scope.model.cartItems, function (item, index) {
        //            wacorpService.post(webservices.ShoppingCart.checkPaymentAmount, item,
        //              function (response) {
        //                  response.data.UBI = response.data.UBI || "";
        //                  $scope.model.cartItems[index] = response.data;
        //                  if (typeof $rootScope.payment != typeof undefined && $rootScope.payment != null && $rootScope.payment.cartItems.length > 0) {
        //                      angular.forEach($rootScope.payment.cartItems, function (item1) {
        //                          if ($scope.model.cartItems[index].ID == item1.ID && item1.isSelect) {
        //                              $scope.model.cartItems[index].isSelect = item1.isSelect;
        //                              $scope.selectChange($scope.model.cartItems[index]);
        //                          }
        //                      });
        //                  }
        //              });
        //        });
        //        if (typeof $rootScope.payment == typeof undefined || $rootScope.payment == null || $rootScope.payment.cartItems.length == 0) {
        //            //wacorpService.alertDialog($scope.messages.ShoppingCartAlertMessage.AlertMessage);
        //        }
        //    }

        if ($scope.model.cartItems.length > 0) {

            var cartItems = $scope.model.cartItems.sort(function (a, b) {
                    return a.FilingType - b.FilingType || a.UBI.localeCompare(b.UBI);
                });

                $scope.filteredItems = $filter('filter')(cartItems, function (item) { return item.UBI });

                var filteredUBIs = $scope.filteredItems;

                $scope.duplicateUBI = [];
                for (var i = 0; i < filteredUBIs.length ; i++) {
                    for (var j = i + 1; j < filteredUBIs.length ; j++) {

                        if (filteredUBIs[i].CFTRegistrationNumber && filteredUBIs[i].CFTRegistrationNumber === filteredUBIs[j].CFTRegistrationNumber && filteredUBIs[i].FilingType === filteredUBIs[j].FilingType && $scope.duplicateUBI.indexOf(filteredUBIs[i].CFTRegistrationNumber) == -1) {
                            $scope.duplicateUBI.push(filteredUBIs[i].CFTRegistrationNumber);
                        }
                        else if ((!filteredUBIs[i].CFTRegistrationNumber && filteredUBIs[i].UBI && filteredUBIs[i].UBI === filteredUBIs[j].UBI && filteredUBIs[i].FilingType === filteredUBIs[j].FilingType && $scope.duplicateUBI.indexOf(filteredUBIs[i].UBI) == -1)) {
                            $scope.duplicateUBI.push(filteredUBIs[i].UBI);
                        }

                    }
                }
                return $scope.duplicateUBI;
            }
        }


    function  InItCallBack(){
        //$rootScope.modal = null;
        //$rootScope.transactionID = null;
        //$scope.getData($rootScope.repository.loggedUser.userid, function (data) {
        //    $scope.model.cartItems = data;
        //    if (data.length > 0) {
        //        var flag = true;
        //        angular.forEach($scope.model.cartItems, function (item, index) {
        //            wacorpService.post(webservices.ShoppingCart.checkPaymentAmount, item,
        //              function (response) {
        //                  response.data.UBI = response.data.UBI || "";
        //                  $scope.model.cartItems[index] = response.data;
        //                  if (typeof $rootScope.payment != typeof undefined && $rootScope.payment != null && $rootScope.payment.cartItems.length > 0) {
        //                      angular.forEach($rootScope.payment.cartItems, function (item1) {
        //                          if ($scope.model.cartItems[index].ID == item1.ID && item1.isSelect) {
        //                              $scope.model.cartItems[index].isSelect = item1.isSelect;
        //                              $scope.selectChange($scope.model.cartItems[index]);
        //                          }
        //                      });
        //                  }
        //              });
        //        });
        //        if (typeof $rootScope.payment == typeof undefined || $rootScope.payment == null || $rootScope.payment.cartItems.length == 0) {
        //            //wacorpService.alertDialog($scope.messages.ShoppingCartAlertMessage.AlertMessage);
        //        }
        //    }

        if ($scope.model.cartItems.length > 0) {

            var cartItems = $scope.model.cartItems.sort(function (a, b) {
                return a.FilingType - b.FilingType || a.UBI.localeCompare(b.UBI);
            });

            $scope.filteredItems = $filter('filter')(cartItems, function (item) { return item.UBI });

            var filteredUBIs = $scope.filteredItems;

            $scope.duplicateUBI = [];
            for (var i = 0; i < filteredUBIs.length ; i++) {
                for (var j = i + 1; j < filteredUBIs.length ; j++) {

                    if (filteredUBIs[i].CFTRegistrationNumber && filteredUBIs[i].CFTRegistrationNumber === filteredUBIs[j].CFTRegistrationNumber && filteredUBIs[i].FilingType === filteredUBIs[j].FilingType && $scope.duplicateUBI.indexOf(filteredUBIs[i].CFTRegistrationNumber) == -1) {
                        $scope.duplicateUBI.push(filteredUBIs[i].CFTRegistrationNumber);
                    }
                    else if ((!filteredUBIs[i].CFTRegistrationNumber && filteredUBIs[i].UBI && filteredUBIs[i].UBI === filteredUBIs[j].UBI && filteredUBIs[i].FilingType === filteredUBIs[j].FilingType && $scope.duplicateUBI.indexOf(filteredUBIs[i].UBI) == -1)) {
                        $scope.duplicateUBI.push(filteredUBIs[i].UBI);
                    }

                }
            }
            return $scope.duplicateUBI;
        }
    }
});
wacorpApp.controller('draftFilingController', function ($scope, $q, $http, $filter, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    
    $scope.modal = {};
    $scope.DraftFilingsPending = [];


    // load draft filings
    $scope.init = function () {
        var data = { params: { id: $rootScope.repository.loggedUser.userid } };
        //webservices.DraftFilings.getDraftData: getDraftData method is available in constants.js 
        wacorpService.get(webservices.DraftFilings.getDraftData,data, function (response) {
            
            $scope.DraftFilingsPending = response.data;
        });
    };

    //to edit selected draft filing
    $scope.edit = function (cartId, FilingType, BusinessTypeId) {
        $rootScope.modal = null;
        var cartlist = $filter('filter')($scope.DraftFilingsPending, { ID: cartId });
        if (cartlist.length > 0)
        {
            
            $rootScope.modal = JSON.parse(cartlist[0].FilingObject);
            if ($rootScope.modal.FEINNumber != null && $rootScope.modal.FEINNumber != '' && $rootScope.modal.FEINNumber != undefined) {
                $rootScope.modal.FEINNumber = $rootScope.modal.FEINNumber;
            }

            $rootScope.isIncompleteFiling = true;

            $rootScope.modal.OnlineCartDraftID = cartId;
            if ($rootScope.modal.OnlineNavigationUrl == "/CopyRequest") {
               
                $rootScope.cftType = $rootScope.modal.CFTType;
                if ($rootScope.modal.CharitiesEntityInfo) {
                    $rootScope.modal.BusinessInfo.BusinessID = $rootScope.modal.CharitiesEntityInfo.CFTId;
                }
                else {
                    $rootScope.modal.BusinessInfo.BusinessID = $rootScope.modal.BusinessInfo.BusinessID
                }
               
                $location.path($rootScope.modal.OnlineNavigationUrl + '/' + $rootScope.modal.BusinessInfo.BusinessID);
            }
            else {
                $location.path($rootScope.modal.OnlineNavigationUrl);
            }
       
        }
    }   

    //to delete  selected draft filing
    $scope.delete = function (index, currentItem) {
        // Folder Name: app Folder
        // Alert Name: ConfirmMessage method is available in alertMessages.js 
        wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
            var config = { params: { ID: currentItem.ID } };
            // deleteDraftFilingById method is available in constants.js
            wacorpService.get(webservices.DraftFilings.deleteDraftFilingById, config,
               function (response) {
                   var itemIndex = $scope.DraftFilingsPending.indexOf(currentItem);
                   $scope.DraftFilingsPending.splice(itemIndex, 1);
                   // Folder Name: app Folder
                   // Alert Name: deleteSuccessful method is available in alertMessages.js 
                   wacorpService.alertDialog(messages.deleteSuccessful);
               },
          function (response) {
              // Service Folder: services
              // File Name: wacorpService.js (you can search with file name in solution explorer)
                   wacorpService.alertDialog(response.data);
               }
           );
          });
    };
    
    $scope.backtoDashboard = function () {
        $location.path('/Dashboard');
    };

    $scope.FEINFormat=function (value) {
    
    }

    //$scope.propertyName = 'FilingDate';
    //$scope.reverse = true;

    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };
     
});
wacorpApp.controller('paymentController', function ($scope, $rootScope, $location, $http, wacorpService, lookupService, $timeout) {
    $rootScope.isPlaceYourOrderButtonDisable = false;
    $scope.model = {};
    $scope.messages = messages;
    $scope.WorkOrderNumber = ""; // work order number
    if ($rootScope.payment) {
        $scope.model = {
            payment: angular.copy($rootScope.payment),
            paymentInfo: { Amount: $rootScope.payment.Amount },
            billingAddress: { State: "WA", Country: "USA" },
            shippingInfo: {
                shippingAddress: { State: "WA", Country: "USA" }
            }
        }
    }
    else {
        $location.path('/shoppingcart');
    }
    $scope.Countries = [];
    $scope.States = [];
    //Get Countries List
    $scope.getCountries = function () {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.countriesList(function (response) { $scope.Countries = response.data; });
    };

    //Get States List
    $scope.getStates = function () {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.statesList(function (response) {
            $scope.States = response.data;
            $scope.InitLoadCountry(); // InitLoadCountry method is available in constants.js
        });
    };

    $scope.getCountries(); // getCountries method is available in constants.js
    $scope.getStates();  // getStates method is available in constants.js

    angular.element("#txtFirstName").focus();

    // process payment (This function not using for refrence perpus)
    $scope.processPayment = function (paymentForm) {
        $scope.showErroMessages = true;
        if ($scope[paymentForm].$valid) {
            $scope.showErroMessages = false;
            $scope.model.billingAddress.PostalCode = $scope.model.billingAddress.Country === 'USA' ?
            $scope.model.billingAddress.Zip5 + '-' + $scope.model.billingAddress.Zip4 : $scope.model.billingAddress.PostalCode;

            $scope.model.billingAddress.State = $scope.model.billingAddress.Country === 'USA' || $scope.model.billingAddress.Country === 'CAN'?
                $scope.model.billingAddress.State : $scope.model.billingAddress.OtherState;

            $scope.model.shippingInfo.shippingAddress.PostalCode = $scope.model.shippingInfo.shippingAddress.Country === 'USA' ?
            $scope.model.shippingInfo.shippingAddress.Zip5 + '-' + $scope.model.shippingInfo.shippingAddress.Zip4 : $scope.model.shippingInfo.shippingAddress.PostalCode;

            $scope.model.shippingInfo.shippingAddress.State = $scope.model.shippingInfo.shippingAddress.Country === 'USA' ?
                $scope.model.shippingInfo.shippingAddress.State : $scope.model.shippingInfo.shippingAddress.OtherState;

            if ($scope.model.paymentInfo.BillToPhoneNumber != undefined && $scope.model.paymentInfo.BillToPhoneNumber != 'undefined' && $scope.model.paymentInfo.BillToPhoneNumber != null) {
                $scope.model.paymentInfo.BillToPhoneNumber = $scope.model.paymentInfo.BillToPhoneNumber.replace("-", "");
            }

            var data = angular.extend({}, $scope.model.paymentInfo);
            data.PaymentType = $scope.model.billingAddress;
            data.BillingAddress = $scope.model.billingAddress;
            data.ShippingAddress = $scope.model.shippingInfo.shippingAddress;
            data.CompanyName = $scope.model.shippingInfo.CompanyName;
            data.ShippingName = $scope.model.shippingInfo.ShippingName;
            data.BusinessTransactions = [];
            if ($scope.user != undefined && $scope.user != 'undefined' && $scope.user != null && $scope.user.FilerTypeId == filerType.CommercialRegisteredAgent) {
                var today = new Date();
                var dd = today.getDate();
                var mm = today.getMonth() + 1; //January is 0!

                var yyyy = today.getFullYear();
                if (dd < 10) {
                    dd = '0' + dd
                }
                if (mm < 10) {
                    mm = '0' + mm
                }
                var todayDate = dd + '/' + mm + '/' + yyyy;

                data.BusinessTransactions.push(
                      {
                          // here BusinessTypeID: 11 is COMMERCIAL REGISTERED AGENT
                          BusinessTypeID: 11,
                          BusinessType: filerType.CommercialListingStatement,
                          DateTimeReceived: todayDate,
                      })
            }
            else {
                angular.forEach($scope.model.payment.cartItems, function (item) {
                    data.BusinessTransactions.push(
                        {
                            BusinessTypeID: ((item.BusinessTypeId != "" || item.BusinessTypeId != undefined) ? item.BusinessTypeId : ''),
                            BusinessID: ((item.BusinessID != "" || item.BusinessID != undefined) ? item.BusinessID : ''),
                            BusinessType: item.FilingType,
                            DateTimeReceived: item.CreatedDateTime,
                            DocumentsList: item.DocumentsList
                        })
                });
            }

            data.Amount = $scope.model.payment.Amount;
            data.CreatedBy = angular.isNullorEmpty($rootScope.repository.loggedUser) ? null : $rootScope.repository.loggedUser.userid;
            data.UserID = -1;
            data.IsOnline = true;
            data.WorkOrderNumber = $scope.WorkOrderNumber; // work order number

            if ($rootScope.payment.isUserPayment) {
                // Folder Name: controller/Account 
                // Controller Name: registerController.js (you can search with file name in solution explorer)
                $scope.makeUserPayment(data); 
            }
            else if ($rootScope.payment.isOneClickAR) {
                // Folder Name: controller/OneClickAnnualReport 
                // Controller Name: oneClickAnnualReportController.js (you can search with file name in solution explorer)
                $scope.oneClickARMakePayment(data); 
            }
            else if ($rootScope.payment.isExpressAR) {
                // Folder Name: controller/ExpressAnnualReport 
                // Controller Name: expressAnnualReportReviewController.js (you can search with file name in solution explorer)
                $scope.expressARMakePayment(data); 
            }
            else {
                if ($rootScope.repository.loggedUser != undefined)
                    $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                $http({
                    method: 'POST',
                    url: webservices.ShoppingCart.processPayment, // processPayment method is available in constants.js
                    data: data,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).then(
               function (response) {
                   // work order number
                   data.WorkOrderNumber = response.data.WorkOrderNumber;
                   $scope.WorkOrderNumber = response.data.WorkOrderNumber;
                   // Payment success 
                   if (response.data.IsSuccess) {
                       data.UncommitedTransactionID = response.data.UncommitedTransactionID;
                       processPay(response, data);
                   }
                   else {
                       // Payment Fails
                       if (response.data.ErrorMessage == null || response.data.ErrorMessage == "" || response.data.ErrorMessage == "<br/>") {
                           // Folder Name: app Folder
                           // Alert Name: Payment method is available in alertMessages.js 
                           wacorpService.alertDialog($scope.messages.ShoppingCart.Payment);
                       } else {
                           // Service Folder: services
                           // File Name: wacorpService.js (you can search with file name in solution explorer)
                           wacorpService.alertDialog(response.data.ErrorMessage);
                       }
                   }
               },
        function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        }
           );
            }

        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    $scope.getCardType = function () {
        //$('#ddlCardType').find('option').each(function () {
        //        if($(this).val()==$scope.model.paymentInfo.PaymentTypeId)
        //        {
        //            $scope.model.paymentInfo.CardType = $(this).text();
        //        }
        //    });
        $scope.model.paymentInfo.CardType = $(event.target || event.srcElement).find("option:selected").text();
    }

    function type1(e) {
        alert(e);
    }

    function processPay(response, data) {

        var cartIds = [];
        var amount = 0;
        var expediteAmount = 0;
        var IsExpedite = [];
        var ExpediteAmountList = [];
        var CartItems = [];
        angular.forEach($scope.model.payment.cartItems, function (item) {
            cartIds.push(item.ID);
            IsExpedite.push(angular.isNullorEmpty(item) ? false : item.IsExpedite);
            //if (!angular.isNullorEmpty(item) && item.IsExpedite) {
            amount = $scope.model.payment.Amount;
            //    ExpediteAmountList.push(constant.ExpdateAmount);
            //}
            //else {
            //    amount += item.FilingAmount;
                ExpediteAmountList.push(0);
            //}
            CartItems.push(item);
        });
        onlineCartInfo = {
            IsPayment: true, CartIds: cartIds, TotalAmount: amount, IsExpediteAmount: ExpediteAmountList,
            IsExpeditelist: IsExpedite, UserId: $rootScope.repository.loggedUser.userid, PaymentInfo: data,
            CartItems: CartItems,
        }
        // update is payment in cart table
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: webservices.ShoppingCart.updatePayments, // updatePayments method is available in constants.js
            data: onlineCartInfo
        }).then(function (response) {
            $rootScope.paymentDone = response.data;
            $rootScope.payment = null;
            $location.path('/paymentdone');
        },
        function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data.ErrorDescription);
        });
    }

    $scope.setCardType = function (obj) {
        var CardType = $(obj).text();
    };

    function makeUserRegistrationPayment(data) {
        // addToCart method is available in constants.js
        wacorpService.post(webservices.UserAccount.addToCart, $scope.model.payment.cartItems, function (result) {
            if ($rootScope.repository.loggedUser != undefined)
                $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
            $http({
                method: 'POST',
                url: webservices.ShoppingCart.processPayment, // processPayment method is available in constants.js
                data: data,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(
                          function (response) {
                              if (response.data.IsSuccess) {
                                  var cartIds = [];
                                  var amount = 0;
                                  var IsExpedite = [];
                                  cartIds.push(result.data.ID);
                                  amount = $scope.model.payment.Amount;
                                  IsExpedite.push(result.data.IsExpedite);
                                  onlineCartInfo = { IsPayment: true, CartIds: cartIds, TotalAmount: amount, IsExpeditelist: IsExpedite, UserId: $scope.model.payment.cartItems.CreatedBy, PaymentInfo: data }
                                  // update ispayment in cart table
                                  $http({
                                      method: 'POST',
                                      url: webservices.ShoppingCart.updatePayments, // updatePayments method is available in constants.js
                                      data: onlineCartInfo
                                  }).then(function (response) {
                                      $scope.saveUser();
                                  },
                                  function (response) {
                                      // Service Folder: services
                                      // File Name: wacorpService.js (you can search with file name in solution explorer)
                                      wacorpService.alertDialog(response.data.ErrorDescription);
                                  });
                              }
                              else {
                                  // Service Folder: services
                                  // File Name: wacorpService.js (you can search with file name in solution explorer)
                                  wacorpService.alertDialog(response.data.ErrorDescription);
                              }
                          },
                          function (response) {
                              // Service Folder: services
                              // File Name: wacorpService.js (you can search with file name in solution explorer)
                              wacorpService.alertDialog(response.data);
                          }
                      );

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });

    }

    // bill
    $scope.$watch('model.billingAddress', function () { $scope.sameAsBillingAddress() }, true);

    // same as Billing Address
    $scope.sameAsBillingAddress = function () {
        if ($scope.model.sameAsBillingAddress) {
            var bAddress = $scope.model.billingAddress;
            $scope.model.shippingInfo.shippingAddress = {
                StreetAddress1: bAddress.StreetAddress1,
                City: bAddress.City,
                Country: bAddress.Country,
                State: bAddress.State,
                Zip5: bAddress.Zip5,
                Zip4: bAddress.Zip4,
                OtherState: bAddress.OtherState,
                PostalCode: bAddress.PostalCode
            };
        }
        else {
            if ($scope.model.shippingInfo != undefined)
                $scope.model.shippingInfo.shippingAddress = { State: "WA", Country: "USA" };
        }
    };

    // back button click
    $scope.back = function () {
        if ($rootScope.payment.isUserPayment) {
            // Folder Name: controller\Account
            // Controller Name: registerController.js
            $scope.backFromPayment();
        }
        else if ($rootScope.payment.isOneClickAR) {
            // Folder Name: controller\OneClickAnnualReport
            // Controller Name: oneClickAnnualReportController.js           
            $scope.oneClickARBackFromPayment();
        }
        else if ($rootScope.payment.isExpressAR) {
            // Folder Name: controller\ExpressAnnualReport
            // Controller Name: expressAnnualReportReviewController.js
            $scope.expressARBackFromPayment(); 
        }
        else {
            $rootScope.payment = { cartItems: $scope.model.payment.cartItems };
            $location.path('/cartitems');
        }
    };

    //USPS Address Validation on city blur
    //Payment Information Section(Billing Address)

    $scope.isRunning = false;
    $scope.isValidAddress = false;
    $scope.$watch("model.billingAddress", function () {
        $scope.isValidAddress = false;
    }, true);


    $scope.getBillingValidAddress = function () {
        if ($scope.isValidAddress || $scope.isRunning) return false;

        if (isUSPSServiceValid && $scope.model.billingAddress.StreetAddress1 != "") {
            var addressorg = {
                Address1: $scope.model.billingAddress.StreetAddress1,
                City: $scope.model.billingAddress.City,
                State: $scope.model.billingAddress.State,
                Zip5: $scope.model.billingAddress.Zip5,
                Zip4: $scope.model.billingAddress.Zip4,
            };

            var isvalusExist = (angular.isDefined(addressorg.Address1) && !angular.isNullorEmpty(addressorg.Address1)
                              && angular.isDefined(addressorg.City) && !angular.isNullorEmpty(addressorg.City)
                              && angular.isDefined(addressorg.State) && !angular.isNullorEmpty(addressorg.State))
                              && (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5));

            if ($scope.model.billingAddress.Country === codes.USA && isvalusExist) {
                $scope.isRunning = true;
                // getValidAddress method is available in constants.js
                wacorpService.post(webservices.Common.getValidAddress, addressorg, function (response) {
                    var result = response.data;
                    if (result.HasErrors) {
                        if (result.ErrorDescription.trim() == "Invalid City." || result.ErrorDescription.trim() == "Invalid Zip Code.") {
                            wacorpService.alertDialog(result.ErrorDescription);
                            $scope.model.billingAddress.Zip5 = '';
                            $scope.model.billingAddress.Zip4 = '';
                        }
                        else {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog(result.ErrorDescription);
                        }

                    }
                    else if (result.IsAddressModifed) {
                        // Folder Name: app Folder
                        // Alert Name: invalidAddressData method is available in alertMessages.js 
                        wacorpService.confirmDialog($scope.messages.Address.invalidAddressData, function () {
                            $scope.model.billingAddress.StreetAddress1 = result.Address1;
                            $scope.model.billingAddress.Zip5 = result.Zip5;
                            $scope.model.billingAddress.Zip4 = result.Zip4;
                            $scope.model.billingAddress.City = result.City;
                            $scope.model.billingAddress.State = result.State;
                            $timeout(function () {
                                $scope.isValidAddress = true;
                            }, 1000);
                        });
                    }
                    else {
                        $timeout(function () {
                            $scope.isValidAddress = true;
                        }, 1000);

                        $scope.model.billingAddress.Zip4 = result.Zip4;
                    }

                    $timeout(function () {
                        $scope.isRunning = false;
                    }, 1000);

                }, function (response) {
                    $scope.isRunning = false;
                });
            }
        }
    }

    //Get City State on Zip5 blur
    //Payment Information Section(Billing Address)
    $scope.getBillingCityStateAddress = function () {
        if ($scope.isValidAddress || $scope.isRunning) return false;

        var addressorg = {
            Address1: $scope.model.billingAddress.StreetAddress1,
            Address2: $scope.model.billingAddress.StreetAddress2,
            City: $scope.model.billingAddress.City,
            State: $scope.model.billingAddress.State,
            Zip5: $scope.model.billingAddress.Zip5,
            Zip4: $scope.model.billingAddress.Zip4,
        };

        var isvalusExist = (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5));

        if (isvalusExist) {
            wacorpService.post(webservices.Common.getCityStateZip, addressorg, function (response) {
                var result = response.data;
                if (result.HasErrors) {
                    // Folder Name: app Folder
                    // Alert Name: validZipExtension method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.Address.validZipExtension);
                    $scope.model.billingAddress.Zip5 = '';
                    $scope.model.billingAddress.Zip4 = '';
                    $scope.model.billingAddress.City = '';
                    $scope.model.billingAddress.State = 'WA';
                }
                else {
                    $scope.model.billingAddress.Zip5 = result.Zip5;
                    $scope.model.billingAddress.Zip4 = result.Zip4;
                    $scope.model.billingAddress.City = result.City;
                    $scope.model.billingAddress.State = result.State;
                    $scope.getBillingValidAddress(); // getBillingValidAddress method is available in this controller only.
                }
            }, function (response) { });
        }

    }


    //USPS Address Validation on city blur
    //Payment Information Section(Billing Address)
    $scope.getShippingValidAddress = function () {
        if (isUSPSServiceValid && $scope.model.shippingInfo.shippingAddress.StreetAddress1 != "") {
            var addressorg = {
                Address1: $scope.model.shippingInfo.shippingAddress.StreetAddress1,
                City: $scope.model.shippingInfo.shippingAddress.City,
                State: $scope.model.shippingInfo.shippingAddress.State,
                Zip5: $scope.model.shippingInfo.shippingAddress.Zip5,
                Zip4: $scope.model.shippingInfo.shippingAddress.Zip4,
            };

            var isvalusExist = (angular.isDefined(addressorg.Address1) && !angular.isNullorEmpty(addressorg.Address1)
                              && angular.isDefined(addressorg.City) && !angular.isNullorEmpty(addressorg.City)
                              && angular.isDefined(addressorg.State) && !angular.isNullorEmpty(addressorg.State))
                              && (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5));

            if ($scope.model.shippingInfo.shippingAddress.Country === codes.USA && isvalusExist) {
                // getValidAddress method is available in constants.js
                wacorpService.post(webservices.Common.getValidAddress, addressorg, function (response) {
                    var result = response.data;
                    if (result.HasErrors) {
                        if (result.ErrorDescription.trim() == "Invalid City." || result.ErrorDescription.trim() == "Invalid Zip Code.") {
                            wacorpService.alertDialog(result.ErrorDescription);
                            $scope.model.shippingInfo.shippingAddress.Zip5 = '';
                            $scope.model.shippingInfo.shippingAddress.Zip4 = '';
                        }
                        else {
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            wacorpService.alertDialog(result.ErrorDescription);
                        }

                    }

                    else if (result.IsAddressModifed) {
                        if ($scope.isAgentAddress) {
                            if (result.State == codes.WA) {
                                // Folder Name: app Folder
                                // Alert Name: invalidAddressData method is available in alertMessages.js
                                wacorpService.confirmDialog($scope.messages.Address.invalidAddressData, function () {
                                    $scope.model.shippingInfo.shippingAddress.Zip5 = result.Zip5;
                                    $scope.model.shippingInfo.shippingAddress.Zip4 = result.Zip4;
                                    $scope.model.shippingInfo.shippingAddress.City = result.City;
                                    $scope.model.shippingInfo.shippingAddress.State = result.State;
                                });
                            }
                            else
                                // Folder Name: app Folder
                                // Alert Name: notWashingtonAddress method is available in alertMessages.js
                                wacorpService.alertDialog($scope.messages.Address.notWashingtonAddress);
                        }
                        else {
                            // Folder Name: app Folder
                            // Alert Name: invalidAddressData method is available in alertMessages.js 
                            wacorpService.confirmDialog($scope.messages.Address.invalidAddressData, function () {
                                $scope.model.shippingInfo.shippingAddress.Zip5 = result.Zip5;
                                $scope.model.shippingInfo.shippingAddress.Zip4 = result.Zip4;
                                $scope.model.shippingInfo.shippingAddress.City = result.City;
                                $scope.model.shippingInfo.shippingAddress.State = result.State;
                            });
                        }
                    }
                    else {
                        $scope.model.shippingInfo.shippingAddress.Zip4 = result.Zip4;
                    }
                }, function (response) { });
            }
        }
    }

    //Get City State on Zip5 blur
    //Payment Information Section(Billing Address)
    $scope.getShippingCityStateAddress = function () {
        var addressorg = {
            Address1: $scope.model.shippingInfo.shippingAddress.StreetAddress1,
            Address2: $scope.model.shippingInfo.shippingAddress.StreetAddress2,
            City: $scope.model.shippingInfo.shippingAddress.City,
            State: $scope.model.shippingInfo.shippingAddress.State,
            Zip5: $scope.model.shippingInfo.shippingAddress.Zip5,
            Zip4: $scope.model.shippingInfo.shippingAddress.Zip4,
        };

        var isvalusExist = (angular.isDefined(addressorg.Zip5) && !angular.isNullorEmpty(addressorg.Zip5));

        if (isvalusExist) {
            // getCityStateZip method is available in constants.js
            wacorpService.post(webservices.Common.getCityStateZip, addressorg, function (response) {
                var result = response.data;
                if (result.HasErrors) {
                    // Folder Name: app Folder
                    // Alert Name: validZipExtension method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.Address.validZipExtension);
                    $scope.model.shippingInfo.shippingAddress.Zip5 = '';
                    $scope.model.shippingInfo.shippingAddress.Zip4 = '';
                    $scope.model.shippingInfo.shippingAddress.City = '';
                    $scope.model.shippingInfo.shippingAddress.State = 'WA';
                }
                else {
                    if ($scope.isAgentAddress) {
                        if (result.State == codes.WA) {
                            // wacorpService.confirmDialog($scope.messages.Address.invalidCityState, function () {
                            $scope.model.shippingInfo.shippingAddress.Zip5 = result.Zip5;
                            $scope.model.shippingInfo.shippingAddress.Zip4 = result.Zip4;
                            $scope.model.shippingInfo.shippingAddress.City = result.City;
                            $scope.model.shippingInfo.shippingAddress.State = result.State;
                            $scope.getShippingValidAddress(); // getShippingValidAddress method is available in this controller only.
                            //  });
                        }
                        else
                            // Folder Name: app Folder
                            // Alert Name: notWashingtonAddress method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.Address.notWashingtonAddress);
                    }
                    else {
                        // wacorpService.confirmDialog($scope.messages.Address.invalidCityState, function () {
                        $scope.model.shippingInfo.shippingAddress.Zip5 = result.Zip5;
                        $scope.model.shippingInfo.shippingAddress.Zip4 = result.Zip4;
                        $scope.model.shippingInfo.shippingAddress.City = result.City;
                        $scope.model.shippingInfo.shippingAddress.State = result.State;
                        $scope.getShippingValidAddress();  // getShippingValidAddress method is available in this controller only.
                        // });
                    }
                }
            }, function (response) { });
        }

    }

     /* New chagnes for Canada */

            $scope.requiredStatesForCountry = ["USA", "CAN"];
            var canadaStates = ["AB", "BC", "MB", "NB", "NL", "NS", "NT", "NU", "ON", "PE", "QC", "SK", "YT"];
            $scope.statesArray = [];

            $scope.changeCountry = function ()
            {
                //var $country = angular.element(event.target);
                if ($scope.requiredStatesForCountry.indexOf($scope.model.billingAddress.Country) > -1) {

                    if ($scope.statesArray.length == 0)
                        angular.copy($scope.States, $scope.statesArray);

                    $scope.States.length = 0;

                    angular.forEach($scope.statesArray, function (data, index) {
                        if (canadaStates.indexOf(data.Key) > -1 && $scope.model.billingAddress.Country == "CAN") {
                            $scope.States.push(data);
                        }
                        else if (canadaStates.indexOf(data.Key) == -1 && $scope.model.billingAddress.Country == "USA") {
                            $scope.States.push(data);
                        }
                    });

                    // set default state
                    $timeout(function () {
                        if ($scope.model.billingAddress.State == "" && $scope.model.billingAddress.Country == "USA"){
                            $scope.model.billingAddress.State = "WA";
                            $scope.model.billingAddress.PostalCode = '';
                        }
                        else if ($scope.model.billingAddress.Country == "CAN")
                            $scope.model.billingAddress.State = "";
                        else if (canadaStates.indexOf($scope.model.billingAddress.State) == -1 && $scope.model.billingAddress.Country == "USA") {
                            $scope.model.billingAddress.PostalCode = '';
                        }
                    }, 200);

                    if ($scope.model.billingAddress.Country == "USA") {
                        $scope.model.billingAddress.PostalCode = '';
                    }
                    else if ($scope.model.billingAddress.Country == "CAN") {
                        $scope.model.billingAddress.Zip5 = '';
                        $scope.model.billingAddress.Zip4 = '';
                    }
                }
            }

            $scope.InitLoadCountry = function () {
                if ($scope.requiredStatesForCountry.indexOf($scope.model.billingAddress.Country) > -1) {

                    if ($scope.statesArray.length == 0)
                        angular.copy($scope.States, $scope.statesArray);

                    $scope.States.length = 0;

                    angular.forEach($scope.statesArray, function (data, index) {
                        if (canadaStates.indexOf(data.Key) > -1 && $scope.model.billingAddress.Country == "CAN") {
                            $scope.States.push(data);
                        }
                        else if (canadaStates.indexOf(data.Key) == -1 && $scope.model.billingAddress.Country == "USA") {
                            $scope.States.push(data);
                        }
                    });

                    // set default state
                    $timeout(function () {
                        if ($scope.model.billingAddress.State == "" && $scope.model.billingAddress.Country == "USA")
                            $scope.model.billingAddress.State = "WA";
                        else if ($scope.model.billingAddress.Country == "CAN")
                            $scope.model.billingAddress.State = "";
                    }, 200);
                }
            }

    // Shopping cart Payment Currently we are using this method for process Payment 
            $scope.shoppingCartPayment = function (paymentForm) {
                $rootScope.isPlaceYourOrderButtonDisable = true;
                
                $scope.showErroMessages = true;
                if ($scope[paymentForm].$valid) {

                    $scope.showErroMessages = false;
                    $scope.model.billingAddress.PostalCode = $scope.model.billingAddress.Country === 'USA' ?
                    $scope.model.billingAddress.Zip5 + '-' + $scope.model.billingAddress.Zip4 : $scope.model.billingAddress.PostalCode;

                    $scope.model.billingAddress.State = $scope.model.billingAddress.Country === 'USA' || $scope.model.billingAddress.Country === 'CAN' ?
                        $scope.model.billingAddress.State : $scope.model.billingAddress.OtherState;

                    $scope.model.shippingInfo.shippingAddress.PostalCode = $scope.model.shippingInfo.shippingAddress.Country === 'USA' ?
                    $scope.model.shippingInfo.shippingAddress.Zip5 + '-' + $scope.model.shippingInfo.shippingAddress.Zip4 : $scope.model.shippingInfo.shippingAddress.PostalCode;

                    $scope.model.shippingInfo.shippingAddress.State = $scope.model.shippingInfo.shippingAddress.Country === 'USA' ?
                        $scope.model.shippingInfo.shippingAddress.State : $scope.model.shippingInfo.shippingAddress.OtherState;

                    if ($scope.model.paymentInfo.BillToPhoneNumber != undefined && $scope.model.paymentInfo.BillToPhoneNumber != 'undefined' && $scope.model.paymentInfo.BillToPhoneNumber != null) {
                        $scope.model.paymentInfo.BillToPhoneNumber = $scope.model.paymentInfo.BillToPhoneNumber.replace("-", "");
                    }

                    if ($rootScope.repository && $rootScope.repository.loggedUser) {
                        $scope.model.paymentInfo.NTUser = $rootScope.repository.loggedUser.username ? $rootScope.repository.loggedUser.username.toUpperCase() : $rootScope.repository.loggedUser.username;
                    }

                    var data = angular.extend({}, $scope.model.paymentInfo);
                    data.PaymentType = $scope.model.billingAddress;
                    data.BillingAddress = $scope.model.billingAddress;
                    data.ShippingAddress = $scope.model.shippingInfo.shippingAddress;
                    data.CompanyName = $scope.model.shippingInfo.CompanyName;
                    data.ShippingName = $scope.model.shippingInfo.ShippingName;
                    data.BusinessTransactions = [];
                    if ($scope.user != undefined && $scope.user != 'undefined' && $scope.user != null && $scope.user.FilerTypeId == filerType.CommercialRegisteredAgent) {
                        var today = new Date();
                        var dd = today.getDate();
                        var mm = today.getMonth() + 1; //January is 0!

                        var yyyy = today.getFullYear();
                        if (dd < 10) {
                            dd = '0' + dd
                        }
                        if (mm < 10) {
                            mm = '0' + mm
                        }
                        var todayDate = dd + '/' + mm + '/' + yyyy;

                        data.BusinessTransactions.push(
                            {
                                BusinessTypeID: 11,
                                BusinessType: filerType.CommercialListingStatement,
                                DateTimeReceived: todayDate,
                            });
                    }
                    else {
                        angular.forEach($scope.model.payment.cartItems, function (item) {
                            data.BusinessTransactions.push(
                                {
                                    BusinessTypeID: ((item.BusinessTypeId != "" || item.BusinessTypeId != undefined)
                                        ? item.BusinessTypeId
                                        : ''),
                                    BusinessID: ((item.BusinessID != "" || item.BusinessID != undefined)
                                        ? item.BusinessID
                                        : ''),
                                    BusinessType: item.FilingType,
                                    DateTimeReceived: item.CreatedDateTime,
                                    DocumentsList: item.DocumentsList
                                });
                        });
                    }

                    data.Amount = $scope.model.payment.Amount;
                    data.CreatedBy = angular.isNullorEmpty($rootScope.repository.loggedUser) ? null : $rootScope.repository.loggedUser.userid;
                    data.UserID = -1;
                    data.IsOnline = true;
                    data.WorkOrderNumber = $scope.WorkOrderNumber; // work order number
                    if ($rootScope.payment.isUserPayment) {
                        data.NTUser = $rootScope.RegisteredUserName ? $rootScope.RegisteredUserName.toUpperCase() : $rootScope.RegisteredUserName;
                        // Folder Name: controller/Account 
                        // Controller Name: registerController.js (you can search with file name in solution explorer)
                        $scope.makeUserPayment(data); 
                    }
                    else if ($rootScope.payment.isOneClickAR) {
                        data.NTUser = "Express";                        
                        // Folder Name: controller/OneClickAnnualReport 
                        // Controller Name: oneClickAnnualReportController.js (you can search with file name in solution explorer)
                        $scope.oneClickARMakePayment(data);
                    }
                    else if ($rootScope.payment.isExpressAR) {
                        data.NTUser = "Express";
                        // Folder Name: controller/ExpressAnnualReport 
                        // Controller Name: expressAnnualReportReviewController.js (you can search with file name in solution explorer)
                        $scope.expressARMakePayment(data);
                    }
                    else {
                        var cartIds = [];
                        var amount = 0;
                        var expediteAmount = 0;
                        var IsExpedite = [];
                        var ExpediteAmountList = [];
                        var CartItems = [];
                        var alretMessage = "";
                        angular.forEach($scope.model.payment.cartItems, function (item) {
                            cartIds.push(item.ID);
                            IsExpedite.push(angular.isNullorEmpty(item) ? false : item.IsExpedite);
                            amount = $scope.model.payment.Amount;
                            ExpediteAmountList.push(0);
                            CartItems.push(item);
                        });
                        onlineCartInfo = {
                            IsPayment: true, CartIds: cartIds, TotalAmount: amount, IsExpediteAmount: ExpediteAmountList,
                            IsExpeditelist: IsExpedite, UserId: $rootScope.repository.loggedUser.userid, PaymentInfo: data,
                            CartItems: CartItems,
                        }
                        // update is payment in cart table
                        if ($rootScope.repository.loggedUser != undefined) {
                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
                            $http({
                                method: 'POST',
                                url: webservices.ShoppingCart.shoppingCartPayment, // shoppingCartPayment method is available in constants.js
                                data: onlineCartInfo
                            }).then(
                            function (response) {
                                // Payment success 
                                if (response.data.IsSuccess) {
                                    $rootScope.paymentDone = response.data;
                                    $rootScope.payment = null;
                                    $location.path('/paymentdone');
                                }
                                else if (!response.data.IsSuccess) { // Payment Failed reasons 
                                    $rootScope.isPlaceYourOrderButtonDisable = false; // Is cart payment is failed Place Your Order Button is enabled

                                    if (response.data.IsShoppingCartResult == 1) { //Payment Fails
                                        if (response.data.ErrorMessage == null || response.data.ErrorMessage == "" || response.data.ErrorMessage == "<br/>") {
                                            // Folder Name: app Folder
                                            // Alert Name: Payment method is available in alertMessages.js 
                                            wacorpService.alertDialog($scope.messages.ShoppingCart.Payment);
                                        } else {
                                            // Service Folder: services
                                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                                            wacorpService.alertDialog(response.data.ErrorMessage);
                                        }
                                    }
                                    else if (response.data.IsShoppingCartResult == 2) { // Cart processiing by another user
                                        angular.forEach(response.data.CartItems, function (value) {
                                            if (value.IsShoppingCartResult == 2) {
                                                alretMessage += value.BusinessName + " ( " + value.FilingType + " ), ";
                                            }
                                        })
                                        // Folder Name: app Folder
                                        // Alert Name: AlreadyCartItemIsProcessed method is available in alertMessages.js 
                                        wacorpService.alertDialog($scope.messages.ShoppingCart.AlreadyCartItemIsProcessed.replace('{0}', alretMessage));
                                    }
                                    else if (response.data.IsShoppingCartResult == 3) {  // Cart item deleted 
                                        angular.forEach(response.data.CartItems, function (value) {
                                            if (value.IsShoppingCartResult == 3) {
                                                alretMessage += value.BusinessName + " ( " + value.FilingType + " ), ";
                                            }
                                        })
                                        // Folder Name: app Folder
                                        // Alert Name: CartItemIsDeleted method is available in alertMessages.js 
                                        wacorpService.alertDialog($scope.messages.ShoppingCart.CartItemIsDeleted.replace('{0}', alretMessage));
                                    }
                                    else if (response.data.IsShoppingCartResult == 4) {  // AR Already Filed
                                        angular.forEach(response.data.CartItems, function (value) {
                                            if (value.IsShoppingCartResult == 4) {
                                                // Folder Name: app Folder
                                                // Alert Name: AnnualReportAlreadyFiled method is available in alertMessages.js 
                                                alretMessage += $scope.messages.ShoppingCart.AnnualReportAlreadyFiled.replace('{0}', value.BusinessName).replace('{0}', value.ErrorMessage)
                                            }
                                        })
                                        // Service Folder: services
                                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                                        wacorpService.alertDialog(alretMessage);
                                    }
                                    else if (response.data.IsShoppingCartResult == 5) {  // Payment Amount Mismatched
                                        // Folder Name: app Folder
                                        // Alert Name: PaymentAmountMisMatch method is available in alertMessages.js 
                                        wacorpService.alertDialog($scope.messages.ShoppingCart.PaymentAmountMisMatch);
                                    }
                                        //Payment Fails
                                    else if (response.data.ErrorMessage == null || response.data.ErrorMessage == "" || response.data.ErrorMessage == "<br/>") {
                                        // Folder Name: app Folder
                                        // Alert Name: Payment method is available in alertMessages.js 
                                        wacorpService.alertDialog($scope.messages.ShoppingCart.Payment);
                                    } else {
                                        // Service Folder: services
                                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                                        wacorpService.alertDialog(response.data.ErrorMessage);
                                    }
                                }
                                else {
                                    $rootScope.isPlaceYourOrderButtonDisable = false;
                                    // Payment Fails
                                    if (response.data.ErrorMessage == null || response.data.ErrorMessage == "" || response.data.ErrorMessage == "<br/>") {
                                        // Folder Name: app Folder
                                        // Alert Name: Payment method is available in alertMessages.js 
                                        wacorpService.alertDialog($scope.messages.ShoppingCart.Payment);
                                    } else {
                                        // Service Folder: services
                                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                                        wacorpService.alertDialog(response.data.ErrorMessage);
                                    }
                                }
                            },
                            function (response) {
                                // Service Folder: services
                                // File Name: wacorpService.js (you can search with file name in solution explorer)
                                wacorpService.alertDialog(response.data.ErrorDescription);
                            });
                        }
                    }
                }
                else {
                    $rootScope.isPlaceYourOrderButtonDisable = false;
                    // Folder Name: app Folder
                    // Alert Name: Payment method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
                }
            };

});
wacorpApp.controller('reviewController', function ($scope, $q,$http, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData) {
    
    $scope.modal = $rootScope.modal;
    checkModel(); // checkModel method is available in this controller only.
    // initialize the scope
    $scope.Init = function () {
        //getNaicsCodes();
        TaxExemptUploadShow(); // TaxExemptUploadShow method is available in this controller only.
        $scope.NaicsCodes = [];
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCodeDesc += $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                        break;
                    }
                }
            });
        });
    }

    // add to card
    $scope.AddToCart = function () {

        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");

        //TFS 2626 TFS 2324 
        $scope.modal.BusinessTransaction.IsGrossRevenueNonProfit = $scope.modal.IsGrossRevenueNonProfit;
        //TFS 2626 TFS 2324 

        var uri = webservices.OnlineFiling.AddToCart;
        //$http({
        //    url: uri,
        //    method: "POST",
        //    data: $scope.modal,
        //    transformRequest: angular.identity,
        //    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        //}).success(function (result) {
        //    alert("Your request added to cart.");
        //    $location.path('/Dashboard');
        //}).error(function (result, status) {
        //    deferred.reject(status);
        //});
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("<div>").html($("section.content-body").html());
        var $initialReportReviewHTML = $("<div>").html($("section.content-body").html());
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove, .initialReport").remove();
        $initialReportReviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove, .formation").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace("&nbsp;REVIEW", " ").replace(" Review", " ");
        $scope.modal.InitialReportReviewHTML = $initialReportReviewHTML.html().replace("&nbsp;REVIEW", " ").replace(" Review", " ");
        
        var data = $scope.modal;
        //if ($rootScope.repository.loggedUser != undefined)
        //    $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.post(uri, data, function (response) {
            $rootScope.modal = null;
            $rootScope.BusinessType = null;
            $rootScope.isFormationWithIR = null;
            $location.path('/shoppingCart');
            

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });



    //    $http({
    //        method: 'POST',
    //        url: uri,
    //        data: data,
    //        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    //    }).then(
    //       function (response) {
    //           $rootScope.modal = null;
    //           $rootScope.BusinessType = null;
    //           $rootScope.isFormationWithIR = null;
    //           if ($scope.modal.BusinessTransaction.TransactionId > 0)
    //               $location.path('/shopingCart');
    //           else
    //               $location.path('/Dashboard');
    //       },
    //       function (response) {
    //           wacorpService.alertDialog(response.data);
    //       }
    //   );
    };

    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    function TaxExemptUploadShow() {
        $scope.isTaxExemptUploadShow = $scope.modal.BusinessTypeID != businessTypeIDs.WAPROFITCORPORATION;
    };

    $scope.back = function () {
       
        $rootScope.modal = $scope.modal;
        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $rootScope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");
        $location.path('/businessFormation').search('ID', '1')
    };

    //Check Model
    function checkModel() {
        var flag = (($rootScope.modal == null || $rootScope.modal == undefined)
                 && ($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null)
                 && ($rootScope.transactionID == undefined || $rootScope.transactionID == null));
        if (flag) {
            $location.path('/businessFormationIndex');
        }
    }

    $scope.AddMoreItems = function () {

        if ($scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode != null && $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.length > 0)
            $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode = $scope.modal.FormationWithInitialReport.NatureOfBusiness.NAICSCode.join(",");

        var uri = webservices.OnlineFiling.AddToCart; // AddToCart method is available in constants.js
        
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        var data = $scope.modal;
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.post(uri, data, function (response) {
            $rootScope.modal = null;
            $rootScope.BusinessType = null;
            $rootScope.isFormationWithIR = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
                $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
       
    };
});
wacorpApp.controller('cartItemsController', function ($scope, $rootScope, $location, $http, wacorpService, $filter) {
    // check business name availability
    $scope.messages = messages;
    //$scope.NameValidationsRequiredFor = ["Business Formation", "FOREIGN REGISTRATION STATEMENT", "CERTIFICATE OF FORMATION",
    //                                    "FOREIGN REGISTRATION STATEMENT", "ARTICLES OF INCORPORATION", "CERTIFICATE OF LIMITED PARTNERSHIP",
    //                                    "CERTIFICATE OF LIMITED LIABILITY LIMITED PARTNERSHIP", "Reinstatement", "AMENDMENT OF FOREIGN REGISTRATION STATEMENT"];

    $scope.checkNameAvailibility = function (item) {
        if (item.BusinessName != "") {
            item.OldBusinessName = '';
            item.OldBusinessName = item.BusinessName;

            //item.DBAName = item.BusinessName != null && item.BusinessName != '' && typeof item.BusinessName != typeof undefined ?
            //   (item.BusinessName.indexOf(' DBA ') > -1 ? item.BusinessName.split(' DBA ')[1] : '')
            //   : "";

            item.BusinessName =
                item.BusinessName != null && item.BusinessName != '' && typeof item.BusinessName != typeof undefined ?
                (item.BusinessName.indexOf(' DBA ') > -1 ? item.BusinessName.split(' DBA ')[0] : item.BusinessName)
                : "";


            // validateBusinessName method is available in constants.js
            wacorpService.post(webservices.ShoppingCart.validateBusinessName, item,
                function (response) {
                    var messages = '';
                    item.isValid = JSON.parse(response.data) == '';
                    var isval = false;
                    if (JSON.parse(response.data).indexOf('`') > -1) {
                        isval = JSON.parse(response.data).split('`')[1];
                        messages = !item.isValid ? JSON.parse(response.data).split('`')[0].split('_') : '';
                        item.isValid = isval == 'True';
                    }
                    else {
                        messages = !item.isValid ? JSON.parse(response.data).split('_') : '';
                    }

                    if (messages.length > 0) {
                        //OSOS ID--2075 Reinstatement  filing item is ready for submission for review by OSOS. 
                        if ((item.FilingType.toLowerCase() == 'reinstatement' || item.FilingType.toLowerCase() == 'requalification') && !item.IsApproved && item.isValid) {
                            item.ErrorMessage = $scope.messages.Cartitems.InhouseAppovalFiling;
                        }
                        else {
                            item.ErrorMessage = messages[0] != '' && messages[0] != 0 ? $scope.messages.ShoppingCart.shoppingCartValidate : '';
                            item.ErrorMessage = item.ErrorMessage != '' ? item.ErrorMessage + '\n' + messages[1] : messages[1];
                        }
                    }
                    else {
                        if (item.IsApproved) {
                            item.ErrorMessage = $scope.messages.Cartitems.OnlineProcessFiling;
                        }
                        else {
                            item.ErrorMessage = $scope.messages.Cartitems.InhouseAppovalFiling;
                        }

                        // TFS ID : 18055 (OSOS ID--2075)
                        //if (item.IsFilingAmountUpdated) {
                        //    //Nonprofits & Forien filings do not require Initial Reports
                        //    if (item.BusinessTypeId == '73' || item.BusinessTypeId == '74' || item.BusinessTypeId == '68' || item.FilingType.indexOf(' FOREIGN ') > -1 ) {
                        //        item.ErrorMessage = "<div>" + item.ErrorMessage + "<br/>" + $scope.messages.Cartitems.InhouseAppovalFiling +
                        //                                                '<ul><li>' + $scope.messages.Cartitems.AnnualReportDueDatePassed + '</li></ul></div>';
                        //    }
                        //    else {
                        //        item.ErrorMessage = "<div>" + item.ErrorMessage + "<br/>" + $scope.messages.Cartitems.InhouseAppovalFiling +
                        //                                               '<ul><li>' + $scope.messages.Cartitems.InitialReportDueDatePassed + '</li>' +
                        //                                               '<li>' + $scope.messages.Cartitems.AnnualReportDueDatePassed + '</li></ul></div>';
                        //    }
                        //}
                    }
                    item.BusinessName = item.OldBusinessName;
                    $scope.model.cartItems.push(item);
                }, function (response) {
                    item.BusinessName = item.OldBusinessName;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data.ErrorDescription);
                });
        }
        else {
            item.isValid = true;
            $scope.model.cartItems.push(item);
        }
    };

    $scope.model = {
        cartItems: []
    };
    if (typeof $rootScope.payment == typeof undefined || $rootScope.payment == null || $rootScope.payment == '')
        $location.path("/shoppingcart");

    angular.forEach($rootScope.payment.cartItems, function (item) {
        if (item.isSelect) {
            $scope.checkNameAvailibility(item); // checkNameAvailibility method is available in this controller only.
        }
    });



    // temp line 
    //$scope.model.cartItems[0].isValid = false;

    $scope.isCartItemSelected = function () {
        var flag = false;
        angular.forEach($scope.model.cartItems, function (item) {
            if (item.isSelect) {
                flag = true;
                return;
            }
        });
        return !flag;
    };

    // calculate total cart amount based on selected items
    $scope.calcTotal = function () {
        var total = 0;
        angular.forEach($scope.model.cartItems, function (item) {
            total += item.isSelect ? item.FilingAmount + item.PracessingAmount : 0;
        })
        return total;
    }

    // delete cart item
    $scope.delete = function (index, currentItem) {
        // Folder Name: app Folder
        // Alert Name: ConfirmMessage method is available in alertMessages.js
        wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {

            var itemIndex = $scope.model.cartItems.indexOf(currentItem);
            $scope.model.cartItems.splice(itemIndex, 1);
        });

    };

    // edit cart item
    $scope.edit = function (id, FilingType, BusinessTypeId) {
        $rootScope.transactionID = id;
        var flag = (FilingType.toLowerCase() === 'business formation' || FilingType.toLowerCase() === 'foreign registration statement'
            || FilingType.toLowerCase() === 'certificate of formation' || FilingType.toLowerCase() === 'articles of incorporation'
            || FilingType.toLowerCase() === 'certificate of limited partnership' || FilingType.toLowerCase() === 'certificate of limited liability limited partnership'
            || FilingType.toLowerCase() === 'certificate of formation with initial report' || FilingType.toLowerCase() === 'articles of incorporation with initial report'
            || FilingType.toLowerCase() === 'certificate of limited partnership with initial report' || FilingType.toLowerCase() === 'certificate of limited liability limited partnership with initial report'
            );


        var flagBusinessAmendment = (FilingType.toLowerCase() === 'business amendment' || FilingType.toLowerCase() === 'articles of amendment'
            || FilingType.toLowerCase() === 'amended certificate of limited liability partnership' || FilingType.toLowerCase() === 'amended certificate of prof limited liability partnership'
            || FilingType.toLowerCase() === 'amended certificate of formation' || FilingType.toLowerCase() === 'amended certificate of limited partnership'
            || FilingType.toLowerCase() === 'amended certificate of prof limited liability limited partnership' || FilingType.toLowerCase() === 'amendment'
            || FilingType.toLowerCase() === 'amended certificate of prof limited partnership' || FilingType.toLowerCase() === 'amended declaration of trust'
            || FilingType.toLowerCase() === 'amended certificate of limited liability limited partnership'
            );

        if (flag) {
            var data = { ID: BusinessTypeId };
            if ($rootScope.repository.loggedUser != undefined)
                $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
            $http({
                method: 'POST',
                url: webservices.Lookup.getBusinessFilingType, // getBusinessFilingType method is available in constants.js
                data: data
            }).then(function (response) {
                var businessType = response.data != undefined ? response.data.split('_')[0] : '';
                var formationType = response.data != undefined ? response.data.split('_')[1] : '';
                if (businessType === "\"C")
                    if (formationType === "0\"")
                        $location.path('/businessFormation').search('ID', '1');
                    else
                        $location.path('/foreignbusinessFormation').search('ID', '1');
                else if (businessType === "\"LLC")
                    if (formationType === "0\"")
                        $location.path('/LLCbusinessFormation').search('ID', '1');
                    else
                        $location.path('/LLCforeignbusinessFormation').search('ID', '1');
                else if (businessType === "\"LLP")
                    if (formationType === "0\"")
                        $location.path('/LLPbusinessFormation').search('ID', '1');
                    else
                        $location.path('/LLPforeignbusinessFormation').search('ID', '1');
            },
            function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data.ErrorDescription);
            });
        }
        else if (FilingType.toLowerCase() === 'annual report') {
            $location.path('/AnnualReport');
        }
        else if (FilingType.toLowerCase() === 'initial report') {
            $location.path('/InitialReport');
        }
        else if (FilingType.toLowerCase() === 'amended annual report') {
            $location.path('/AmendedAnnualReport');
        }
        else if (FilingType.toLowerCase() === 'statement of change') {
            $location.path('/StatementofChange');
        }
        else if (FilingType.toLowerCase() === 'commercial statement of change') {
            $location.path('/CommercialStatementofChange');
        }
        else if (FilingType.toLowerCase() === 'statement of resignation') {
            $location.path('/StatementofTermination');
        }
        else if (FilingType.toLowerCase() === 'commercial termination statement') {
            $location.path('/CommercialStatementofTermination');
        }
        else if (FilingType.toLowerCase() === 'commercial listing statement') {
            $location.path('/CommercialListingStatement');
        }
        else if (FilingType.toLowerCase() === 'reinstatement') {
            $location.path('/Reinstatement');
        }
        else if (FilingType.toLowerCase() === 'requalification') {
            $location.path('/Requalification');
        }
        else if (FilingType.toLowerCase() === 'amendment of foreign registration statement') {
            $location.path('/AmendmentofForiegnRegistrationStatement');
        }
        else if (FilingType.toLowerCase() === 'statement of withdrawal') {
            $location.path('/StatementofWithdrawal');
        }
        else if (FilingType.toLowerCase() === 'voluntary termination') {
            $location.path('/VoluntaryTermination');
        }
        else if (FilingType.toLowerCase() === 'certificate of dissolution') {
            $location.path('/CertificateOfDissolution');
        }
        else if (FilingType.toLowerCase() === 'articles of dissolution') {
            $location.path('/ArticlesOfDissolution');
        }
        else if (flagBusinessAmendment) {
            $location.path('/BusinessAmendment/0');
        }
        else if (FilingType.toLowerCase() === 'certified copies' || FilingType.toLowerCase() === 'records / certificate request' || FilingType.toLowerCase() === 'records/certificate request') {
            $location.path('/CopyRequest/Edit');
        }
        else if (FilingType.toLowerCase() === 'charitable organization registration') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesRegistration');
        }
        else if (FilingType.toLowerCase() === 'charitable organization renewal') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesRenewal');
        }
        else if (FilingType.toLowerCase() === 'charitable organization amendment') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesAmendment');
        }
        else if (FilingType.toLowerCase() === 'charitable organization optional registration') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesOptionalRegistration');
        }
        else if (FilingType.toLowerCase() === 'charitable organization optional renewal') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesOptionalRenewal');
        }
        else if (FilingType.toLowerCase() === 'charitable organization optional amendment') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesOptionalAmendment');
        }
        else if (FilingType.toLowerCase() === 'charitable organization optional closure') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesOptionalClosure');
        }
        else if (FilingType.toLowerCase() === 'close charitable organization') {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesClosure');
        }
        else if (FilingType.toLowerCase() === 'commercial fundraiser registration') {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserRegistration');
        }
        else if (FilingType.toLowerCase() === 'commercial fundraiser renewal') {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserRenewal/0');
        }
        else if (FilingType.toLowerCase() === 'commercial fundraiser amendment') {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserAmendment/0');
        }
        else if (FilingType.toLowerCase() === 'commercial fundraiser closure') {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserClosure/0');
        }
        else if (FilingType.toLowerCase() === 'charitable trust renewal') {
            $rootScope.IsShoppingCart = true;
            $location.path('/trusteeRenewal/0');
        }
        else if (FilingType.toLowerCase() === 'charitable trust closure') {
            $rootScope.IsShoppingCart = true;
            $location.path('/trusteeClosure/0');
        }
            // here BusinessTypeId = 7 is CHARITABLE ORGANIZATION
        else if (FilingType.toLowerCase() === 're-registration' && BusinessTypeId == 7) {
            $rootScope.IsShoppingCart = true;
            $location.path('/charitiesReRegistration/0');
            // here BusinessTypeId = 8 is CHARITABLE TRUST
        } else if (FilingType.toLowerCase() === 're-registration' && BusinessTypeId == 8) {
            $rootScope.IsShoppingCart = true;
            $location.path('/trustReRegistration/0');
            // here BusinessTypeId = 10 is COMMERCIAL FUNDRAISER
        } else if (FilingType.toLowerCase() === 're-registration' && BusinessTypeId == 10) {
            $rootScope.IsShoppingCart = true;
            $location.path('/fundraiserReRegistration/0');
        }
        else if (FilingType.toLowerCase() === 'records / certificate request') {
            $location.path('/CopyRequest/0');
        }
        else if (FilingType.toLowerCase() === 'fundraising service contract registration') {
            $rootScope.IsShoppingCart = true;
            $location.path('/submitFundraisingServiceContract/0');
        }
        else if (FilingType.toLowerCase() === 'fundraising service contract amendment') {
            $rootScope.IsShoppingCart = true;
            $location.path('/submitFundraisingServiceContractAmendment/0');
        }
        else if (FilingType.toLowerCase() === 'express pdf certificate of existence') {
            $location.path('/ExpressPDFCertificate/Edit');
        }
    };

    $scope.back = function () {
        $location.path("/shoppingcart");
    };

    // check errors
    $scope.checkErrors = function () {
        var flag = false;
        angular.forEach($scope.model.cartItems, function (item) {
            if (!item.isValid) {
                flag = true;
                return;
            }
        });
        return flag;
    };

    // check out on-click
    $scope.processtoCheckout = function () {
        if ($scope.checkErrors()) {
            // Folder Name: app Folder
            // Alert Name: invalidItemsCheckout method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.ShoppingCart.invalidItemsCheckout);
            return;
        }
        $rootScope.payment = {};
        $rootScope.payment.cartItems = $scope.model.cartItems;
        $rootScope.payment.Amount = $scope.calcTotal();
        $location.path("/payment");
    }

    $scope.showErrors = function (message, businessName) {
        if (businessName != '')
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(message.replace("TEXTCHANGE", "<b>" + businessName + "</b>").replace("no longer available", "<b>no longer available</b>"));
        else
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(message);
    }

    $scope.processPayment = function () {
        var data = {};
        data.BusinessTransactions = [];
        angular.forEach($scope.model.cartItems, function (item) {
            data.BusinessTransactions.push(
                {
                    BusinessTypeID: ((item.BusinessTypeId != "" || item.BusinessTypeId != undefined) ? item.BusinessTypeId : ''),
                    BusinessType: item.FilingType,
                    DateTimeReceived: item.CreatedDateTime,
                    DocumentsList: item.DocumentsList
                })
        });

        data.Amount = $scope.calcTotal();
        data.CreatedBy = angular.isNullorEmpty($rootScope.repository.loggedUser) ? null : $rootScope.repository.loggedUser.userid;
        data.UserID = -1;
        data.IsOnline = true;
        data.WorkOrderNumber = ""; // work order number

        $http({
            method: 'POST',
            url: webservices.ShoppingCart.processPayment, // processPayment method is available in constants.js
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
               function (response) {
                   // work order number
                   data.WorkOrderNumber = response.data.WorkOrderNumber;
                   $scope.WorkOrderNumber = response.data.WorkOrderNumber;
                   // Payment success 
                   if (response.data.IsSuccess) {
                       data.UncommitedTransactionID = response.data.UncommitedTransactionID;
                       processPay(response, data); // processPay method is available in this controller only.
                   }
                   else {
                       // Payment Fails
                       if (response.data.ErrorMessage == null || response.data.ErrorMessage == "" || response.data.ErrorMessage == "<br/>") {
                           // Folder Name: app Folder
                           // Alert Name: Payment method is available in alertMessages.js 
                           wacorpService.alertDialog($scope.messages.ShoppingCart.Payment);
                       } else {
                           // Service Folder: services
                           // File Name: wacorpService.js (you can search with file name in solution explorer)
                           wacorpService.alertDialog(response.data.ErrorMessage);
                       }
                   }
               },
                function (response) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                }
           );
    };

    function processPay(response, data) {

        var cartIds = [];
        var amount = 0;
        var expediteAmount = 0;
        var IsExpedite = [];
        var ExpediteAmountList = [];
        var CartItems = [];
        angular.forEach($scope.model.cartItems, function (item) {
            cartIds.push(item.ID);
            IsExpedite.push(angular.isNullorEmpty(item) ? false : item.IsExpedite);
            if (!angular.isNullorEmpty(item) && item.IsExpedite) {
                amount += item.Amount;
                ExpediteAmountList.push(constant.ExpdateAmount);
            }
            else {
                amount += item.FilingAmount;
                ExpediteAmountList.push(0);
            }
            CartItems.push(item);
        });
        onlineCartInfo = {
            IsPayment: true, CartIds: cartIds, TotalAmount: amount, IsExpediteAmount: ExpediteAmountList,
            IsExpeditelist: IsExpedite, UserId: $rootScope.repository.loggedUser.userid, PaymentInfo: data,
            CartItems: CartItems,
        }
        // update is payment in cart table
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: webservices.ShoppingCart.updatePayments, // shoppingCartPayment method is available in constants.js
            data: onlineCartInfo
        }).then(function (response) {
            $rootScope.paymentDone = response.data;
            $rootScope.payment = null;
            $location.path('/paymentdone');
        },
        function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data.ErrorDescription);
        });
    };

    //$scope.propertyName = 'CreatedDateTime';
    //$scope.reverse = true;

    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };


    // Shopping cart Payment
    $scope.shoppingCartPayment = function (paymentForm) {

        var data = {};
        data.BusinessTransactions = [];
        angular.forEach($scope.model.cartItems, function (item) {
            data.BusinessTransactions.push(
                {
                    BusinessTypeID: ((item.BusinessTypeId != "" || item.BusinessTypeId != undefined) ? item.BusinessTypeId : ''),
                    BusinessType: item.FilingType,
                    DateTimeReceived: item.CreatedDateTime,
                    DocumentsList: item.DocumentsList
                })
        });

        data.Amount = $scope.calcTotal();
        data.CreatedBy = angular.isNullorEmpty($rootScope.repository.loggedUser) ? null : $rootScope.repository.loggedUser.userid;
        data.UserID = -1;
        data.IsOnline = true;
        data.WorkOrderNumber = ""; // work order number

        var cartIds = [];
        var amount = 0;
        var expediteAmount = 0;
        var IsExpedite = [];
        var ExpediteAmountList = [];
        var CartItems = [];
        angular.forEach($scope.model.cartItems, function (item) {
            cartIds.push(item.ID);
            IsExpedite.push(angular.isNullorEmpty(item) ? false : item.IsExpedite);
            if (!angular.isNullorEmpty(item) && item.IsExpedite) {
                amount += item.Amount;
                ExpediteAmountList.push(constant.ExpdateAmount);
            }
            else {
                amount += item.FilingAmount;
                ExpediteAmountList.push(0);
            }
            CartItems.push(item);
        });
        onlineCartInfo = {
            IsPayment: true, CartIds: cartIds, TotalAmount: amount, IsExpediteAmount: ExpediteAmountList,
            IsExpeditelist: IsExpedite, UserId: $rootScope.repository.loggedUser.userid, PaymentInfo: data,
            CartItems: CartItems,
        }
        // update is payment in cart table
        if ($rootScope.repository.loggedUser != undefined)
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.repository.loggedUser.t;
        $http({
            method: 'POST',
            url: webservices.ShoppingCart.shoppingCartPayment, // shoppingCartPayment method is available in constants.js
            data: onlineCartInfo
        }).then(
        function (response) {
            // Payment success 
            if (response.data.IsSuccess) {
                $rootScope.paymentDone = response.data;
                $rootScope.payment = null;
                $location.path('/paymentdone');
            }
            else if (!response.data.IsSuccess) {
                // Payment Amount Fails
                if (response.data.isFailed) {
                    // Folder Name: app Folder
                    // Alert Name: PaymentAmountMisMatch method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.ShoppingCart.PaymentAmountMisMatch);
                }
                    //Payment Fails
                else if (response.data.ErrorMessage == null || response.data.ErrorMessage == "" || response.data.ErrorMessage == "<br/>") {
                    // Folder Name: app Folder
                    // Alert Name: Payment method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.ShoppingCart.Payment);
                } else {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data.ErrorMessage);
                }
            }
            else {
                // Payment Fails
                if (response.data.ErrorMessage == null || response.data.ErrorMessage == "" || response.data.ErrorMessage == "<br/>") {
                    // Folder Name: app Folder
                    // Alert Name: Payment method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.ShoppingCart.Payment);
                } else {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data.ErrorMessage);
                }
            }
        },
        function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data.ErrorDescription);
        });

    };

});

wacorpApp.controller('subscriptionsController', function ($scope, $http, $rootScope, wacorpService, $location, $timeout, $cookieStore) {
    // declarations
    $scope.messages = messages;
    $scope.businessSearchCriteria = { Type: searchTypes.BUSINESSNO, IsOnline: true };
    $scope.charitySearchCriteria = {
        Type: searchTypes.RegistrationNumber, ID: "", EntityName: "", businesstype: null, businessStatusInfo: null, ModifiedDate: "", RenewalDate: "",
        PageID: constant.ONE, PageCount: constant.TEN, IsOnline: true, SortBy: null, SortType: null, SearchType: "", FilerId: "", BusinessStatusID: null,
        BusinessTypeId: null, RegistrationNumber: "", FEINNo: "", UBINumber: ""
    };

    $scope.SearchCriteria_bkp = {
        Type: searchTypes.RegistrationNumber, ID: "", EntityName: "", businesstype: null, businessStatusInfo: null, ModifiedDate: "", RenewalDate: "",
        PageID: constant.ONE, PageCount: constant.TEN, IsOnline: true, SortBy: null, SortType: null, SearchType: "", FilerId: "", BusinessStatusID: null,
        BusinessTypeId: null, RegistrationNumber: "", FEINNo: "", UBINumber: ""
    };

    //CORPORATIONS
    $scope.BusinessList = [];
    $scope.SubscriptionList = [];
    $scope.BusinessSearchList = [];
    $scope.checkedBusiness = [];
    $scope.checkedSubscriptionBusiness = [];

    //CHARITIES
    $scope.CFTSubscriptionList = [];
    $scope.CFTSearchList = [];
    $scope.checkedCFTBusiness = [];
    $scope.checkedCFTSubscriptionBusiness = [];

    $scope.page = constant.ZERO;
    $scope.page1 = constant.ZERO;
    $scope.pagesCount1 = constant.ZERO;
    $scope.totalCount1 = constant.ZERO;
    $scope.businessCategoryType = businessCatType.CORP;

    $scope.page2 = constant.ZERO;
    $scope.pagesCount2 = constant.ZERO;
    $scope.totalCount2 = constant.ZERO;

    $scope.page3 = constant.ZERO;
    $scope.pagesCount3 = constant.ZERO;
    $scope.totalCount3 = constant.ZERO;

    $scope.isButtonSearch = false;

    //Corporations
    $scope.search = loadbusinessList;
    $scope.searchSubscriptions = loadSubscriptionList;
    $scope.searchBusinessList = loadbusinessSearchList;

    //Charities
    $scope.searchCFTSubscriptions = loadCFTSubscriptionList;
    $scope.searchCFTBusinessList = loadCFTbusinessSearchList;


    $scope.mySubsciptionViewList = false;

    // tabs
    $scope.swtichTabs = function (navigation) {

        $scope.checkedBusiness = [];
        $scope.checkedSubscriptionBusiness = [];

        $scope.checkedCFTBusiness = [];
        $scope.checkedCFTSubscriptionBusiness = [];

        $scope.businessSearchCriteria = {};
        $scope.businessSearchCriteria.Type = searchTypes.BUSINESSNO;
        $scope.businessSearchCriteria.PageCount = 10;

        $scope.charitySearchCriteria = {};
        $scope.charitySearchCriteria.PageCount = 10;
        $scope.charitySearchCriteria.Type = searchTypes.RegistrationNumber;

        $scope.SearchCriteria_bkp = {};
        $scope.SearchCriteria_bkp.PageCount = 10;

        $scope.selectedTab = navigation;
        $scope.businessCategoryType = businessCatType.CORP;
        $("#corp").prop("checked", true);
        $scope.resetSearch();
        if ($scope.selectedTab == "myBusiness") {
            if ($scope.BusinessList.length == 0) {
                loadbusinessList(constant.ZERO); // loadbusinessList method is available in this controller only.
            }
            $scope.mySubsciptionViewList = false;
            $scope.businessSearchCriteria.isSearchClick = true;
        }
        if ($scope.selectedTab == "subscription") {
            //if ($scope.SubscriptionList.length == 0)
            loadSubscriptionList(constant.ZERO); // loadSubscriptionList method is available in this controller only.
            $scope.mySubsciptionViewList = false;
            $scope.businessSearchCriteria.isSearchClick = true;
        }
        $scope.page = constant.ZERO;
        $scope.page1 = constant.ZERO;
        $scope.pagesCount1 = constant.ZERO;
        $scope.totalCount1 = constant.ZERO;

        $scope.page2 = constant.ZERO;
        $scope.pagesCount2 = constant.ZERO;
        $scope.totalCount2 = constant.ZERO;

        $scope.page3 = constant.ZERO;
        $scope.pagesCount3 = constant.ZERO;
        $scope.totalCount3 = constant.ZERO;
    };

    // scope initilization
    $scope.init = function () {
        $scope.selectedTab = $scope.CAmenu() ? "myBusiness" : "subscription";
        $scope.businessSearchCriteria = { Type: searchTypes.BUSINESSNO, ID: "", IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, BusinessTypeId: constant.ZERO, IsOnline: true, isSearchClick: false };
        $scope.getBusinessTypes();
        $scope.getCFTTypes();
        $scope.getCFTStatus();
        $scope.getBusinessStatus();
        $scope.selectedBusiness = false;
        $scope.selectedSubscriptionBusiness = false;
        $scope.modal = {};
        $scope.searchBusiness(); // searchBusiness method is available in this controller only.
        $scope.mySubsciptionViewList = false;
    };

    // search button event
    $scope.searchBusiness = function (searchform) {
        $scope.businessSearchCriteria.isSearchClick = true;
        $scope.isButtonSearch = true;
        if ($scope.selectedTab == "myBusiness") {
            //$scope.search = loadbusinessList;
            $scope.BusinessList = [];
            loadbusinessList(constant.ZERO);
            $scope.mySubsciptionViewList = false;
        }
        else if ($scope.selectedTab == "subscription") {
            if ($scope.businessCategoryType == "CORP") {

                $scope.SubscriptionList = [];
                $scope.search = loadSubscriptionList;
                loadSubscriptionList(constant.ZERO);
            }
            else {
                $scope.CFTSubscriptionList = [];
                $scope.searchCFTSubscriptions = loadCFTSubscriptionList;
                loadCFTSubscriptionList(constant.ZERO);
            }
            $scope.mySubsciptionViewList = false;
        }
        else if ($scope.selectedTab == "businessSearch") {
            if ($scope.businessCategoryType == "CORP") {
                $scope.BusinessSearchList = [];
                $scope.search = loadbusinessSearchList;
                loadbusinessSearchList(constant.ZERO); // loadbusinessSearchList method is available in this controller only.
            }
            else {
                $scope.CFTSearchList = [];
                $scope.searchCFTBusinessList = loadCFTbusinessSearchList;
                loadCFTbusinessSearchList(constant.ZERO);
            }
            $scope.mySubsciptionViewList = false;
        }
        $scope.checkedBusiness = [];
        $scope.checkedSubscriptionBusiness = [];
    };

    // View Entire List button event
    $scope.viewEntireBusinessList = function (searchform) {
        $scope.businessSearchCriteria.isSearchClick = true;
        $scope.isButtonSearch = true;
        if ($scope.selectedTab == "myBusiness") {
            //$scope.search = loadbusinessList;
            $scope.BusinessList = [];
            loadbusinessList(constant.ZERO); // loadbusinessList method is available in this controller only.
            //$scope.mySubsciptionViewList = true;
        }
        else if ($scope.selectedTab == "subscription") {
            if ($scope.businessCategoryType == "CORP") {
                $scope.businessSearchCriteria = {};
                $scope.businessSearchCriteria.Type = searchTypes.BUSINESSNO;
                $scope.businessSearchCriteria.PageCount = 10;
                $scope.businessSearchCriteria.isSearchClick = true;
                $scope.SubscriptionList = [];
                $scope.search = loadSubscriptionList;
                loadSubscriptionList(constant.ZERO); // loadSubscriptionList method is available in this controller only.
            }
            else {
                $scope.charitySearchCriteria = {};
                $scope.charitySearchCriteria.PageCount = 10;
                $scope.charitySearchCriteria.Type = searchTypes.RegistrationNumber;
                $scope.businessSearchCriteria.isSearchClick = true;
                $scope.CFTSubscriptionList = [];
                $scope.searchCFTSubscriptions = loadCFTSubscriptionList;
                loadCFTSubscriptionList(constant.ZERO);
            }
            //$scope.mySubsciptionViewList = true;
        }
        else if ($scope.selectedTab == "businessSearch") {
            $scope.BusinessSearchList = [];
            $scope.search = loadbusinessSearchList;
            loadbusinessSearchList(constant.ZERO); // loadbusinessSearchList method is available in this controller only.
            $scope.mySubsciptionViewList = false;
        }
        $scope.checkedBusiness = [];
        $scope.checkedSubscriptionBusiness = [];
    };

    // reset criteria
    $scope.resetSearch = function () {
        $scope.businessSearchCriteria =
            {
                Type: searchTypes.BUSINESSNO,
                ID: "",
                IsSearch: true,
                PageID: constant.ONE,
                PageCount: constant.TEN,
                BusinessTypeId: constant.ZERO,
                IsOnline: true,
                isSearchClick: false,
                businesstype: {},
                businessStatusInfo: {},
                DueDate: "",
                ModifiedDate: "",
            };
        $scope.checkedBusiness = [];
        $scope.checkedSubscriptionBusiness = [];
        $scope.mySubsciptionViewList = false;
    };

    // --------------------------------********** my business search ***************** ---------------------------------------
    // get my business list
    function loadbusinessList(page, sortBy) {
        //page = page || constant.ZERO;
        $scope.businessSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        $scope.businessSearchCriteria.SearchType = searchTypes.BUSINESSBYAGENTID;
        $scope.businessSearchCriteria.AgentId = $rootScope.repository.loggedUser.agentid;
        $scope.businessSearchCriteria.BusinessStatusID = !angular.isNullorEmpty($scope.businessSearchCriteria.businessStatusInfo) ? $scope.businessSearchCriteria.businessStatusInfo.Key : 0;
        $scope.businessSearchCriteria.BusinessTypeId = (!angular.isNullorEmpty($scope.businessSearchCriteria.businesstype) && !angular.isNullorEmpty($scope.businessSearchCriteria.businesstype.Key)) ? $scope.businessSearchCriteria.businesstype.Key.split('`')[0] : constant.ZERO;
        if (sortBy != undefined) {
            if ($scope.businessSearchCriteria.SortBy == sortBy) {
                if ($scope.businessSearchCriteria.SortType == 'ASC') {
                    $scope.businessSearchCriteria.SortType = 'DESC';
                }
                else {
                    $scope.businessSearchCriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.businessSearchCriteria.SortBy = sortBy;
                $scope.businessSearchCriteria.SortType = 'ASC';
            }
        }
        $scope.isButtonSearch = page == 0;
        //For Maintaing the Search Critera in Sorting
        var data = {};
        if (page == constant.ZERO && sortBy == undefined) {
            angular.copy($scope.businessSearchCriteria, $scope.SearchCriteria_bkp);
            //$scope.SearchCriteria_bkp = $scope.charitySearchCriteria;
            data = $scope.businessSearchCriteria;
        }
        else {
            data = $scope.SearchCriteria_bkp;
            data.PageID = $scope.businessSearchCriteria.PageID;
            data.SortType = $scope.businessSearchCriteria.SortType;
            data.SortBy = $scope.businessSearchCriteria.SortBy;
        }
        // getBusinessesForSubscription method is available in constants.js
        wacorpService.post(webservices.Subscription.getBusinessesForSubscription, data, function (response) {
            $scope.BusinessList = response.data;
            angular.forEach($scope.BusinessList, function (item) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                item.ModifiedDate = wacorpService.dateFormatService(item.ModifiedDate);
                item.ARDueDate = wacorpService.dateFormatService(item.ARDueDate);
            });
            if ($scope.isButtonSearch && response.data.length > 0) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                $scope.pagesCount1 = response.data.length < $scope.businessSearchCriteria.PageCount && page > 0 ? $scope.pagesCount1 : pagecount;
                $scope.totalCount1 = totalcount;
            }
            $scope.page1 = page;
            $scope.page = page;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    };

    //Watch my business list
    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == constant.ZERO) {
            $scope.totalCount1 = constant.ZERO;
            $scope.pagesCount1 = constant.ZERO;
            $scope.totalCount1 = constant.ZERO;
            $scope.page1 = constant.ZERO;
        }
    }, true);


    // --------------------------------********** subscriptions search ***************** ---------------------------------------

    // get subscriptions list data from server
    function loadSubscriptionList(page, sortBy) {
        //page = page || constant.ZERO;
        $scope.businessSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        $scope.businessSearchCriteria.SearchType = searchTypes.SUBSCRIPTIONSEARCH;
        $scope.businessSearchCriteria.FilerId = $rootScope.repository.loggedUser.userid;
        $scope.businessSearchCriteria.BusinessStatusID = !angular.isNullorEmpty($scope.businessSearchCriteria.businessStatusInfo) ? $scope.businessSearchCriteria.businessStatusInfo.Key : 0;
        $scope.businessSearchCriteria.BusinessTypeId = (!angular.isNullorEmpty($scope.businessSearchCriteria.businesstype) && !angular.isNullorEmpty($scope.businessSearchCriteria.businesstype.Key)) ? $scope.businessSearchCriteria.businesstype.Key.split('`')[0] : constant.ZERO;
        if (sortBy != undefined) {
            if ($scope.businessSearchCriteria.SortBy == sortBy) {
                if ($scope.businessSearchCriteria.SortType == 'ASC') {
                    $scope.businessSearchCriteria.SortType = 'DESC';
                }
                else {
                    $scope.businessSearchCriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.businessSearchCriteria.SortBy = sortBy;
                $scope.businessSearchCriteria.SortType = 'ASC';
            }
        }
        $scope.modal.selectSubscriptionAll = false;
        $scope.isButtonSearch = page == 0;

        //For Maintaing the Search Critera in Sorting
        var data = {};
        if (page == constant.ZERO && sortBy == undefined) {
            angular.copy($scope.businessSearchCriteria, $scope.SearchCriteria_bkp);
            //$scope.SearchCriteria_bkp = $scope.charitySearchCriteria;
            data = $scope.businessSearchCriteria;
        }
        else {
            data = $scope.SearchCriteria_bkp;
            data.PageID = $scope.businessSearchCriteria.PageID;
            data.SortType = $scope.businessSearchCriteria.SortType;
            data.SortBy = $scope.businessSearchCriteria.SortBy;
        }
        // getBusinessesForSubscription method is available in constants.js
        wacorpService.post(webservices.Subscription.getBusinessesForSubscription, data, function (response) {
            $scope.SubscriptionList = response.data;
            angular.forEach($scope.SubscriptionList, function (item) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                item.ModifiedDate = wacorpService.dateFormatService(item.ModifiedDate);
                item.ARDueDate = wacorpService.dateFormatService(item.ARDueDate);
                angular.forEach($scope.checkedSubscriptionBusiness, function (ID) {
                    if (item.ID == ID)
                        item.isSelect = true;
                });
            });
            if ($scope.isButtonSearch && response.data.length > 0) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                $scope.pagesCount2 = response.data.length < $scope.businessSearchCriteria.PageCount && page > 0 ? $scope.pagesCount2 : pagecount;
                $scope.totalCount2 = totalcount;
            }
            $scope.page2 = page;
            $scope.page = page;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    //Watch subscriptions Search List
    $scope.$watch('SubscriptionList', function () {
        if ($scope.SubscriptionList == undefined)
            return;
        if ($scope.SubscriptionList.length == constant.ZERO) {
            $scope.totalCount2 = constant.ZERO;
            $scope.pagesCount2 = constant.ZERO;
            $scope.totalCount2 = constant.ZERO;
            $scope.page2 = constant.ZERO;
        }
    }, true);



    // --------------------------------********** business search  ***************** ---------------------------------------

    // get business list data from server
    function loadbusinessSearchList(page, sortBy) {
        //page = page || constant.ZERO;
        $scope.businessSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        $scope.businessSearchCriteria.SearchType = searchTypes.BUSINESSSEARCH;
        $scope.businessSearchCriteria.FilerId = $rootScope.repository.loggedUser.userid;
        $scope.businessSearchCriteria.BusinessStatusID = !angular.isNullorEmpty($scope.businessSearchCriteria.businessStatusInfo) ? $scope.businessSearchCriteria.businessStatusInfo.Key : 0;
        $scope.businessSearchCriteria.BusinessTypeId = (!angular.isNullorEmpty($scope.businessSearchCriteria.businesstype) && !angular.isNullorEmpty($scope.businessSearchCriteria.businesstype.Key)) ? $scope.businessSearchCriteria.businesstype.Key.split('`')[0] : constant.ZERO;
        if (sortBy != undefined) {
            if ($scope.businessSearchCriteria.SortBy == sortBy) {
                if ($scope.businessSearchCriteria.SortType == 'ASC') {
                    $scope.businessSearchCriteria.SortType = 'DESC';
                }
                else {
                    $scope.businessSearchCriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.businessSearchCriteria.SortBy = sortBy;
                $scope.businessSearchCriteria.SortType = 'ASC';
            }
        }
        $scope.modal.selectAll = false;
        $scope.isButtonSearch = page == 0;

        //For Maintaing the Search Critera in Sorting
        var data = {};
        if (page == constant.ZERO && sortBy == undefined) {
            angular.copy($scope.businessSearchCriteria, $scope.SearchCriteria_bkp);
            //$scope.SearchCriteria_bkp = $scope.charitySearchCriteria;
            data = $scope.businessSearchCriteria;
        }
        else {
            data = $scope.SearchCriteria_bkp;
            data.PageID = $scope.businessSearchCriteria.PageID;
            data.SortType = $scope.businessSearchCriteria.SortType;
            data.SortBy = $scope.businessSearchCriteria.SortBy;
        }
        // getBusinessesForSubscription method is available in constants.js
        wacorpService.post(webservices.Subscription.getBusinessesForSubscription, data, function (response) {
            $scope.BusinessSearchList = response.data;
            angular.forEach($scope.BusinessSearchList, function (item) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                item.ModifiedDate = wacorpService.dateFormatService(item.ModifiedDate);
                item.ARDueDate = wacorpService.dateFormatService(item.ARDueDate);
                angular.forEach($scope.checkedBusiness, function (businessID) {
                    if (item.BusinessID == businessID)
                        item.isSelect = true;
                });
            });
            if ($scope.isButtonSearch && response.data.length > 0) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                $scope.pagesCount3 = response.data.length < $scope.businessSearchCriteria.PageCount && page > 0 ? $scope.pagesCount3 : pagecount;
                $scope.totalCount3 = totalcount;
            }
            $scope.page3 = page;
            $scope.page = page;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    //Watch my Business Search List
    $scope.$watch('BusinessSearchList', function () {
        if ($scope.BusinessSearchList == undefined)
            return;
        if ($scope.BusinessSearchList.length == constant.ZERO) {
            $scope.totalCount3 = constant.ZERO;
            $scope.pagesCount3 = constant.ZERO;
            $scope.totalCount3 = constant.ZERO;
            $scope.page3 = constant.ZERO;
        }
    }, true);


    //navigate to business information
    $scope.showBusineInfo = function (id, businessType) {
        $scope.businessSearchCriteria.businessid = id;
        $scope.businessSearchCriteria.businesstype = businessType;
        $rootScope.isBackButtonHide = true;
        $cookieStore.put('businesssearchcriteria', $scope.businessSearchCriteria);
        $scope.navBusinessInformation();
        // window.open(url, '_blank');
    }

    // --------------------------------********** helper methods  ***************** ---------------------------------------
    //Get Business Types
    $scope.getBusinessTypes = function () {
        var data = { params: { name: searchTypes.BUSINESSTYPEONLINEDASHBOARD } };
        // OnBusinessFilingLookups method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.OnBusinessFilingLookups, data, function (response) {
            $scope.businessTypes = response.data;
        }, function (response) { });
    };

    //Get CFT Types
    $scope.getCFTTypes = function () {
        var data = { params: { name: searchTypes.CFTONLINEDASHBOARD } };
        // OnBusinessFilingLookups method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.OnBusinessFilingLookups, data, function (response) {
            $scope.cftTypes = response.data;
        }, function (response) { });
    };

    //Get CFT Status
    $scope.getCFTStatus = function () {
        var data = { params: { name: "CFTStatus" } };
        // OnBusinessFilingLookups method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.OnlineCFTStatus, data, function (response) {
            $scope.CFTStatus = response.data;
        }, function (response) { });
    };

    //Get Business Status
    $scope.getBusinessStatus = function () {
        var data = { params: { name: searchTypes.BUSINESSSTATUS } };
        // OnBusinessFilingLookups method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.OnBusinessFilingLookups, data, function (response) {
            $scope.businessStatus = response.data;
        }, function (response) { });
    };

    // select All businesses for subscription
    $scope.selectAll = function () {
        angular.forEach($scope.BusinessSearchList, function (business) {
            business.isSelect = $scope.modal.selectAll;
            if (!$scope.modal.selectAll) {
                var index = $scope.checkedBusiness.indexOf(business.BusinessID);
                if (index > -1)
                    $scope.checkedBusiness.splice(index, 1);
            }
            if ($scope.modal.selectAll) {
                var index = $scope.checkedBusiness.indexOf(business.BusinessID);
                if (index <= -1)
                    $scope.checkedBusiness.push(business.BusinessID);
            }
            $scope.selectedBusiness = $scope.checkedBusiness.length > 0;
        });
    };

    // select All businesses for CFT subscription
    $scope.selectCFTAll = function () {
        angular.forEach($scope.CFTSearchList, function (business) {
            business.isSelect = $scope.modal.selectCFTAll;
            if (!$scope.modal.selectCFTAll) {
                for (var i = 0; i < $scope.checkedCFTBusiness.length; i++) {
                    if ($scope.checkedCFTBusiness[i].CFTId == business.CFTId && $scope.checkedCFTBusiness[i].CFTType == business.BusinessType) {
                        $scope.checkedCFTBusiness.splice(i, 1);
                    }
                }
            }
            else if ($scope.modal.selectCFTAll) {

                var index = 0;
                for (var i = 0; i < $scope.checkedCFTBusiness.length; i++) {
                    if ($scope.checkedCFTBusiness[i].CFTId == business.CFTId && $scope.checkedCFTBusiness[i].CFTType == business.BusinessType) {
                        index = i;
                    }
                }
                //var index = $scope.checkedCFTBusiness.findIndex(x=> x.CFTId == business.CFTId && x.CFTType == business.BusinessType);
                if (index == 0) {
                    $scope.checkedCFTBusiness.push({
                        CFTId: business.CFTId, CFTType: business.BusinessType, RegistrationNumber: business.RegistrationNumber
                    });
                }
            }
            $scope.selectedCFTBusiness = $scope.checkedCFTBusiness.length > 0;
        });
    };

    // select All businesses for unsubscription
    $scope.selectSubscriptionAll = function () {
        angular.forEach($scope.SubscriptionList, function (business) {
            business.isSelect = $scope.modal.selectSubscriptionAll;
            if (!$scope.modal.selectSubscriptionAll) {
                var index = $scope.checkedSubscriptionBusiness.indexOf(business.ID);
                if (index > -1)
                    $scope.checkedSubscriptionBusiness.splice(index, 1);
            }
            if ($scope.modal.selectSubscriptionAll) {
                var index = $scope.checkedSubscriptionBusiness.indexOf(business.ID);
                if (index <= -1)
                    $scope.checkedSubscriptionBusiness.push(business.ID);
            }
            $scope.selectedSubscriptionBusiness = $scope.checkedSubscriptionBusiness.length > 0;
        });
    };

    // select All businesses for CFT unsubscription
    $scope.selectCFTSubscriptionAll = function () {
        angular.forEach($scope.CFTSubscriptionList, function (business) {
            business.isSelect = $scope.modal.selectCFTSubscriptionAll;
            if (!$scope.modal.selectCFTSubscriptionAll) {

                for (var i = 0; i < $scope.checkedCFTSubscriptionBusiness.length; i++) {
                    if ($scope.checkedCFTSubscriptionBusiness[i].CFTId == business.CFTId && $scope.checkedCFTSubscriptionBusiness[i].CFTType == business.BusinessType) {
                        $scope.checkedCFTSubscriptionBusiness.splice(i, 1);
                    }
                }
            }
            else if ($scope.modal.selectCFTSubscriptionAll) {

                var index = 0;
                for (var i = 0; i < $scope.checkedCFTSubscriptionBusiness.length; i++) {
                    if ($scope.checkedCFTSubscriptionBusiness[i].CFTId == business.CFTId && $scope.checkedCFTSubscriptionBusiness[i].CFTType == business.BusinessType) {
                        index = i;
                    }
                }
                //var index = $scope.checkedCFTSubscriptionBusiness.findIndex(x=> x.CFTId == business.CFTId && x.CFTType == business.BusinessType);
                if (index == 0) {
                    $scope.checkedCFTSubscriptionBusiness.push({
                        CFTId: business.CFTId, CFTType: business.BusinessType
                    });
                }
            }
            $scope.selectedCFTSubscriptionBusiness = $scope.checkedCFTSubscriptionBusiness.length > 0;
        });
    };

    // item checkbox click for subscription
    $scope.selectChange = function (business) {
        var flag = true;
        var isBusinessSelected = false;
        angular.forEach($scope.BusinessSearchList, function (business) {
            if (!business.isSelect) {
                var index = $scope.checkedBusiness.indexOf(business.BusinessID);
                if (index > -1)
                    $scope.checkedBusiness.splice(index, 1);
                flag = false;
                return;
            }
            if (business.isSelect) {
                var index = $scope.checkedBusiness.indexOf(business.BusinessID);
                if (index <= -1)
                    $scope.checkedBusiness.push(business.BusinessID);
                isBusinessSelected = true;
                return;
            }
        });
        $scope.modal.selectAll = flag;
        $scope.selectedBusiness = $scope.checkedBusiness.length > 0;
    };

    // item checkbox click for CFT subscription
    $scope.selectCFTChange = function (business) {
        if (!business.isSelect) {
            for (var i = 0; i < $scope.checkedCFTBusiness.length; i++) {
                if ($scope.checkedCFTBusiness[i].CFTId == business.CFTId && $scope.checkedCFTBusiness[i].CFTType == business.BusinessType) {
                    $scope.checkedCFTBusiness.splice(i, 1);
                    flag = false;
                    $scope.modal.selectCFTAll = ($scope.CFTSearchList.length == $scope.checkedCFTBusiness.length) ? true : false;
                    $scope.selectedCFTBusiness = $scope.checkedCFTBusiness.length > 0;
                    return;
                }
            }
        }
        else if (business.isSelect) {
            $scope.checkedCFTBusiness.push({
                CFTId: business.CFTId, CFTType: business.BusinessType, RegistrationNumber: business.RegistrationNumber
            });
            $scope.modal.selectCFTAll = ($scope.CFTSearchList.length == $scope.checkedCFTBusiness.length) ? true : false;
            $scope.selectedCFTBusiness = $scope.checkedCFTBusiness.length > 0;
            return;
        }
    };

    // item checkbox click for unsubscription
    $scope.selectSubscriptionChange = function (business) {
        var flag = true;
        var isBusinessSelected = false;
        angular.forEach($scope.SubscriptionList, function (business) {
            if (!business.isSelect) {
                var index = $scope.checkedSubscriptionBusiness.indexOf(business.ID);
                if (index > -1)
                    $scope.checkedSubscriptionBusiness.splice(index, 1);
                flag = false;
                return;
            }
            if (business.isSelect) {
                var index = $scope.checkedSubscriptionBusiness.indexOf(business.ID);
                if (index <= -1)
                    $scope.checkedSubscriptionBusiness.push(business.ID);
                isBusinessSelected = true;
                return;
            }
        });
        $scope.modal.selectSubscriptionAll = flag;
        $scope.selectedSubscriptionBusiness = $scope.checkedSubscriptionBusiness.length > 0;
    };

    // item checkbox click for cft unsubscription
    $scope.selectCFTSubscriptionChange = function (business) {

        if (!business.isSelect) {
            for (var i = 0; i < $scope.checkedCFTSubscriptionBusiness.length; i++) {
                if ($scope.checkedCFTSubscriptionBusiness[i].CFTId == business.CFTId && $scope.checkedCFTSubscriptionBusiness[i].CFTType == business.BusinessType) {
                    $scope.checkedCFTSubscriptionBusiness.splice(i, 1);
                    flag = false;
                    $scope.modal.selectCFTSubscriptionAll = ($scope.CFTSubscriptionList.length == $scope.checkedCFTSubscriptionBusiness.length) ? true : false;
                    $scope.selectedCFTSubscriptionBusiness = $scope.checkedCFTSubscriptionBusiness.length > 0;
                    return;
                }
            }
        }
        else if (business.isSelect) {
            $scope.checkedCFTSubscriptionBusiness.push({
                CFTId: business.CFTId, CFTType: business.BusinessType
            });
            $scope.modal.selectCFTSubscriptionAll = ($scope.CFTSubscriptionList.length == $scope.checkedCFTSubscriptionBusiness.length) ? true : false;
            $scope.selectedCFTSubscriptionBusiness = $scope.checkedCFTSubscriptionBusiness.length > 0;
            return;
        }
    };

    //Subscribe the businesses
    $scope.subscribeBusiness = function () {
        if ($scope.checkedBusiness.toString() != '') {
            var data = {
                MulitipleIDs: $scope.checkedBusiness.toString(), FilerId: $rootScope.repository.loggedUser.userid
            };
            // SubscribeBusiness method is available in constants.js
            wacorpService.post(webservices.Subscription.SubscribeBusiness, data, function (response) {
                if (response.data.isSuccess) {
                    for (var j = 0; j < $scope.BusinessSearchList.length; j++) {
                        for (var i = 0; i < $scope.checkedBusiness.length; i++) {
                            if ($scope.checkedBusiness[i] == $scope.BusinessSearchList[j].BusinessID) {
                                $scope.BusinessSearchList.splice(j, 1);
                            }
                        }
                    }

                    $scope.checkedBusiness = [];
                    // Folder Name: app Folder
                    // Alert Name: subscriptionSuccess method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.Subscription.subscriptionSuccess);
                    angular.forEach($scope.BusinessSearchList, function (business) {
                        business.isSelect = false;
                    });
                    //To Load the Search results with same criteria -- 2712
                    loadbusinessSearchList(constant.ZERO);
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: subscriptionFailed method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.Subscription.subscriptionFailed);
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        }
    };


    //Subscribe the CFT Business
    $scope.subscribeCFTBusiness = function () {
        if ($scope.checkedCFTBusiness.length > 0) {
            var data = {
                CFTBusinessList: $scope.checkedCFTBusiness, FilerId: $rootScope.repository.loggedUser.userid
            };
            // SubscribeBusiness method is available in constants.js
            wacorpService.post(webservices.Subscription.SubscribeCFTBusiness, data, function (response) {
                if (response.data.isSuccess) {
                    for (var j = 0; j < $scope.CFTSearchList.length; j++) {
                        for (var i = 0; i < $scope.checkedCFTBusiness.length; i++) {
                            if ($scope.checkedCFTBusiness[i].CFTId == $scope.CFTSearchList[j].CFTId && $scope.checkedCFTBusiness[i].CFTType == $scope.CFTSearchList[j].BusinessType) {
                                $scope.CFTSearchList.splice(j, 1);
                            }
                        }
                    }
                    $scope.checkedCFTBusiness = [];
                    // Folder Name: app Folder
                    // Alert Name: subscriptionSuccess method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.Subscription.CFTSubscriptionSuccess);

                    angular.forEach($scope.CFTSearchList, function (business) {
                        business.isSelect = false;
                    });
                    $scope.modal.selectCFTAll = false;
                    //To Load the Search results with same criteria -- 2712
                    loadCFTbusinessSearchList(constant.ZERO);
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: subscriptionFailed method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.Subscription.CFTSubscriptionFailed);
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        }
    };

    //UnSubscribe the businesses
    $scope.unSubscribeBusiness = function () {
        if ($scope.checkedSubscriptionBusiness.toString() != '') {
            var data = {
                MulitipleIDs: $scope.checkedSubscriptionBusiness.toString()
            };
            // UnSubscribeBusiness method is available in constants.js
            wacorpService.post(webservices.Subscription.UnSubscribeBusiness, data, function (response) {
                if (response.data.isSuccess) {
                    $scope.checkedSubscriptionBusiness = [];
                    loadSubscriptionList(constant.ZERO); // loadSubscriptionList method is available in this controller only.
                    // Folder Name: app Folder
                    // Alert Name: unSubscriptionSuccess method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.Subscription.unSubscriptionSuccess);
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: unSubscriptionFailed method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.Subscription.unSubscriptionFailed);
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        }
    };

    //UnSubscribe the CFT businesses
    $scope.unSubscribeCFTBusiness = function () {
        if ($scope.checkedCFTSubscriptionBusiness.length > 0) {
            var data = {
                CFTBusinessList: $scope.checkedCFTSubscriptionBusiness, FilerId: $rootScope.repository.loggedUser.userid
            };
            // UnSubscribeBusiness method is available in constants.js
            wacorpService.post(webservices.Subscription.UnSubscribeCFTBusiness, data, function (response) {
                if (response.data.isSuccess) {
                    $scope.checkedCFTSubscriptionBusiness = [];
                    loadCFTSubscriptionList(constant.ZERO); // loadCFTSubscriptionList method is available in this controller only.
                    // Folder Name: app Folder
                    // Alert Name: unSubscriptionSuccess method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.Subscription.CFTUnSubscriptionSuccess);
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: unSubscriptionFailed method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.Subscription.CFTUnSubscriptionFailed);
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        }
    };

    $scope.CAmenu = function () {
        if ($rootScope.repository.loggedUser != null)
            return $rootScope.repository.loggedUser.filerTypeId == filerType.CommercialRegisteredAgent && $rootScope.repository.loggedUser.agentid != 0;
    };

    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.businessSearchCriteria.ID = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.businessSearchCriteria.ID = pastedText;
            });
        }
    };

    $scope.setPastedFEIN = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.charitySearchCriteria.FEINNo = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.charitySearchCriteria.FEINNo = pastedText;
            });
        }
    };

    $scope.setUBILength = function (e) {
        if ($scope.businessSearchCriteria.ID != undefined && $scope.businessSearchCriteria.ID != null && $scope.businessSearchCriteria.ID != "" && $scope.businessSearchCriteria.ID.length >= 9) {
            // Allow: backspace, delete, tab, escape, enter and .
            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                // Allow: Ctrl+A, Command+A
                (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                // Allow: home, end, left, right, down, up
                (e.keyCode >= 35 && e.keyCode <= 40)) {
                // let it happen, don't do anything
                return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
            e.preventDefault();
        }
    };

    $scope.checkBusinessType = function (value) {

        $scope.checkedBusiness = [];
        $scope.checkedSubscriptionBusiness = [];

        $scope.checkedCFTBusiness = [];
        $scope.checkedCFTSubscriptionBusiness = [];

        if (value == "CFT") {
            $scope.businessCategoryType = businessCatType.CFT;
        }
        else {
            $scope.businessCategoryType = businessCatType.CORP;
        }
        $scope.page = constant.ZERO;
        $scope.page1 = constant.ZERO;
        $scope.pagesCount1 = constant.ZERO;
        $scope.totalCount1 = constant.ZERO;

        $scope.page2 = constant.ZERO;
        $scope.pagesCount2 = constant.ZERO;
        $scope.totalCount2 = constant.ZERO;

        $scope.page3 = constant.ZERO;
        $scope.pagesCount3 = constant.ZERO;
        $scope.totalCount3 = constant.ZERO;
        if ($scope.selectedTab == "subscription") {
            $scope.searchBusiness();
        }
    };

    $scope.setCFTUBILength = function (e) {
        if (e.currentTarget.value.length >= 9) {
            e.preventDefault();
        }
    };

    $scope.setCFTPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.charitySearchCriteria.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.charitySearchCriteria.UBINumber = pastedText;
            });
        }
    };

    //CFT Search Module -- START

    //1 -- CFT Subscriptions Search for -- MY SUBSCRIPTIONS
    function loadCFTSubscriptionList(page, sortBy) {
        //page = page || constant.ZERO;
        $scope.charitySearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        $scope.charitySearchCriteria.SearchType = searchTypes.SUBSCRIPTIONSEARCH;
        $scope.charitySearchCriteria.FilerId = $rootScope.repository.loggedUser.userid;
        $scope.charitySearchCriteria.BusinessStatusID = !angular.isNullorEmpty($scope.charitySearchCriteria.businessStatusInfo) ? $scope.charitySearchCriteria.businessStatusInfo.Key : 0;
        $scope.charitySearchCriteria.BusinessTypeId = (!angular.isNullorEmpty($scope.charitySearchCriteria.businesstype) && !angular.isNullorEmpty($scope.charitySearchCriteria.businesstype.Key)) ? $scope.charitySearchCriteria.businesstype.Key.split('`')[0] : constant.ZERO;
        if (sortBy != undefined) {
            if ($scope.charitySearchCriteria.SortBy == sortBy) {
                if ($scope.charitySearchCriteria.SortType == 'ASC') {
                    $scope.charitySearchCriteria.SortType = 'DESC';
                }
                else {
                    $scope.charitySearchCriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.charitySearchCriteria.SortBy = sortBy;
                $scope.charitySearchCriteria.SortType = 'ASC';
            }
        }
        $scope.modal.selectCFTSubscriptionAll = false;
        $scope.isButtonSearch = page == 0;

        //For Maintaing the Search Critera in Sorting
        var data = {};
        if (page == constant.ZERO && sortBy == undefined) {
            angular.copy($scope.charitySearchCriteria, $scope.SearchCriteria_bkp);
            //$scope.SearchCriteria_bkp = $scope.charitySearchCriteria;
            data = $scope.charitySearchCriteria;
        }
        else {
            data = $scope.SearchCriteria_bkp;
            data.PageID = $scope.charitySearchCriteria.PageID;
            data.SortType = $scope.charitySearchCriteria.SortType;
            data.SortBy = $scope.charitySearchCriteria.SortBy;
        }
        // getCFTForSubscription method is available in constants.js
        wacorpService.post(webservices.Subscription.getCFTForSubscription, data, function (response) {
            $scope.CFTSubscriptionList = response.data;
            angular.forEach($scope.CFTSubscriptionList, function (item) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                item.ModifiedDate = wacorpService.dateFormatService(item.ModifiedDate);
                item.ARDueDate = wacorpService.dateFormatService(item.ARDueDate);
                angular.forEach($scope.checkedCFTSubscriptionBusiness, function (innerItem) {
                    if (item.CFTId == innerItem.CFTId && item.BusinessType == innerItem.CFTType)
                        item.isSelect = true;
                });
            });
            if ($scope.isButtonSearch && response.data.length > 0) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                $scope.pagesCount2 = response.data.length < $scope.charitySearchCriteria.PageCount && page > 0 ? $scope.pagesCount2 : pagecount;
                $scope.totalCount2 = totalcount;
            }
            $scope.page2 = page;
            $scope.page = page;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    //Watch subscriptions Search List
    $scope.$watch('CFTSubscriptionList', function () {
        if ($scope.CFTSubscriptionList == undefined)
            return;
        if ($scope.CFTSubscriptionList.length == constant.ZERO) {
            $scope.totalCount2 = constant.ZERO;
            $scope.pagesCount2 = constant.ZERO;
            $scope.totalCount2 = constant.ZERO;
            $scope.page2 = constant.ZERO;
        }
    }, true);

    //2 -- CFT Business Search for -- ADD SUBSCRIPTIONS
    function loadCFTbusinessSearchList(page, sortBy) {
        //page = page || constant.ZERO;
        $scope.charitySearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        $scope.charitySearchCriteria.SearchType = searchTypes.BUSINESSSEARCH;
        $scope.charitySearchCriteria.FilerId = $rootScope.repository.loggedUser.userid;
        $scope.charitySearchCriteria.BusinessStatusID = !angular.isNullorEmpty($scope.charitySearchCriteria.businessStatusInfo) ? $scope.charitySearchCriteria.businessStatusInfo.Key : 0;
        $scope.charitySearchCriteria.BusinessTypeId = (!angular.isNullorEmpty($scope.charitySearchCriteria.businesstype) && !angular.isNullorEmpty($scope.charitySearchCriteria.businesstype.Key)) ? $scope.charitySearchCriteria.businesstype.Key.split('`')[0] : constant.ZERO;
        if (sortBy != undefined) {
            if ($scope.charitySearchCriteria.SortBy == sortBy) {
                if ($scope.charitySearchCriteria.SortType == 'ASC') {
                    $scope.charitySearchCriteria.SortType = 'DESC';
                }
                else {
                    $scope.charitySearchCriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.charitySearchCriteria.SortBy = sortBy;
                $scope.charitySearchCriteria.SortType = 'ASC';
            }
        }
        $scope.modal.selectCFTAll = false;
        $scope.isButtonSearch = page == 0;

        //For Maintaing the Search Critera in Sorting
        var data = {};
        if (page == constant.ZERO && sortBy == undefined) {
            angular.copy($scope.charitySearchCriteria, $scope.SearchCriteria_bkp);
            //$scope.SearchCriteria_bkp = $scope.charitySearchCriteria;
            data = $scope.charitySearchCriteria;
        }
        else {
            data = $scope.SearchCriteria_bkp;
            data.PageID = $scope.charitySearchCriteria.PageID;
            data.SortType = $scope.charitySearchCriteria.SortType;
            data.SortBy = $scope.charitySearchCriteria.SortBy;
        }
        // getCFTForSubscription method is available in constants.js
        wacorpService.post(webservices.Subscription.getCFTForSubscription, data, function (response) {
            $scope.CFTSearchList = response.data;
            angular.forEach($scope.CFTSearchList, function (item) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                item.ModifiedDate = wacorpService.dateFormatService(item.ModifiedDate);
                item.ARDueDate = wacorpService.dateFormatService(item.ARDueDate);
                angular.forEach($scope.checkedCFTBusiness, function (innerItem) {
                    if (item.CFTId == innerItem.CFTId && item.BusinessType == innerItem.CFTType)
                        item.isSelect = true;
                });
            });
            if ($scope.isButtonSearch && response.data.length > 0) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                $scope.pagesCount3 = response.data.length < $scope.charitySearchCriteria.PageCount && page > 0 ? $scope.pagesCount3 : pagecount;
                $scope.totalCount3 = totalcount;
            }
            $scope.page3 = page;
            $scope.page = page;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    //Watch my Business Search List
    $scope.$watch('CFTSearchList', function () {
        if ($scope.CFTSearchList == undefined)
            return;
        if ($scope.CFTSearchList.length == constant.ZERO) {
            $scope.totalCount3 = constant.ZERO;
            $scope.pagesCount3 = constant.ZERO;
            $scope.totalCount3 = constant.ZERO;
            $scope.page3 = constant.ZERO;
        }
    }, true);

    $scope.cleartext = function (value) {
        switch (value) {
            case "RegistrationNumber":
                $scope.charitySearchCriteria.EntityName = null;
                $scope.charitySearchCriteria.FEINNo = null;
                $scope.charitySearchCriteria.UBINumber = null;
                break;
            case "FEINNo":
                $scope.charitySearchCriteria.RegistrationNumber = null;
                $scope.charitySearchCriteria.EntityName = null;
                $scope.charitySearchCriteria.UBINumber = null;
                break;
            case "UBINumber":
                $scope.charitySearchCriteria.RegistrationNumber = null;
                $scope.charitySearchCriteria.EntityName = null;
                $scope.charitySearchCriteria.FEINNo = null;
                break;
            case "OrganizationName":
                $scope.charitySearchCriteria.RegistrationNumber = null;
                $scope.charitySearchCriteria.FEINNo = null;
                $scope.charitySearchCriteria.UBINumber = null;
                break;
            default:

        }
    };

    //CFT Search Module -- End

});



wacorpApp.controller('dashboardController', function ($scope, $sce, $http, $rootScope, wacorpService, $location) {
    $scope.subscriptionLayout = "/ng-app/view/Subscriptions/Subscription.html";
    $scope.selectedTab = 'myBusiness';
    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.documentType = "";
    $scope.userId = 0;
    $scope.search = null;
    $scope.MailBoxList = {};
    $scope.mailContent = "";

    $scope.criteria = {

    };

    $scope.getDashboardCounts = function () {
        var data = { params: { filerId: $rootScope.repository.loggedUser.userid } };
        // getDashboardCounts method is available in constants.js
        wacorpService.get(webservices.Dashboard.getDashboardCounts, data, function (response) { $scope.DashboardCounts = response.data; }, function (response) { });
    };

    $scope.getDashboardCounts(); // getDashboardCounts method is available in this controller only.

    $scope.getCorrespondenceList = function () {
        $scope.search = getCorrespondences;
        getCorrespondences(0) // getCorrespondences method is available in this controller only.
    };
    function getCorrespondences(page, sortBy) {
        page = page || 0;
        if (sortBy != undefined) {
            if ($scope.criteria.SortBy == sortBy) {
                if ($scope.criteria.SortType == 'ASC') {
                    $scope.criteria.SortType = 'DESC';
                }
                else {
                    $scope.criteria.SortType = 'ASC';
                }
            }
            else {
                $scope.criteria.SortBy = sortBy;
                $scope.criteria.SortType = 'ASC';
            }
        }
        $scope.criteria.Type= docuementTypeIds.CORRESPONDENCES; $scope.criteria.UserId= $rootScope.repository.loggedUser.userid; $scope.criteria.PageCount= 10; $scope.criteria.PageID= page == 0 ? 1 : page + 1 ;
        var data = $scope.criteria;
        // getCorrespondenceList method is available in constants.js
        wacorpService.post(webservices.Dashboard.getCorrespondenceList, data, function (response) {
            $rootScope.CorrespondenceList = response.data.Correspondencelist;
            if (page == 0 && response.data.Correspondencelist.length > constant.ZERO) {
                var totalcount = response.data.Correspondencelist.length > constant.ZERO ? response.data.TotalRowsCount : constant.ZERO;
                var pagecount = totalcount / response.data.Correspondencelist.length > Math.round(totalcount / response.data.Correspondencelist.length)
                                    ? Math.round(totalcount / response.data.Correspondencelist.length) + 1 : Math.round(totalcount / response.data.Correspondencelist.length);
                $scope.pagesCount = response.data.Correspondencelist.length < 10 && page > 0 ? $scope.pagesCount : pagecount;
                $scope.totalCount = totalcount;
            }
            $scope.page = page;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };


    /* Mail Box */
    $scope.getMailBoxList = function () {
        var filerParams = { params: { filerid: $rootScope.repository.loggedUser.userid } };
        // getMailBox method is available in constants.js
        wacorpService.get(webservices.MailBox.getMailBox, filerParams, function (response) {
            $scope.MailBoxList = response.data;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.deleteMail = function (mailItem) {
        var mailParams = { params: { id: mailItem.ID } };
        // Folder Name: app Folder
        // Alert Name: deleteConfirmation method is available in alertMessages.js 
        wacorpService.confirmDialog(messages.deleteConfirmation, function () {
            // deleteMailItem method is available in constants.js
            wacorpService.get(webservices.MailBox.deleteMailItem, mailParams, function (response) {
                // Folder Name: app Folder
                // Alert Name: MailBoxDeleteMsg method is available in alertMessages.js 
                wacorpService.alertDialog(messages.MailBoxDeleteMsg);
                $scope.getMailBoxList(); // getMailBoxList method is available in this controller only.
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        });
    };

    $scope.viewMail = function (mailItem) {
        $scope.mailContent = $sce.trustAsHtml(mailItem.MailContent);
        $("#divMailContent").modal('toggle');
    };

    $scope.getReceiptList = function () {
        $scope.search = getReceipts;
        getReceipts(0) // getReceipts method is available in this controller only.
    };
    function getReceipts(page, sortBy) {
        page = page || 0;
        if (sortBy != undefined) {
            if ($scope.criteria.SortBy == sortBy) {
                if ($scope.criteria.SortType == 'ASC') {
                    $scope.criteria.SortType = 'DESC';
                }
                else {
                    $scope.criteria.SortType = 'ASC';
                }
            }
            else {
                $scope.criteria.SortBy = sortBy;
                $scope.criteria.SortType = 'ASC';
            }
        }
        $scope.criteria.Type = docuementTypeIds.RECEIPTS; $scope.criteria.UserId = $rootScope.repository.loggedUser.userid; $scope.criteria.PageCount = 10; $scope.criteria.PageID = page == 0 ? 1 : page + 1;
        var data = $scope.criteria;
        // getReceiptList method is available in constants.js
        wacorpService.post(webservices.Dashboard.getReceiptList, data, function (response) {
            $rootScope.ReceiptList = response.data.RecieptList;
            if (page == 0 && response.data.RecieptList.length > constant.ZERO) {
                var totalcount = response.data.RecieptList.length > constant.ZERO ? response.data.TotalRowsCount : constant.ZERO;
                var pagecount = totalcount / response.data.RecieptList.length > Math.round(totalcount / response.data.RecieptList.length)
                                    ? Math.round(totalcount / response.data.RecieptList.length) + 1 : Math.round(totalcount / response.data.RecieptList.length);
                $scope.pagesCount = response.data.RecieptList.length < 10 && page > 0 ? $scope.pagesCount : pagecount;
                $scope.totalCount = totalcount;
            }
            $scope.page = page;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.backtoDashboard = function () {
        $location.path('/Dashboard');
    };
    $scope.downloadFile = function (location) {
        var path = filePath.sharedPath + location;
        return false;
    };

    $scope.swtichTabs = function (navigation) {
        $scope.selectedTab = navigation;
    };

    //$scope.getTransactionDocumentsList = function getTransactionDocumentsList(Transactionid) {
    //    var criteria = {
    //        ID: Transactionid
    //    };
    //    wacorpService.post(webservices.WorkOrder.GetTransactionDocuments, criteria,
    //        function (response) {
    //            if (response.data != null) {
    //                $scope.transactionDocumentsList = angular.copy(response.data);
    //                $("#divSearchResult").modal('toggle');
    //            }
    //            else
    //                wacorpService.alertDialog($scope.messages.noDataFound);
    //        },
    //        function (response) {
    //            wacorpService.alertDialog(response.data.Message);
    //        }
    //    );
    //}


    $scope.getTransactionDocumentsList = function getTransactionDocumentsList(FilingNumber, Transactionid, filingTypeName) {
        FilingNumber = ((filingTypeName == 'COMMERCIAL STATEMENT OF CHANGE' || filingTypeName == 'COMMERCIAL TERMINATION STATEMENT') && Transactionid > 0 ? 0 : FilingNumber);
        var criteria = {
            ID: Transactionid, FilingNumber: FilingNumber
        };
        // getOnlineCorrespondenceDocumentsList method is available in constants.js
        wacorpService.post(webservices.Dashboard.getOnlineCorrespondenceDocumentsList, criteria,
            function (response) {
                if (response.data != null) {
                    $scope.transactionDocumentsList = angular.copy(response.data);
                    $("#divSearchResult").modal('toggle');
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: noDataFound method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.noDataFound);
            },
            function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data.Message);
            }
        );
    }

    $scope.deleteCorrespondence = function (transactionID, FilingNumber, CategoryType) {
        var Params = { params: { transactionID: transactionID, filingNumber: FilingNumber, categoryType: CategoryType } };
        // Folder Name: app Folder
        // Alert Name: deleteConfirmation method is available in alertMessages.js
        wacorpService.confirmDialog(messages.deleteConfirmation, function () {
            // deleteCorrespondence method is available in constants.js
            wacorpService.get(webservices.Dashboard.deleteCorrespondence, Params, function (response) {
                // Folder Name: app Folder
                // Alert Name: NoticesandFiledDocumentsDeleteMsg method is available in alertMessages.js
                wacorpService.alertDialog(messages.NoticesandFiledDocumentsDeleteMsg);
                $scope.getCorrespondenceList(); // getCorrespondenceList method is available in this controller only.
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        });
    };

    $scope.deleteReceipts = function (documentId) {
        var Params = { params: { documentId: documentId } };
        // Folder Name: app Folder
        // Alert Name: deleteConfirmation method is available in alertMessages.js
        wacorpService.confirmDialog(messages.deleteConfirmation, function () {
            // deleteReceipts method is available in constants.js
            wacorpService.get(webservices.Dashboard.deleteReceipts, Params, function (response) {
                // Folder Name: app Folder
                // Alert Name: ReceiptsDeleteMsg method is available in alertMessages.js
                wacorpService.alertDialog(messages.ReceiptsDeleteMsg);
                $scope.getReceiptList(); // getReceiptList method is available in this controller only
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        });
    };


});



wacorpApp.controller('CertificateOfDissolutionController', function ($scope, $location, $rootScope, wacorpService) {
    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.BusinessStatus) >= constant.ZERO) {
            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
            $rootScope.certificateOfDissolutionModel = null;
            $rootScope.transactionID = null;
            $location.path('/CertificateOfDissolution');
        }
        else {
            // Folder Name: app Folder
            // Alert Name: selectedBusiness method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(messages.selectedBusiness.replace('{0}', $scope.selectedBusiness.BusinessStatus));
        }
    }
    //---------------------------- Certificate Of Dissolution screen functionality --------------------//

    $scope.$watch(function () {
        if (!angular.isNullorEmpty($scope.modal))
            $scope.isRequired = ($scope.modal.DissolutionCheckType == constant.ONE || $scope.modal.DissolutionCheckType == constant.TWO) ? false : true;
    });

    $scope.Init = function () {
        $scope.messages = messages;
        $scope.validateErrorMessage = false;
        var data = null;
        if ($rootScope.transactionID > constant.ZERO)
            data = {
                params: {
                    businessID: null, transactionID: $rootScope.transactionID,
                }
            };
        else
            data = {
                params: {
                    businessID: $rootScope.BusinessID, transactionID: $rootScope.transactionID
                }
            };
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.certificateOfDissolutionModel = $rootScope.modal;
            //$rootScope.modal = null;
        }
        if (angular.isNullorEmpty($rootScope.certificateOfDissolutionModel)) {
            if ($rootScope.BusinessID == undefined && $rootScope.transactionID == undefined) {
                $location.path('/StatementofWithdrawalIndex');
            }
            else {
                // CertificateOfDissolutionCriteria method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.CertificateOfDissolutionCriteria, data, function (response) {
                    $scope.modal = response.data;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || ResultStatus.INDIVIDUAL;
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? codes.WASHINGTON : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    $scope.modal.IsArticalsExist = $scope.modal.IsArticalsExist ? true : $scope.modal.IsArticalsExist;
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.DateOfAdoption = wacorpService.dateFormatService($scope.modal.DateOfAdoption);
                    $scope.modal.DissolutionApprovalDate = wacorpService.dateFormatService($scope.modal.DissolutionApprovalDate);
                    $scope.modal.BusinessFiling.EffectiveDate = wacorpService.dateFormatService($scope.modal.BusinessFiling.EffectiveDate);
                    $scope.modal.EffectiveDateType = angular.isNullorEmpty($scope.modal.EffectiveDateType) ? ResultStatus.DATEOFFILING : $scope.modal.EffectiveDateType;
                    $scope.modal.BusinessFiling.DateOfAdoption = wacorpService.dateFormatService($scope.modal.BusinessFiling.DateOfAdoption);
                    $scope.modal.DateOfAdoptionType = angular.isNullorEmpty($scope.modal.DateOfAdoptionType) ? ResultStatus.DATEOFADOPTIONFILING : $scope.modal.DateOfAdoptionType;
                    $scope.modal.DissolutionCheckType = $scope.modal.DissolutionCheckType == constant.ZERO ? constant.ONE : $scope.modal.DissolutionCheckType;
                    var correspondenceAddress = {
                        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                            FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                        }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                        State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null,
                        PostalCode: null, County: null, CountyName: null
                    }
                    $scope.modal.CorrespondenceAddress = $scope.modal.CorrespondenceAddress ? angular.extend(correspondenceAddress, $scope.modal.CorrespondenceAddress) : angular.copy(correspondenceAddress);

                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                    $scope.isShowReturnAddress = true;
                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js (you can search with file name in solution explorer)
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                }, function (response) { $scope.isShowContinue = false; });
            }
        }

        else {
            $scope.modal = $rootScope.certificateOfDissolutionModel;
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.BusinessFiling.EffectiveDate = "";
            if ($scope.modal.DateOfAdoptionType == 'DateOfAdoptionFiling')
                $scope.modal.BusinessFiling.DateOfAdoption = "";

            $scope.modal.BusinessFiling.EffectiveDate = wacorpService.dateFormatService($scope.modal.BusinessFiling.EffectiveDate);
            $scope.modal.BusinessFiling.DateOfAdoption = wacorpService.dateFormatService($scope.modal.BusinessFiling.DateOfAdoption);
            $scope.isShowReturnAddress = true;
        }
    }


    // back to annual report business serarch
    $scope.back = function () {
        $location.path('/StatementofWithdrawalIndex');
    };

    // validate & continue annual report for review
    $scope.ContinueSave = function (certificateOfDissolutionform) {
        $scope.validateErrorMessage = true;

        //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
        if (($scope.modal.AgentEntity.EmailAddress == "" || $scope.modal.AgentEntity.EmailAddress == null || $scope.modal.AgentEntity.EmailAddress == undefined)) {
	        $scope.modal.IsEmailOptionChecked = false;
        }

        var isEffectiveDateValid = $scope[certificateOfDissolutionform].EffectiveDate.$valid;

        var isDateOfAdoptionValid = $scope.modal.BusinessType != 'WA LIMITED LIABILITY COMPANY' ? $scope[certificateOfDissolutionform].DateOfAdoption.$valid : true;

        //var isDissolutionApprovalDateValid = $scope[certificateOfDissolutionform].DissolutionApprovalForm.$valid;

        var isDissolutionAttensationChecked = $scope[certificateOfDissolutionform].DissolutionAttestationsForm.$valid;

        var isCleranceCertificateUploadValid = $scope.modal.IsArticalsExist ? ($scope.modal.IsArticalsExist && $scope.modal.ClearanceCertificateList != null && $scope.modal.ClearanceCertificateList.length > constant.ZERO) : true;

        var isCorrespondenceAddressValid = $scope[certificateOfDissolutionform].CorrespondenceAddress.$valid;

        var isAuthorizedPersonValid = $scope[certificateOfDissolutionform].AuthorizedPersonForm.$valid;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isFormValid = isEffectiveDateValid && isDissolutionAttensationChecked
                            && isCleranceCertificateUploadValid && isAuthorizedPersonValid && isDateOfAdoptionValid && isAdditionalUploadValid && isCorrespondenceAddressValid;

        if (isFormValid) {
            $scope.validateErrorMessage = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.CorrespondenceAddress.FullAddress = wacorpService.fullAddressService($scope.modal.CorrespondenceAddress);
            if ($scope.modal.EffectiveDateType == ResultStatus.DATEOFFILING)
                $scope.modal.BusinessFiling.EffectiveDate = new Date();
            if ($scope.modal.DateOfAdoptionType == ResultStatus.DATEOFADOPTIONFILING)
                $scope.modal.BusinessFiling.DateOfAdoption = new Date();
            else
                $scope.modal.BusinessFiling.DateOfAdoption = $scope.modal.DateOfAdoption;

            $rootScope.certificateOfDissolutionModel = $scope.modal;
            $rootScope.modal = $scope.modal;
            $location.path("/CertificateOfDissolutionReview");
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };
    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/CertificateOfDissolution';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // CertificateofDissolutionSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CertificateofDissolutionSaveAsDraft, $scope.modelDraft, function (response) {

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

});

wacorpApp.controller('CertificateOfDissolutionReviewController', function ($scope, $location, $rootScope, wacorpService) {
    //scope load
    $scope.Init = function () {
        if (angular.isNullorEmpty($rootScope.certificateOfDissolutionModel))
            $location.path('/CertificateOfDissolutionIndex');
        else
            $scope.modal = $rootScope.certificateOfDissolutionModel;
    }
    // add filing to cart
    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CertificateOfDissolutionAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CertificateOfDissolutionAddToCart, $scope.modal, function (response) {
            $rootScope.certificateOfDissolutionModel = null;
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $location.path('/shoppingCart');
          
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    // back to Statement of Withdrawal flow
    $scope.back = function () {
        $rootScope.certificateOfDissolutionModel = $scope.modal;
        $location.path('/CertificateOfDissolution');
    };

    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        // CertificateOfDissolutionAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CertificateOfDissolutionAddToCart, $scope.modal, function (response) {
            $rootScope.certificateOfDissolutionModel = null;
            $rootScope.transactionID = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
            $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('ArticlesOfDissolutionController', function ($scope, $location, $rootScope, wacorpService) {
    /* --------Business Search Functionality------------- */
    $scope.modal = {};
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {      
        if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT, ResultStatus.AdministrativelyDissolved].indexOf($scope.selectedBusiness.BusinessStatus) >= constant.ZERO) {
            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
            $rootScope.articlesOfDissolutionModel = null;
            $rootScope.transactionID = null;
            $location.path('/ArticlesOfDissolution');
        }
        else {
            // Folder Name: app Folder
            // Alert Name: selectedBusiness method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(messages.selectedBusiness.replace('{0}', $scope.selectedBusiness.BusinessStatus));
        }
    }

    //---------------------------- Articles Of Dissolution screen functionality --------------------//

    $scope.$watch(function () {
        $scope.isRequired = angular.isNullorEmpty($scope.modal) ? false :
            ($scope.modal.DissolutionCheckType == constant.ONE || $scope.modal.DissolutionCheckType == constant.TWO) ? false : true;
    });

    $scope.Init = function () {      
        $scope.dateOptions = {
            minDate: new Date()
        };
        $scope.messages = messages;
        $scope.validateErrorMessage = false;
        $scope.isDissolutionApprovalRequiredSection = true;
        $scope.isDissolutionApprovalRequiredSectionNonProfit = true;//TFS 2365
        $scope.canShowDissolutionAttestationsProvidedForWaPublicRequiredSection = false;
        $scope.isClearanceCertificateRequiredSection = true;
        $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = null;
        $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = null;

        var data = null;
        if ($rootScope.transactionID > constant.ZERO)
            data = {
                params: {
                    businessID: null, transactionID: $rootScope.transactionID,
                }
            };
        else
            data = {
                params: {
                    businessID: $rootScope.BusinessID, transactionID: $rootScope.transactionID
                }
            };
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.articlesOfDissolutionModel = $rootScope.modal;
            //$rootScope.modal = null;
        }
        if (angular.isNullorEmpty($rootScope.articlesOfDissolutionModel)) {
            if ($rootScope.BusinessID == undefined && $rootScope.transactionID == undefined) {
                $location.path('/StatementofWithdrawalIndex');
            }
            else {
                // ArticlesOfDissolutionCriteria method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.ArticlesOfDissolutionCriteria, data, function (response) {
                    $scope.modal = response.data;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || ResultStatus.INDIVIDUAL;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.DateOfAdoption = wacorpService.dateFormatService($scope.modal.DateOfAdoption);
                    $scope.modal.DissolutionApprovalDate = wacorpService.dateFormatService($scope.modal.DissolutionApprovalDate);

                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? codes.WASHINGTON : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    $scope.modal.IsArticalsExist = $scope.modal.IsArticalsExist ? true : $scope.modal.IsArticalsExist;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.modal.BusinessFiling.EffectiveDate = wacorpService.dateFormatService($scope.modal.BusinessFiling.EffectiveDate);
                    $scope.modal.EffectiveDateType = angular.isNullorEmpty($scope.modal.EffectiveDateType) ? ResultStatus.DATEOFFILING : $scope.modal.EffectiveDateType;
                    $scope.modal.BusinessFiling.DateOfAdoption = wacorpService.dateFormatService($scope.modal.BusinessFiling.DateOfAdoption);
                    $scope.modal.DateOfAdoptionType = angular.isNullorEmpty($scope.modal.DateOfAdoptionType) ? ResultStatus.DATEOFADOPTIONFILING : $scope.modal.DateOfAdoptionType;
                    $scope.modal.IsDissolutionAttestedChecked = angular.isNullorEmpty($scope.modal.IsDissolutionAttestedChecked) ? true : $scope.modal.IsDissolutionAttestedChecked;
                    $scope.modal.DissolutionCheckType = $scope.modal.DissolutionCheckType == constant.ZERO ? constant.ONE : $scope.modal.DissolutionCheckType;
                    $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = wacorpService.dateFormatService($scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit);
                    var correspondenceAddress = {
                        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                            FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                        }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                        State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null,
                        PostalCode: null, County: null, CountyName: null
                    }
                    $scope.modal.CorrespondenceAddress = $scope.modal.CorrespondenceAddress ? angular.extend(correspondenceAddress, $scope.modal.CorrespondenceAddress) : angular.copy(correspondenceAddress);

                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;

                    //$scope.modal.AdoptionofArticlesofAmendmentNonProfit = !angular.isNullorEmpty($scope.modal.AdoptionofArticlesofAmendmentNonProfit) ? $scope.modal.AdoptionofArticlesofAmendmentNonProfit : 'M';//Commented for 13.7
                    $scope.DateofAdoptionOfArticlesOfAmendmentNonProfit();

                    //Commented and Added for 13.7 - TFS 2365
                    //var canShowDissolution = $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION
                    //    || $scope.modal.BusinessTypeID == businessTypeIDs.WAMISCELLANEOUSANDMUTUALCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WACORPSOLE || $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WAPUBLICBENEFITCORPORATION;//$scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION ||
                    //$scope.isDissolutionApprovalRequiredSection = !canShowDissolution;

                    var canShowDissolution = $scope.modal.BusinessTypeID == businessTypeIDs.WAMISCELLANEOUSANDMUTUALCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WACORPSOLE;//$scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION ||
                    $scope.isDissolutionApprovalRequiredSection = !canShowDissolution;

                    var canShowDissolutionNonProfit =
	                    $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION;
                    $scope.isDissolutionApprovalRequiredSectionNonProfit = !canShowDissolutionNonProfit;

                    if (canShowDissolution) {
	                    $scope.modal.AdoptionofArticlesofAmendmentNonProfit =
		                    !angular.isNullorEmpty($scope.modal.AdoptionofArticlesofAmendmentNonProfit)
		                    ? $scope.modal.AdoptionofArticlesofAmendmentNonProfit
		                    : 'M'; 
                    }

                    //if (canShowDissolutionNonprofit) {
                	//	$scope.modal.AdoptionOfArticlesOfAmendmentOnlyNonProfitM = 'NM';
	                    //$scope.modal.AdoptionofArticlesofAmendmentNonProfit =
	                    //    !angular.isNullorEmpty($scope.modal.AdoptionofArticlesofAmendmentNonProfit)
	                    //    ? $scope.modal.AdoptionofArticlesofAmendmentNonProfit
	                    //    : 'YM'; 
                	//}

                    var canShowDissolutionAttestations = $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFITCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALSERVICECORPORATION
	                    || $scope.modal.BusinessTypeID == governerAddressRequiredEntityTypeID.WaPublicUtilityCorporation || $scope.modal.BusinessTypeID == governerAddressRequiredEntityTypeID.WaSocialPurposeCorporation
	                    || $scope.modal.BusinessTypeID == governerAddressRequiredEntityTypeID.WaMassachusettsTrust;
                    $scope.isDissolutionAttestationsRequiredSection = !canShowDissolutionAttestations;
					
                    var canShowDissolutionAttestationsNonProfit = $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION;
                    $scope.isDissolutionAttestationsRequiredSectionNonProfit = !canShowDissolutionAttestationsNonProfit;

                	//Ends here TFS 2365

                    var canShowDissolutionAttestationsProvidedForWaPublic = $scope.modal.BusinessTypeID == businessTypeIDs.WAPUBLICBENEFITCORPORATION;
                    $scope.canShowDissolutionAttestationsProvidedForWaPublicRequiredSection = canShowDissolutionAttestationsProvidedForWaPublic;

                    var canShowClearanceCertificate = $scope.modal.BusinessTypeID == businessTypeIDs.WALIMITEDLIABILITYPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.WALIMITEDLIABILITYLIMITEDPARTNERSHIP
                      || $scope.modal.BusinessTypeID == businessTypeIDs.WALIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP
                    || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDLIABILITYPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDPARTNERSHIP;
                    $scope.isClearanceCertificateRequiredSection = !canShowClearanceCertificate;

                    if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                        $scope.modal.BusinessFiling.EffectiveDate = "";
                    if ($scope.modal.DateOfAdoptionType == 'DateOfAdoptionFiling')
                        $scope.modal.BusinessFiling.DateOfAdoption = "";
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                    $scope.isShowReturnAddress =true;
                    $scope.isReturnAddMandatory();//to check Return address is mandatory

                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js (you can search with file name in solution explorer)
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                }, function (response) { $scope.isShowContinue = false; });

            }
        }

        else {
            $scope.isShowReturnAddress =true;
            $scope.modal = $rootScope.articlesOfDissolutionModel;
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.BusinessFiling.EffectiveDate = "";
            if ($scope.modal.DateOfAdoptionType == 'DateOfAdoptionFiling')
                $scope.modal.BusinessFiling.DateOfAdoption = "";

            $scope.modal.BusinessFiling.EffectiveDate = wacorpService.dateFormatService($scope.modal.BusinessFiling.EffectiveDate);
            $scope.modal.BusinessFiling.DateOfAdoption = wacorpService.dateFormatService($scope.modal.BusinessFiling.DateOfAdoption);

            $scope.modal.DateOfAdoption = wacorpService.dateFormatService($scope.modal.DateOfAdoption);
            // @1195 date format Issue.
            if ($scope.modal.DissolutionApprovalDate)
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.DissolutionApprovalDate = wacorpService.dateFormatService($scope.modal.DissolutionApprovalDate);

            //Commented and Added for 13.7 - TFS 2365
            //var canShowDissolution = $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION
            //           || $scope.modal.BusinessTypeID == businessTypeIDs.WAMISCELLANEOUSANDMUTUALCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WACORPSOLE || $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WAPUBLICBENEFITCORPORATION;
            //$scope.isDissolutionApprovalRequiredSection = !canShowDissolution;
        	
            var canShowDissolution = $scope.modal.BusinessTypeID == businessTypeIDs.WAMISCELLANEOUSANDMUTUALCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WACORPSOLE;
            $scope.isDissolutionApprovalRequiredSection = !canShowDissolution;

            var canShowDissolutionNonProfit = $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION;
            $scope.isDissolutionApprovalRequiredSectionNonProfit = !canShowDissolutionNonProfit;

            var canShowDissolutionAttestations = $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFITCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALSERVICECORPORATION
	            || $scope.modal.BusinessTypeID == governerAddressRequiredEntityTypeID.WaPublicUtilityCorporation || $scope.modal.BusinessTypeID == governerAddressRequiredEntityTypeID.WaSocialPurposeCorporation
	            || $scope.modal.BusinessTypeID == governerAddressRequiredEntityTypeID.WaMassachusettsTrust;
            $scope.isDissolutionAttestationsRequiredSection = !canShowDissolutionAttestations;

            var canShowDissolutionAttestationsNonProfit = $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION;
            $scope.isDissolutionAttestationsRequiredSectionNonProfit = !canShowDissolutionAttestationsNonProfit;

            //Ends here

            var canShowDissolutionAttestationsProvidedForWaPublic = $scope.modal.BusinessTypeID == businessTypeIDs.WAPUBLICBENEFITCORPORATION;
            $scope.canShowDissolutionAttestationsProvidedForWaPublicRequiredSection = canShowDissolutionAttestationsProvidedForWaPublic;

            var canShowClearanceCertificate = $scope.modal.BusinessTypeID == businessTypeIDs.WALIMITEDLIABILITYPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.WALIMITEDLIABILITYLIMITEDPARTNERSHIP
                    || $scope.modal.BusinessTypeID == businessTypeIDs.WALIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP
                  || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDLIABILITYPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDPARTNERSHIP;
            $scope.isClearanceCertificateRequiredSection = !canShowClearanceCertificate;

            $scope.DateofAdoptionOfArticlesOfAmendmentNonProfit();

            $scope.isReturnAddMandatory();//to check Return address is mandatory
        }
    }

    // back to annual report business serarch
    $scope.back = function () {
        $location.path('/StatementofWithdrawalIndex');
    };

    $scope.isReturnAddMandatory = function () {
        if ($scope.modal.BusinessType != undefined && $scope.modal.BusinessType != null && $scope.modal.BusinessType != "") {
            if ($scope.modal.BusinessType == "WA NONPROFIT CORPORATION"
                || $scope.modal.BusinessType == "WA PROFIT CORPORATION"
                || $scope.modal.BusinessType == "WA SOCIAL PURPOSE CORPORATION "
                || $scope.modal.BusinessType == "WA MASSACHUSETTS TRUST"
                || $scope.modal.BusinessType == "WA MISCELLANEOUS AND MUTUAL CORPORATION"
                || $scope.modal.BusinessType == "WA NONPROFIT PROFESSIONAL SERVICE CORPORATION"
                || $scope.modal.BusinessType == "WA PROFESSIONAL SERVICE CORPORATION"
                || $scope.modal.BusinessType == "WA PUBLIC BENEFIT CORPORATION"
                || $scope.modal.BusinessType == "WA PUBLIC UTILITY CORPORATION")
            {
                $scope.isMandatory = true;
            }
            else
                $scope.isMandatory = false;
        }
    };

    // validate & continue annual report for review
    $scope.ContinueSave = function (articlesOfDissolutionform) {
        $scope.isShowReturnAddress =true;
        $scope.validateErrorMessage = true;

        //Added for 13.7 - TFS 2365
        if ($scope.modal.AdoptionOfArticlesOfAmendmentOnlyNonProfitB) {
	        $scope.modal.AdoptionofArticlesofAmendmentNonProfit = 'NMB';
        }
		
        if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'M') {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM;
        }
        else if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'B') {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB;
        }
        else {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = null;
        }

        //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
        if (($scope.modal.AgentEntity.EmailAddress == "" || $scope.modal.AgentEntity.EmailAddress == null || $scope.modal.AgentEntity.EmailAddress == undefined)) {
	        $scope.modal.IsEmailOptionChecked = false;
        }

        var isEffectiveDateValid = $scope[articlesOfDissolutionform].EffectiveDate.$valid;

        var isDateOfAdoptionValid = $scope.isDissolutionApprovalRequiredSection == false ? $scope[articlesOfDissolutionform].DateOfAdoption.$valid : true;

        var isDissolutionApprovalDateValid = $scope.isDissolutionApprovalRequiredSection == true ? $scope[articlesOfDissolutionform].DissolutionApprovalForm.$valid : true;

        // var isDissolutionAttensationChecked = ($scope.modal.BusinessTypeID != businessTypeIDs.WAPROFITCORPORATION) ? $scope[articlesOfDissolutionform].DissolutionAttestationsForm.$valid : true;

        var isCleranceCertificateUploadValid = $scope.modal.IsArticalsExist && $scope.modal.ClearanceCertificateList != null && $scope.modal.ClearanceCertificateList.length > constant.ZERO;

        var isCorrespondenceAddressValid = $scope[articlesOfDissolutionform].CorrespondenceAddress.$valid;

        var isAdoptionOfArticlesOfAmendmentNonProfitValid = $scope.isDissolutionApprovalRequiredSection == false ? $scope[articlesOfDissolutionform].AdoptionOfArticlesOfAmendmentNonProfitForm.$valid : true;

    	//var isAdoptionOfArticlesOfAmendmentOnlyNonProfitValid = $scope.isDissolutionApprovalRequiredSectionNonprofit == false ? $scope[articlesOfDissolutionform].AdoptionOfArticlesOfAmendmentOnlyNonProfitForm.$valid : true;
        var isAdoptionOfArticlesOfAmendmentOnlyNonProfitValid = $scope.modal.AdoptionOfArticlesOfAmendmentOnlyNonProfitM == "" ? false : true;

        var isAuthorizedPersonValid = $scope[articlesOfDissolutionform].AuthorizedPersonForm;

        //var isDissolutionAttestationsProvidedForWaPublicValid = $scope.canShowDissolutionAttestationsProvidedForWaPublicRequiredSection ? $scope[articlesOfDissolutionform].AdoptionOfArticlesOfAmendmentWABenefit.$valid : true;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        //isAdoptionOfArticlesOfAmendmentOnlyNonProfitValid = false;
        var isFormValid = isEffectiveDateValid && isDissolutionApprovalDateValid
            //&& isDissolutionAttensationChecked
           && isCleranceCertificateUploadValid && isAuthorizedPersonValid && isDateOfAdoptionValid && isAdoptionOfArticlesOfAmendmentNonProfitValid && isAdoptionOfArticlesOfAmendmentOnlyNonProfitValid  && isAdditionalUploadValid && isCorrespondenceAddressValid;//&& isDissolutionAttestationsProvidedForWaPublicValid


        if (isFormValid) {
            $scope.validateErrorMessage = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.CorrespondenceAddress.FullAddress = wacorpService.fullAddressService($scope.modal.CorrespondenceAddress);
            $rootScope.articlesOfDissolutionModel = $scope.modal;
            if ($scope.modal.EffectiveDateType == ResultStatus.DATEOFFILING)
                $scope.modal.BusinessFiling.EffectiveDate = new Date();
            if ($scope.modal.DateOfAdoptionType == ResultStatus.DATEOFADOPTIONFILING)
                $scope.modal.BusinessFiling.DateOfAdoption = new Date();
            else
                $scope.modal.BusinessFiling.DateOfAdoption = $scope.modal.DateOfAdoption;
            $rootScope.modal = $scope.modal;
            $location.path("/ArticlesOfDissolutionReview");
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };




    $scope.AdoptionofArticlesofAmendmentOnlyNonProfit = function () {
	    if ($scope.modal.TypeOfWithdrawal == "Dissolution in Home Jurisdiction") {
		    $scope.divDissolution = true;
		    $scope.divConversion = false;
	    }
	    else if ($scope.modal.TypeOfWithdrawal == "Conversion in Home Jurisdiction") {
		    $scope.divDissolution = false;
		    $scope.divConversion = true;
	    }
	    else {
		    $scope.divDissolution = false;
		    $scope.divConversion = false;
	    }
    }


    $scope.DateofAdoptionOfArticlesOfAmendmentNonProfit = function (isRadioBtn) {
        if (isRadioBtn) {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = '';
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = '';
        }
        else {
            if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'M') {
                $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = '';
                $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = wacorpService.dateFormatService($scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit);
            }
            else if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'B') {
                $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = '';
                $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = wacorpService.dateFormatService($scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit);
            }
            else {
                $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = '';
                $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = '';
                $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = null;
            }
        }
    }

	//clear Fields on selecting radiobutton for the adopted by -For 13.7 - TFS 2365
    $scope.clearFields = function () {
	    $scope.modal.AdoptionofArticlesofAmendmentNonProfit = null;
	    if ($scope.modal.AdoptionOfArticlesOfAmendmentOnlyNonProfitM == "YM") {
	    	$scope.modal.AdoptionOfArticlesOfAmendmentOnlyNonProfitB = null;
	    } 
    };

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
    	$scope.isShowReturnAddress = true;
        //Added for 13.7 - TFS 2365
    	if ($scope.modal.AdoptionOfArticlesOfAmendmentOnlyNonProfitB) {
	        $scope.modal.AdoptionofArticlesofAmendmentNonProfit = 'NMB';
        }

        if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'M') {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM;
        }
        else if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'B') {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB;
        }
        else {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = null;
        }

        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/ArticlesOfDissolution';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // ArticlesofDissolutionSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.ArticlesofDissolutionSaveAsDraft, $scope.modelDraft, function (response) {

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }
});

wacorpApp.controller('ArticlesOfDissolutionReviewController', function ($scope, $location, $rootScope, wacorpService) {
    //scope load
    $scope.Init = function () {        
        if (angular.isNullorEmpty($rootScope.articlesOfDissolutionModel))
            $location.path('/ArticlesOfDissolutionIndex');
        else
            $scope.modal = $rootScope.articlesOfDissolutionModel;

        var canShowDissolution =$scope.modal.BusinessTypeID == businessTypeIDs.WAMISCELLANEOUSANDMUTUALCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WACORPSOLE;
        $scope.isDissolutionApprovalRequiredSection = !canShowDissolution;

       //Added for 13.7 - TFS 2365
        var canShowDissolutionNonProfit = $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION;
        $scope.isDissolutionApprovalRequiredSectionNonProfit = !canShowDissolutionNonProfit;
    	
        var canShowDissolutionAttestations = $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFITCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALSERVICECORPORATION
	        || $scope.modal.BusinessTypeID == governerAddressRequiredEntityTypeID.WaPublicUtilityCorporation || $scope.modal.BusinessTypeID == governerAddressRequiredEntityTypeID.WaSocialPurposeCorporation
	        || $scope.modal.BusinessTypeID == governerAddressRequiredEntityTypeID.WaMassachusettsTrust;
        $scope.isDissolutionAttestationsRequiredSection = !canShowDissolutionAttestations;

        var canShowDissolutionAttestationsNonProfit = $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITPROFESSIONALSERVICECORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.WANONPROFITCORPORATION;
        $scope.isDissolutionAttestationsRequiredSectionNonProfit = !canShowDissolutionAttestationsNonProfit;

        //Ends here
		var canShowDissolutionAttestationsProvidedForWaPublic = $scope.modal.BusinessTypeID == businessTypeIDs.WAPUBLICBENEFITCORPORATION;
        $scope.canShowDissolutionAttestationsProvidedForWaPublicRequiredSection = canShowDissolutionAttestationsProvidedForWaPublic;
		
        var canShowClearanceCertificate = $scope.modal.BusinessTypeID == businessTypeIDs.WALIMITEDLIABILITYPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.WALIMITEDLIABILITYLIMITEDPARTNERSHIP
                   || $scope.modal.BusinessTypeID == businessTypeIDs.WALIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP
                 || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDLIABILITYPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.WAPROFESSIONALLIMITEDPARTNERSHIP;
        $scope.isClearanceCertificateRequiredSection = !canShowClearanceCertificate;
    }
    // add filing to cart
    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // ArticlesOfDissolutionAddToCart method is available constants.js
        wacorpService.post(webservices.OnlineFiling.ArticlesOfDissolutionAddToCart, $scope.modal, function (response) {
            $rootScope.articlesOfDissolutionModel = null;
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $location.path('/shoppingCart');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    // back to Statement of Withdrawal flow
    $scope.back = function () {       
        $rootScope.articlesOfDissolutionModel = $scope.modal;
        $location.path('/ArticlesOfDissolution');
    };

    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        // ArticlesOfDissolutionAddToCart method is available constants.js
        wacorpService.post(webservices.OnlineFiling.ArticlesOfDissolutionAddToCart, $scope.modal, function (response) {
            $rootScope.articlesOfDissolutionModel = null;
            $rootScope.transactionID = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

});

wacorpApp.controller('statementOfWithdrawalController', function ($scope, $location, $rootScope, wacorpService) {
    // scope variables
    $scope.modal = {};
    $scope.CountriesList = [];
    $scope.StatesList = [];
    $scope.NewCountriesList = [];
    $scope.NewStatesList = [];
    $scope.principalsCount = constant.ZERO;
    $scope.RequirmentsFlag = true;
    // page load
    $scope.Init = function () {
        $scope.CountryChangeDesc(); // CountryChangeDesc method is available in this controller only.
        $scope.NewCountryChangeDesc(); // NewCountryChangeDesc method is available in this controller only.
        $scope.businessTypes(); // businessTypes method is available in this controller only.

        $scope.validateErrorMessage = false;
        $scope.messages = messages;
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.statementOfWithdrawalModal = $rootScope.modal;
            //$rootScope.modal = null;
        }

        var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
            $scope.CountriesList = response.data;
        }, function (response) {
        });

        var lookupStatesParams = { params: { name: 'ForeignJurisdictionStates' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
            $scope.StatesList = response.data;
        }, function (response) {
        });

        var NewlookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, NewlookupCountriesParams, function (response) {
            $scope.NewCountriesList = response.data;
        }, function (response) {
        });

        var NewlookupStatesParams = { params: { name: 'JurisdictionStates' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, NewlookupStatesParams, function (response) {
            $scope.NewStatesList = response.data;
        }, function (response) {
        });

        $scope.isClearanceCertificateRequiredSection = true;

        // get business details 
        var data = null;
        if ($rootScope.transactionID > constant.ZERO)
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: filingTypeIDs.STATEMENTOFWITHDRAWAL } };
        else
            data = { params: { businessID: $rootScope.BusinessID, transactionID: $rootScope.transactionID, filingTypeID: filingTypeIDs.STATEMENTOFWITHDRAWAL } };
        if (angular.isNullorEmpty($rootScope.statementOfWithdrawalModal)) {
            if ($rootScope.BusinessID == undefined && $rootScope.transactionID == undefined) {
                $location.path('/StatementofWithdrawalIndex');
            }
            else {
                // StatementofWithdrawalCriteria method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.StatementofWithdrawalCriteria, data, function (response) {
                    $scope.modal = response.data;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || ResultStatus.INDIVIDUAL;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.BusinessFiling.EffectiveDate = wacorpService.dateFormatService($scope.modal.BusinessFiling.EffectiveDate);

                    $scope.modal.EffectiveDateType = angular.isNullorEmpty($scope.modal.EffectiveDateType) ? ResultStatus.DATEOFFILING : $scope.modal.EffectiveDateType;
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? codes.WASHINGTON : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;
                    $scope.modal.IsWithdrawalfromWAState = true;

                    $scope.modal.TypeOfWithdrawal = angular.isNullorEmpty($scope.modal.TypeOfWithdrawal) ? "Withdrawal from WA State" : $scope.modal.TypeOfWithdrawal;
                    $scope.modal.ConvertedEnityType = (angular.isNullorEmpty($scope.modal.ConvertedEnityType) || $scope.modal.ConvertedEnityType==0) ? "" : $scope.modal.ConvertedEnityType.toString();

                    if ($scope.modal.EmailAddress == null || $scope.modal.EmailAddress == "" || $scope.modal.EmailAddress == undefined)
                        $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;

                    var serviceAddress = {
                        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                            FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                        }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                        State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null,
                        PostalCode: null, County: null, CountyName: null
                    }
                    $scope.modal.ServiceAddress = $scope.modal.ServiceAddress ? angular.extend(serviceAddress, $scope.modal.ServiceAddress) : angular.copy(serviceAddress);
                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;

                    var canShowClearanceCertificate = $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNBANKLIMITEDLIABILITYCOMPANY || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYCOMPANY
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYPARTNERSHIP
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYCOMPANY
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYPARTNERSHIP
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDPARTNERSHIP;
                    $scope.isClearanceCertificateRequiredSection = !canShowClearanceCertificate;
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;

                    var isRequirments = $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNBANKCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNBANKLIMITEDLIABILITYCOMPANY
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNCREDITUNION || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNINSURANCECOMPANY || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDPARTNERSHIP
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYCOMPANY || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYLIMITEDPARTNERSHIP
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYPARTNERSHIP
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYCOMPANY
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNSAVINGSANDLOANASSOCIATION;
                    $scope.modal.IsRequirmentsFlag = isRequirments;

                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "" : $scope.modal.JurisdictionDesc;
                    $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
                    $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0 || $scope.modal.JurisdictionCountry == "") ? usaCode : $scope.modal.JurisdictionCountry.toString();
                    $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
                    $scope.modal.JurisdictionState = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0) ? null : $scope.modal.JurisdictionState.toString();

                    $scope.modal.NewJurisdictionDesc = angular.isNullorEmpty($scope.modal.NewJurisdictionDesc) ? "" : $scope.modal.NewJurisdictionDesc;
                    $scope.modal.NewJurisdiction = ($scope.modal.NewJurisdiction == null || $scope.modal.NewJurisdiction == "0") ? "" : $scope.modal.NewJurisdiction.toString();
                    $scope.modal.NewJurisdictionCountry = ($scope.modal.NewJurisdictionCountry == null || $scope.modal.NewJurisdictionCountry == 0 || $scope.modal.NewJurisdictionCountry == "") ? usaCode : $scope.modal.NewJurisdictionCountry.toString();
                    $scope.modal.NewJurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.NewJurisdictionCountry);
                    $scope.modal.NewJurisdictionState = ($scope.modal.NewJurisdictionState == null || $scope.modal.NewJurisdictionState == 0) ? null : $scope.modal.NewJurisdictionState.toString();
                    $scope.isShowReturnAddress =true;
                    $scope.isReturnAddMandatory();//to check Return address is mandatory

                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }

                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;

                    $scope.TypeOfWithdrawal(); // TypeOfWithdrawal method is available in this controller only.
                }, function (response) { });
            }
        }
        else {
                $scope.isShowReturnAddress =true;
            $scope.modal = $rootScope.statementOfWithdrawalModal;
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.BusinessFiling.EffectiveDate = "";

            $scope.modal.BusinessFiling.EffectiveDate = wacorpService.dateFormatService($scope.modal.BusinessFiling.EffectiveDate);

            var canShowClearanceCertificate = $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNBANKLIMITEDLIABILITYCOMPANY || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYCOMPANY
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYPARTNERSHIP
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYCOMPANY
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYPARTNERSHIP
                        || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDPARTNERSHIP;
            $scope.isClearanceCertificateRequiredSection = !canShowClearanceCertificate;

            var isRequirments = $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNBANKCORPORATION || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNBANKLIMITEDLIABILITYCOMPANY
                     || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNCREDITUNION || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNINSURANCECOMPANY
                     || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYCOMPANY || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYLIMITEDPARTNERSHIP
                     || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYPARTNERSHIP
                     || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYCOMPANY
                     || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNSAVINGSANDLOANASSOCIATION;

            $scope.modal.IsRequirmentsFlag = isRequirments;

            $scope.modal.TypeOfWithdrawal = angular.isNullorEmpty($scope.modal.TypeOfWithdrawal) ? "Withdrawal from WA State" : $scope.modal.TypeOfWithdrawal;
            $scope.modal.ConvertedEnityType = (angular.isNullorEmpty($scope.modal.ConvertedEnityType) || $scope.modal.ConvertedEnityType.toString() == "") ? "" : $scope.modal.ConvertedEnityType.toString();

            $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "" : $scope.modal.JurisdictionDesc;
            $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
            $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0 || $scope.modal.JurisdictionCountry == "") ? usaCode : $scope.modal.JurisdictionCountry.toString();
            $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.
            $scope.modal.JurisdictionState = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0) ? null : $scope.modal.JurisdictionState.toString();

            $scope.modal.NewJurisdictionDesc = angular.isNullorEmpty($scope.modal.NewJurisdictionDesc) ? "" : $scope.modal.NewJurisdictionDesc;
            $scope.modal.NewJurisdiction = ($scope.modal.NewJurisdiction == null || $scope.modal.NewJurisdiction == "0") ? "" : $scope.modal.NewJurisdiction.toString();
            $scope.modal.NewJurisdictionCountry = ($scope.modal.NewJurisdictionCountry == null || $scope.modal.NewJurisdictionCountry == 0 || $scope.modal.NewJurisdictionCountry == "") ? usaCode : $scope.modal.NewJurisdictionCountry.toString();
            $scope.modal.NewJurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.NewJurisdictionCountry); // selectedJurisdiction method is available in this controller only.
            $scope.modal.NewJurisdictionState = ($scope.modal.NewJurisdictionState == null || $scope.modal.NewJurisdictionState == 0) ? null : $scope.modal.NewJurisdictionState.toString();
            if ($scope.modal.EmailAddress == null || $scope.modal.EmailAddress == "" || $scope.modal.EmailAddress == undefined)
                $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
            
            $scope.isReturnAddMandatory();//to check Return address is mandatory

        }

        $scope.TypeOfWithdrawal(); // TypeOfWithdrawal method is available in this controller only.
    };


    $scope.isReturnAddMandatory = function () {
        if ($scope.modal.BusinessType != undefined && $scope.modal.BusinessType != null && $scope.modal.BusinessType != "") {
            if ($scope.modal.BusinessType == "FOREIGN NONPROFIT CORPORATION"
                || $scope.modal.BusinessType == "FOREIGN PROFIT CORPORATION"
                || $scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY COMPANY"
                || $scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY PARTNERSHIP"
                || $scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP"
                || $scope.modal.BusinessType == "FOREIGN MASSACHUSETTS TRUST"
                || $scope.modal.BusinessType == "FOREIGN PROFESSIONAL SERVICE CORPORATION"
                || $scope.modal.BusinessType == "FOREIGN PUBLIC UTILITY CORPORATION"
                || $scope.modal.BusinessType == "FOREIGN PROFESSIONAL LIMITED LIABILITY COMPANY"
                || $scope.modal.BusinessType == "FOREIGN COOPERATIVE ASSOCIATION"
                || $scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY COMPANY"
                || $scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                $scope.isMandatory = true;
            }
            else
                $scope.isMandatory = false;
        }
    };

    // continue for review
    $scope.ContinueSave = function (statementOfWithdrawalForm) {
        $scope.validateErrorMessage = true;
        $scope.isShowReturnAddress =true;

        var principalsValid = $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFITCORPORATION ? true : $scope.principalsCount("GoverningPerson") > 0;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isCleranceCertificateUploadValid = $scope.isClearanceCertificateRequiredSection ? $scope.modal.ClearanceCertificateList != null && $scope.modal.ClearanceCertificateList.length > constant.ZERO : true;
        var isCorrespondenceAddressValid = $scope[statementOfWithdrawalForm].CorrespondenceAddress.$valid;

        var isTypeOfWithdrawalValid = $scope[statementOfWithdrawalForm].TypeOfWithdrawalForm.$valid;

        if ($scope[statementOfWithdrawalForm].RequirementsForm.$valid && $scope[statementOfWithdrawalForm].AuthorizedPersonForm.$valid && isCorrespondenceAddressValid &&
            $scope[statementOfWithdrawalForm].AddressForServiceProcessForm.$valid && $scope[statementOfWithdrawalForm].CorrespondenceAddress.$valid &&
            $scope[statementOfWithdrawalForm].EffectiveDate.$valid && isCleranceCertificateUploadValid && isAdditionalUploadValid && isTypeOfWithdrawalValid) {
            $scope.validateErrorMessage = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.ServiceAddress.FullAddress = wacorpService.fullAddressService($scope.modal.ServiceAddress);

            var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.
            // here JurisdictionCountry = 261 is UnitedStates
            if ($scope.modal.JurisdictionCountry == 261) {
                var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.JurisdictionState); // selectedJurisdiction method is available in this controller only.
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionState);
                $scope.modal.JurisdictionDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionStateDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
                $scope.modal.NewJurisdictionDesc = angular.isNullorEmpty(stateDesc) ? angular.copy(countryDesc) : angular.copy(stateDesc);
            }
            else {
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionCountry);
                $scope.modal.JurisdictionDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionStateDesc = null;
            }

            var newCountryDesc = $scope.selectedJurisdiction($scope.NewCountriesList, $scope.modal.NewJurisdictionCountry); // selectedJurisdiction method is available in this controller only.
            // here JurisdictionCountry = 261 is UnitedStates
            if ($scope.modal.NewJurisdictionCountry == 261) {
                var newStateDesc = $scope.selectedJurisdiction($scope.NewStatesList, $scope.modal.NewJurisdictionState); // selectedJurisdiction method is available in this controller only.
                $scope.modal.NewJurisdiction = angular.copy($scope.modal.NewJurisdictionState);
                $scope.modal.NewJurisdictionDesc = angular.copy(newStateDesc);
                $scope.modal.NewJurisdictionStateDesc = angular.copy(newStateDesc);
                $scope.modal.NewJurisdictionCountryDesc = angular.copy(newCountryDesc);
                $scope.modal.NewJurisdictionDesc = angular.isNullorEmpty(newStateDesc) ? angular.copy(newCountryDesc) : angular.copy(newStateDesc);
            }
            else {
                $scope.modal.NewJurisdiction = angular.copy($scope.modal.NewJurisdictionCountry);
                $scope.modal.NewJurisdictionDesc = angular.copy(newCountryDesc);
                $scope.modal.NewJurisdictionCountryDesc = angular.copy(newCountryDesc);
                $scope.modal.NewJurisdictionStateDesc = null;
            }
             
            $scope.modal.ConvertedEnityTypeDesc = $scope.selectedJurisdiction($scope.businessTypes, $scope.modal.ConvertedEnityType); // selectedJurisdiction method is available in this controller only.

            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            

                if (($scope.modal.AgentEntity.EmailAddress == "" || $scope.modal.AgentEntity.EmailAddress == null || $scope.modal.AgentEntity.EmailAddress == undefined)) {
                    $scope.modal.IsEmailOptionChecked = false;
                }
            
            

            if ($scope.modal.EffectiveDateType == ResultStatus.DATEOFFILING)
                $scope.modal.BusinessFiling.EffectiveDate = new Date();
            $rootScope.statementOfWithdrawalModal = $rootScope.modal = $scope.modal;
            $location.path('/StatementofWithdrawalReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // back to business search
    $scope.back = function () {
        $location.path('/StatementofWithdrawalIndex');
    };

    // validate principals count
    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    $scope.businessTypes = function () {
        var config = { params: { name: 'TypeOfWithdrawalEntityType' } };
        // getLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.businessTypes = response.data; });
    };

    $scope.selectedJurisdiction = function (items, selectedVal) {
        var result = "";
        angular.forEach(items, function (item) {
            if (selectedVal == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }

    $scope.CountryChangeDesc = function () {
        $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.
    };

    $scope.NewCountryChangeDesc = function () {
        $scope.modal.NewJurisdictionCountryDesc = $scope.selectedJurisdiction($scope.NewCountriesList, $scope.modal.NewJurisdictionCountry); // selectedJurisdiction method is available in this controller only.
    };

    $scope.TypeOfWithdrawal = function () {
        if ($scope.modal.TypeOfWithdrawal == "Dissolution in Home Jurisdiction") {
            $scope.divDissolution = true;
            $scope.divConversion = false;
        }
        else if ($scope.modal.TypeOfWithdrawal == "Conversion in Home Jurisdiction") {
            $scope.divDissolution = false;
            $scope.divConversion = true;
        }
        else {
            $scope.divDissolution = false;
            $scope.divConversion = false;
        }
    }

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/StatementofWithdrawal';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // StatementOfWithDrawalSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.StatementOfWithDrawalSaveAsDraft, $scope.modelDraft, function (response) {

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }


    $scope.CopyAddressOfServiceFromCorrespondence = function () {
        if ($scope.modal.CorrespondenceAddress.IsAddressSame) {
            $scope.modal.CorrespondenceAddress.StreetAddress1 = angular.copy($scope.modal.ServiceAddress.StreetAddress1);
            $scope.modal.CorrespondenceAddress.StreetAddress2 = angular.copy($scope.modal.ServiceAddress.StreetAddress2);
            $scope.modal.CorrespondenceAddress.City = angular.copy($scope.modal.ServiceAddress.City);
            $scope.modal.CorrespondenceAddress.Country = angular.copy($scope.modal.ServiceAddress.Country);
            $scope.modal.CorrespondenceAddress.State = angular.copy($scope.modal.ServiceAddress.State);
            $scope.modal.CorrespondenceAddress.Zip5 = angular.copy($scope.modal.ServiceAddress.Zip5);
            $scope.modal.CorrespondenceAddress.Zip4 = angular.copy($scope.modal.ServiceAddress.Zip4);
            $scope.modal.CorrespondenceAddress.PostalCode = angular.copy($scope.modal.ServiceAddress.PostalCode);
            $scope.modal.CorrespondenceAddress.OtherState = angular.copy($scope.modal.ServiceAddress.OtherState);
        }
        else {
            $scope.modal.CorrespondenceAddress.StreetAddress1 = '';
            $scope.modal.CorrespondenceAddress.StreetAddress2 = '';
            $scope.modal.CorrespondenceAddress.City = '';
            $scope.modal.CorrespondenceAddress.Country = codes.USA;
            $scope.modal.CorrespondenceAddress.State = codes.WA;
            $scope.modal.CorrespondenceAddress.Zip5 = '';
            $scope.modal.CorrespondenceAddress.Zip4 = '';
            $scope.modal.CorrespondenceAddress.PostalCode = '';
            $scope.modal.CorrespondenceAddress.OtherState = '';
            $scope.modal.CorrespondenceAddress.IsAddressSame = false;
        }
    };

    $scope.ServiceAddress = function () {
        if ($scope.modal.CorrespondenceAddress) {
            if ($scope.modal.CorrespondenceAddress.IsAddressSame)
                $scope.modal.CorrespondenceAddress.IsAddressSame = false;
        }
    };

    var stwithDrawalSericeAddress = $rootScope.$on("InvokeServiceAddress", function () {
        //$scope.address.IsACPChecked =true;
        $scope.ServiceAddress(); // ServiceAddress method is available in this controller only.
    });

    $scope.$on('$destroy', function () {

        stwithDrawalSericeAddress(); // stwithDrawalSericeAddress method is available in this controller only.
    });
});

wacorpApp.controller('statementOfWithdrawalIndexController', function ($scope, $location, $rootScope, wacorpService) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        
        var statementofWithdrawalTypes = new Array(14, 40, 17, 19, 92);//This is the list of IDs that statement of withdrawal is not included 

        var voluntaryTerminationTypes = new Array(67, 68, 69, 75, 76, 77);//allowed voluntary termination only for this businesstypes

        var certificateOfDissolutionTypes = new Array(65,79);//allowed certificate of dissolution only for this businesstypes

        var articlesOfDissolutionTypes = new Array(58, 72, 71, 73, 74, 59, 61, 90, 87, 88, 86, 85);//allowed articles of dissolution only for this businesstypes

        if ($scope.selectedBusiness.BusinessCategoryID == 5)//Statement of withdrawal is only for foreign entities
        {
            //angular.forEach(statementofWithdrawalTypes, function (key, data) {
                
                //if ($scope.selectedBusiness.BusinessTypeID != key) {
                if (statementofWithdrawalTypes.indexOf($scope.selectedBusiness.BusinessTypeID) == -1) {
                //if (statementofWithdrawalType.contains($scope.selectedBusiness.BusinessTypeID)) {
                    
                    if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT, ResultStatus.Terminated].indexOf($scope.selectedBusiness.BusinessStatus) >= constant.ZERO) {
                        $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                        $rootScope.statementOfWithdrawalModal = null;
                        $rootScope.transactionID = null;
                        $location.path('/StatementofWithdrawal');
                    }
                    else {
                        // Folder Name: app Folder
                        // Alert Name: statementofWithdrawalAllowed method is available in alertMessages.js 
                        wacorpService.alertDialog(messages.statementofWithdrawalAllowed);
                        //wacorpService.alertDialog(messages.selectedBusiness.replace('{0}', $scope.selectedBusiness.BusinessStatus));
                    }
                }
            //});
        }
        //Voluntary termination,certificate of dissolution,articles of dissolution allowed only for Domestic entity type  and for below business types
        if($scope.selectedBusiness.BusinessCategoryID == 3)
        {
            
            if (voluntaryTerminationTypes.indexOf($scope.selectedBusiness.BusinessTypeID) > -1) {
                
                if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT, ResultStatus.AdministrativelyDissolved].indexOf($scope.selectedBusiness.BusinessStatus) >= constant.ZERO) {
                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                    $rootScope.voluntaryTerminationModal = null;
                    $rootScope.transactionID = null;
                    $location.path('/VoluntaryTermination');
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: voluntaryTerminationAllowed method is available in alertMessages.js 
                    wacorpService.alertDialog(messages.voluntaryTerminationAllowed);
                }

            }
            else if (certificateOfDissolutionTypes.indexOf($scope.selectedBusiness.BusinessTypeID) > -1)
            {
                
                if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT, ResultStatus.AdministrativelyDissolved].indexOf($scope.selectedBusiness.BusinessStatus) >= constant.ZERO) {
                    
                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                    $rootScope.certificateOfDissolutionModel = null;
                    $rootScope.transactionID = null;
                    $location.path('/CertificateOfDissolution');
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: certificateOfDissolutionAllowed method is available in alertMessages.js 
                    wacorpService.alertDialog(messages.certificateOfDissolutionAllowed);
                }
            }
            else if (articlesOfDissolutionTypes.indexOf($scope.selectedBusiness.BusinessTypeID) > -1)
            {
                
                if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT, ResultStatus.AdministrativelyDissolved].indexOf($scope.selectedBusiness.BusinessStatus) >= constant.ZERO) {
                    
                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                    $rootScope.articlesOfDissolutionModel = null;
                    $rootScope.transactionID = null;
                    $location.path('/ArticlesOfDissolution');
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: articlesOfDissolutionAllowed method is available in alertMessages.js 
                    wacorpService.alertDialog(messages.articlesOfDissolutionAllowed);
                }
            }
            else
            {
                // Folder Name: app Folder
                // Alert Name: ValidDissolutionFilings method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.ValidDissolutionFilings);
            }
        }      
    }
});



wacorpApp.controller('statementOfWithdrawalReviewController', function ($scope, $location, $rootScope, wacorpService) {
    //scope load
    $scope.Init = function () {
        if (angular.isNullorEmpty($rootScope.statementOfWithdrawalModal))
            $location.path('/StatementofWithdrawalIndex');
        else
            $scope.modal = $rootScope.statementOfWithdrawalModal;

        var canShowClearanceCertificate = $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNBANKLIMITEDLIABILITYCOMPANY || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYCOMPANY
                       || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDLIABILITYPARTNERSHIP
                       || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYCOMPANY
                       || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYLIMITEDPARTNERSHIP || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDLIABILITYPARTNERSHIP
                       || $scope.modal.BusinessTypeID == businessTypeIDs.FOREIGNPROFESSIONALLIMITEDPARTNERSHIP;
        $scope.isClearanceCertificateRequiredSection = !canShowClearanceCertificate;
        $scope.TypeOfWithdrawal();// TypeOfWithdrawal method is available in this controller only.
    }
    // add filing to cart
    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // SOWAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.SOWAddToCart, $scope.modal, function (response) {
            $rootScope.statementOfWithdrawalModal = null;
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $location.path('/shoppingCart');
           
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    // back to Statement of Withdrawal flow
    $scope.back = function () {
        $rootScope.statementOfWithdrawalModal = $scope.modal;
        $location.path('/StatementofWithdrawal');
    };

    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        // SOWAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.SOWAddToCart, $scope.modal, function (response) {
            $rootScope.statementOfWithdrawalModal = null;
            $rootScope.transactionID = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
                $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.TypeOfWithdrawal = function () {
        if ($scope.modal.TypeOfWithdrawal == "Dissolution in Home Jurisdiction") {
            $scope.divDissolution = true;
            $scope.divConversion = false;
        }
        else if ($scope.modal.TypeOfWithdrawal == "Conversion in Home Jurisdiction") {
            $scope.divDissolution = false;
            $scope.divConversion = true;
        }
        else {
            $scope.divDissolution = false;
            $scope.divConversion = false;
        }
    }
});

wacorpApp.controller('voluntaryTerminationController', function ($scope, $location, $rootScope, wacorpService) {
    // scope variables
    $scope.messages = messages;
    $scope.modal = {};

    // page load
    $scope.Init = function () {
        $scope.validateErrorMessage = false;
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.voluntaryTerminationModal = $rootScope.modal;
            //$rootScope.modal = null;
        }
        // get business details 
        var data = null;
        if ($rootScope.transactionID > constant.ZERO)
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: filingTypeIDs.VOLUNTARYTERMINATION } };
        else
            data = { params: { businessID: $rootScope.BusinessID, transactionID: $rootScope.transactionID, filingTypeID: filingTypeIDs.VOLUNTARYTERMINATION } };
        if (angular.isNullorEmpty($rootScope.voluntaryTerminationModal)) {
            if ($rootScope.BusinessID == undefined && $rootScope.transactionID == undefined) {
                $location.path('/StatementofWithdrawalIndex');
            }
            else {
                // VoluntaryTerminationCriteria method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.VoluntaryTerminationCriteria, data, function (response) {
                    $scope.modal = response.data;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || ResultStatus.INDIVIDUAL;
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.DissolutionApprovalDate = wacorpService.dateFormatService($scope.modal.DissolutionApprovalDate);
                    $scope.modal.BusinessFiling.EffectiveDate = wacorpService.dateFormatService($scope.modal.BusinessFiling.EffectiveDate);
                    $scope.modal.EffectiveDateType = angular.isNullorEmpty($scope.modal.EffectiveDateType) ? ResultStatus.DATEOFFILING : $scope.modal.EffectiveDateType;
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? codes.WASHINGTON : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    $scope.modal.IsArticalsExist = angular.isNullorEmpty($scope.modal.IsArticalsExist) ? true : $scope.modal.IsArticalsExist;
                    $scope.modal.IsDissolutionAttestedChecked = angular.isNullorEmpty($scope.modal.IsDissolutionAttestedChecked) ? true : $scope.modal.IsDissolutionAttestedChecked;
                    $scope.modal.DissolutionCheckType = $scope.modal.DissolutionCheckType == constant.ZERO ? constant.ONE : $scope.modal.DissolutionCheckType;
                    if ($scope.modal.EmailAddress == null || $scope.modal.EmailAddress == "" || $scope.modal.EmailAddress == undefined)
                        $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;

                    var correspondenseAddress = {
                        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                            FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null
                        }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                        State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null,
                        PostalCode: null, County: null, CountyName: null
                    }
                    $scope.modal.CorrespondenceAddress = $scope.modal.CorrespondenceAddress ? angular.extend(correspondenseAddress, $scope.modal.CorrespondenceAddress) : angular.copy(correspondenseAddress);
                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.isShowReturnAddress = true;

                }, function (response) { });
            }
        }
        else {
            $scope.modal = $rootScope.voluntaryTerminationModal;
            if ($scope.modal.EffectiveDateType == 'DateOfFiling') {
                $scope.modal.BusinessFiling.EffectiveDate = "";
            }
            if ($scope.modal.EmailAddress == null || $scope.modal.EmailAddress == "" || $scope.modal.EmailAddress == undefined)
                $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;

            $scope.modal.BusinessFiling.EffectiveDate = wacorpService.dateFormatService($scope.modal.BusinessFiling.EffectiveDate);
            $scope.isShowReturnAddress = true;
        }
    };

    // continue for review
    $scope.ContinueSave = function (VoluntaryTerminationForm) {
        $scope.validateErrorMessage = true;

        var isEffectiveDateValid = $scope[VoluntaryTerminationForm].EffectiveDate.$valid;

        //var isDissolutionApprovalDateValid = $scope[VoluntaryTerminationForm].DissolutionApprovalForm.$valid;

        var isCleranceCertificateUploadValid = $scope.modal.IsArticalsExist ? ($scope.modal.IsArticalsExist && $scope.modal.ClearanceCertificateList != null && $scope.modal.ClearanceCertificateList.length > constant.ZERO) : true;

        //var isDissolutionAttensationChecked = $scope[VoluntaryTerminationForm].DissolutionAttestationsForm.$valid;

        //var isCorrespondenceAddressValid = $scope[VoluntaryTerminationForm].CorrespondenceAddress.$valid;

        //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
        if (($scope.modal.AgentEntity.EmailAddress == "" || $scope.modal.AgentEntity.EmailAddress == null || $scope.modal.AgentEntity.EmailAddress == undefined)) {
	        // $rootScope.$broadcast('onEmailEmpty');
	        $scope.modal.IsEmailOptionChecked = false;
        }
        var isAuthorizedPersonValid = $scope[VoluntaryTerminationForm].AuthorizedPersonForm.$valid;
        var isCorrespondenceAddressValid = $scope[VoluntaryTerminationForm].CorrespondenceAddress.$valid;
        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        //&& isDissolutionApprovalDateValid && isDissolutionAttensationChecked  && isCorrespondenceAddressValid
        if (isEffectiveDateValid 
            && isCleranceCertificateUploadValid 
            && isAuthorizedPersonValid && isAdditionalUploadValid &&isCorrespondenceAddressValid) {
            $scope.validateErrorMessage = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.CorrespondenceAddress.FullAddress = wacorpService.fullAddressService($scope.modal.CorrespondenceAddress);
            $scope.modal.BusinessFiling.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.BusinessFiling.EffectiveDate;
            $rootScope.voluntaryTerminationModal = $scope.modal;
            $location.path('/VoluntaryTerminationReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // back to business search
    $scope.back = function () {
        $location.path('/StatementofWithdrawalIndex');
    };
    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/VoluntaryTermination';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // VoluntaryTerminationSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.VoluntaryTerminationSaveAsDraft, $scope.modelDraft, function (response) {
            
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }
});

wacorpApp.controller('voluntaryTerminationIndexController', function ($scope, $location, $rootScope, wacorpService) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.BusinessStatus) >= constant.ZERO) {
            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
            $rootScope.voluntaryTerminationModal = null;
            $rootScope.transactionID = null;
            $location.path('/VoluntaryTermination');
        }
        else {
            // Folder Name: app Folder
            // Alert Name: selectedBusiness method is available in alertMessages.js 
            wacorpService.alertDialog(messages.selectedBusiness.replace('{0}', $scope.selectedBusiness.BusinessStatus));
        }
    }
});



wacorpApp.controller('voluntaryTerminationReviewController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, ScopesData, focus) {
    //scope load
    $scope.Init = function () {
        if (angular.isNullorEmpty($rootScope.voluntaryTerminationModal))
            $location.path('/VoluntaryTerminationIndex');
        else
            $scope.modal = $rootScope.voluntaryTerminationModal;
    }
    // add filing to cart
    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // VoluntaryTerminationAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.VoluntaryTerminationAddToCart, $scope.modal, function (response) {
            $rootScope.voluntaryTerminationModal = null;
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $location.path('/shoppingCart');
            
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    // back to Statement of Withdrawal flow
    $scope.back = function () {
        $rootScope.voluntaryTerminationModal = $scope.modal;
        $location.path('/VoluntaryTermination');
    };

    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        // VoluntaryTerminationAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.VoluntaryTerminationAddToCart, $scope.modal, function (response) {
            $rootScope.voluntaryTerminationModal = null;
            $rootScope.transactionID = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
                $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('businessAmendmentIndexController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {
    /* ------------Business Search Functionality--------------- */
    $scope.selectedBusiness = null;
    $scope.messages = messages;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        // Here BusinessCategoryID = 3 Domestic Business Type.
        if ($scope.selectedBusiness.BusinessCategoryID == 3) {//If This is Domestic Navigate to Business Amendment
            //OSOS ID--2682--Online Reinstatements > Users are able to change their entity name and submit a Reinstatement
            //OSOS ID--2851 Business Amendments - available for any entity status
            if (["Active", "Delinquent", "Administratively Dissolved"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
                $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                $rootScope.annualReportModal = null;
                $rootScope.transactionID = null;
                $location.path('/BusinessAmendment/' + $scope.selectedBusiness.BusinessID);
            }
            else {
                // Folder Name: app Folder
                // Alert Name: AmendmentNotAllowStatus method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.AmendmentNotAllowStatus);
            }
        }
        // Here BusinessCategoryID = 5 Foreign Business Type.
        if ($scope.selectedBusiness.BusinessCategoryID == 5) {//If This is Foreign Navigate to  Amendment of Foreign Registration Statement
            //OSOS ID--2851 Business Amendments - available for any entity status
            if (["Active", "Delinquent"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
                $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                $rootScope.annualReportModal = null;
                $rootScope.transactionID = null;
                $location.path('/AmendmentofForiegnRegistrationStatement/' + $scope.selectedBusiness.BusinessID);
            }
            else {
                // Folder Name: app Folder
                // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.AmendmentOfForiegnRegistrationStmt.ActiveAndDelinquentStatus);
            }
        }
    }
});




wacorpApp.controller('businessAmendmentReviewController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService,$http) {
    $scope.NaicsCodes = [];
    $scope.businessLayout = "/ng-app/view/partial/_businessAmendmentReview.html";
    //scope load
    $scope.Init = function () {
        if (!angular.isNullorEmpty($rootScope.modal)) {
            $scope.modal = $rootScope.modal;
            $scope.modal.oldAmendmentEntity = $scope.modal.oldAmendmentEntity;
            $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;
            $scope.modal.PrincipalOffice.PhoneNumber = $scope.modal.PrincipalOffice.PhoneNumber;
            getNaicsCodes();// method is available in this controller only.
            $scope.ExpireDate = (wacorpService.dateFormatService($scope.modal.DurationExpireDate) == '01/01/1970'
                                  || wacorpService.dateFormatService($scope.modal.DurationExpireDate) == null)
                                  ? 'Perpetual' : $scope.modal.DurationExpireDate;
            $scope.IsAmendEntityTypeShow = true;
        }
        else
            $scope.navBusinessAmendment();
    }

    // add Amendment filing to cart 
    $scope.AddToCart = function () {

        $scope.modal.NewBusinessName = $scope.modal.BusinessName;
        $scope.modal.BusinessName = $scope.modal.oldAmendmentEntity.BusinessName;
        $scope.modal.OldBusinessName = $scope.modal.oldAmendmentEntity.BusinessName;

        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        // AmendmentofDomestic method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AmendmentofDomestic, $scope.modal, function (response) {
            $rootScope.modal = null;

            $rootScope.transactionID = null;
            $location.path('/shoppingCart');
           
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

   // back to Amendment flow
    $scope.back = function () {
        
        //$rootScope.annualReportModal = $scope.modal;
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $rootScope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $location.path('/BusinessAmendment/' + $scope.modal.BusinessID);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
             return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    $scope.currentdate = function () {
        return new Date();
    }

    // get selected NAICS Codes
    function getNaicsCodes() {
        var naicDesc = "";
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        naicDesc += (naicDesc == "" ? response.data[i].Value : (", " + response.data[i].Value));
                        break;
                    }
                }
            });
            $scope.modal.NatureOfBusiness.NAICSCodeDesc = naicDesc;
        });
    }
    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        // AmendmentofDomestic is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AmendmentofDomestic, $scope.modal, function (response) {
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
            $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});


wacorpApp.controller('businessAmendmentController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {
    // scope variable
    $scope.modal = {};
    $scope.NaicsCodes = [];
    $scope.JurisdictionList = [];
    $scope.validateErrorMessage = false;
    $scope.principalsCount = 0;
    $scope.amendprincipalsCount = 0;
    $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = null;
    $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = null;
    $scope.businessLayout = "/ng-app/view/partial/_businessAmendment.html";
    $scope.IsAmendEntityTypeShow = false;
    $scope.isIncorporatorEntityName = false;
    $scope.isGeneralPartnerEntityName = false;
    $scope.currentbusinesstypeid = 0;

    // scope load 
    $scope.Init = function () {
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $scope.modal = $rootScope.modal;
        }
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
        });

        var data = { params: { name: 'Jurisdiction' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, data, function (response) { $scope.JurisdictionList = response.data; }, function (response) { });

        // get business details
        var data = null;
        if ($rootScope.transactionID > 0)
            // Here filingTypeID : 10 is AMENDED CERTIFICATE OF LIMITED LIABILITY LIMITED PARTNERSHIP.
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 10 } };
        else
            data = { params: { businessID: $routeParams.id, transactionID: $rootScope.transactionID, filingTypeID: 10 } };
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            // AmendmentOfDomesticCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.AmendmentOfDomesticCriteria, data, function (response) {
                $scope.modal = response.data;
                $scope.currentBusiness = angular.copy(response.data);
                calcDuration(); // calcDuration method is available in this controller only

                if ($scope.modal.DurationYears > 0) {
                    $scope.modal.DurationExpireDate = "";
                }

                if ($scope.modal.BusinessTypeID == businessTypeIDs.WAPROFITCORPORATION) {


                }
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.PeriodofDurationDate = (wacorpService.dateFormatService($scope.modal.PeriodofDurationDate) != null || wacorpService.dateFormatService($scope.modal.PeriodofDurationDate) == "") ? $scope.modal.PeriodofDurationDate : $scope.modal.DurationExpireDate;
                $scope.getEntityTypes($scope.currentBusiness.BusinessType);
                $scope.currentbusinesstypeid = $scope.modal.BusinessTypeID;
                $scope.modal.OldBusinessTypeID = $scope.currentbusinesstypeid;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                $scope.modal.EffectiveDateType = $scope.modal.EffectiveDate == null ? 'DateOfFiling' : $scope.modal.EffectiveDateType;
                $scope.modal.DateOfAdoption = wacorpService.dateFormatService($scope.modal.DateOfAdoption);
                $scope.modal.DateOfAdoptionType = angular.isNullorEmpty($scope.modal.DateOfAdoptionType) ? ResultStatus.DATEOFADOPTIONFILING : $scope.modal.DateOfAdoptionType;
                $scope.modal.BusinessFiling.DateOfAdoption = wacorpService.dateFormatService($scope.modal.BusinessFiling.DateOfAdoption);
                $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = wacorpService.dateFormatService($scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit);
                $scope.modal.DateOfIncorporation = wacorpService.dateFormatService($scope.modal.DateOfIncorporation);
                $scope.modal.NameReservedId = ($scope.modal.NameReservedId == 0 ? null : $scope.modal.NameReservedId);
                $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
                $scope.modal.DateOfFormationInHomeJurisdiction = wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);
                $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertStringToObject($scope.modal.NatureOfBusiness.NAICSCode);
                $scope.modal.NatureOfBusiness.IsOtherNAICS = !angular.isNullorEmpty($scope.modal.NatureOfBusiness.OtherDescription) ? true : false;
                $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                $scope.modal.CorporateShares = $scope.modal.CorporateShares == 0 ? "" : $scope.modal.CorporateShares;
                $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;
                $scope.modal.PrincipalOffice.PhoneNumber = $scope.modal.PrincipalOffice.PhoneNumber;
                $scope.modal.IsAmendmentEntityType = angular.isNullorEmpty($scope.modal.IsAmendmentEntityType) ? false : $scope.modal.IsAmendmentEntityType; //Is Entity Type Radio button
                $scope.modal.IsAmendmentDurationChange = angular.isNullorEmpty($scope.modal.IsAmendmentDurationChange) ? false : $scope.modal.IsAmendmentDurationChange; //Is Entity Type Radio button
                $scope.modal.IsAmendmentCorpSharesChange = angular.isNullorEmpty($scope.modal.IsAmendmentCorpSharesChange) ? false : $scope.modal.IsAmendmentCorpSharesChange; //Is Entity Type Radio button
                //$scope.modal.BINAICSCodeDesc=!angular.isNullorEmpty($scope.modal.BINAICSCodeDesc)?$scope.modal.BINAICSCodeDesc.replace(/&amp;/g, '&'):"";
                //$scope.modal.BINAICSCodeDesc = !angular.isNullorEmpty($scope.modal.BIOtherDescription)?$scope.modal.BINAICSCodeDesc+','+$scope.modal.BIOtherDescription:$scope.modal.BINAICSCodeDesc;
                $scope.amendmentEntityType = {
                    Key: angular.isNullorEmpty($scope.modal.AmendedBusinessType) ? "" : $scope.modal.AmendedBusinessType,
                    Value: angular.isNullorEmpty($scope.modal.AmendedBusinessTypeDesc) ? "" : $scope.modal.AmendedBusinessTypeDesc
                }

                $scope.modal.AdoptionofArticlesofAmendment = !angular.isNullorEmpty($scope.modal.AdoptionofArticlesofAmendment) ? $scope.modal.AdoptionofArticlesofAmendment : 'B';
                $scope.modal.AdoptionofArticlesofAmendmentNonProfit = !angular.isNullorEmpty($scope.modal.AdoptionofArticlesofAmendmentNonProfit) ? $scope.modal.AdoptionofArticlesofAmendmentNonProfit : 'M';
                $scope.$watch(function () {
                    $scope.isRequired = ($scope.modal.IsCorporateSharesCommonStock || $scope.modal.IsCorporateSharesPreferedStock) ? false : true;
                });
                $scope.ExpireDate = (wacorpService.dateFormatService($scope.modal.DurationExpireDate) == '01/01/1970'
                                    || wacorpService.dateFormatService($scope.modal.DurationExpireDate) == null)
                                    ? 'PERPETUAL' : $scope.modal.DurationExpireDate;
                $scope.DateofAdoptionOfArticlesOfAmendmentNonProfit();
                $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;

                $scope.modal.NewBusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
                $scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
                $scope.modal.OldBusinessName = !angular.isNullorEmpty($scope.modal.OldBusinessName) ? $scope.modal.OldBusinessName : $scope.modal.BusinessName;
                if ($scope.modal.IsActiveFilingExist) {
                    //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }
                $scope.isShowReturnAddress = true;
                $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                // Copy old Entity Data
                if (!$scope.modal.oldAmendmentEntity) {
                    $scope.modal.oldAmendmentEntity = {};
                    angular.copy($scope.modal, $scope.modal.oldAmendmentEntity);
                }

            }, function (response) { });
        }
        else {

            $scope.modal = $rootScope.modal;
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = "";
            if ($scope.modal.DateOfAdoptionType == 'DateOfAdoptionFiling')
                $scope.modal.BusinessFiling.DateOfAdoption = "";
            calcDuration(); // calcDuration method is available in this controller only.
            if ($scope.modal.DurationYears > 0) {
                $scope.modal.DurationExpireDate = "";
            }
            $scope.ExpireDate = (wacorpService.dateFormatService($scope.modal.DurationExpireDate) == '01/01/1970'
                                    || wacorpService.dateFormatService($scope.modal.DurationExpireDate) == null)
                                    ? 'PERPETUAL' : wacorpService.dateFormatService($scope.modal.DurationExpireDate);
            //$scope.currentBusiness = $rootScope.currentBusiness;
            //$scope.getEntityTypes($rootScope.currentBusiness.BusinessType);

            $scope.modal.PeriodofDurationDate = wacorpService.dateFormatService($scope.modal.PeriodofDurationDate);
            if (typeof $rootScope.currentBusiness == typeof undefined) {
                $rootScope.currentBusiness = angular.copy($scope.modal);
                $scope.currentBusiness = angular.copy($scope.modal);
            }

            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            $scope.modal.BusinessFiling.DateOfAdoption = wacorpService.dateFormatService($scope.modal.BusinessFiling.DateOfAdoption);
            $scope.modal.DurationExpireDate = wacorpService.dateFormatService($scope.modal.DurationExpireDate);

            $scope.getEntityTypes($rootScope.currentBusiness.BusinessType);
            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode.split(',');
            }

            //$scope.modal.NewBusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
            //$scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
            $scope.modal.OldBusinessName = !angular.isNullorEmpty($scope.modal.OldBusinessName) ? $scope.modal.OldBusinessName : $scope.modal.BusinessName;

            // Copy old Entity Data
            if (!$scope.modal.oldAmendmentEntity) {
                $scope.modal.oldAmendmentEntity = {};
                angular.copy($scope.modal, $scope.modal.oldAmendmentEntity);// Copy old Entity Data
            }

            $scope.amendmentEntityType = {
                Key: angular.isNullorEmpty($scope.modal.AmendedBusinessType) ? "" : $scope.modal.AmendedBusinessType,
                Value: angular.isNullorEmpty($scope.modal.AmendedBusinessTypeDesc) ? "" : $scope.modal.AmendedBusinessTypeDesc
            }
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = $scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'M' ? $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit : "";
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = $scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'B' ? $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit : "";
            $scope.isShowReturnAddress = true;
        }

    };

    // back to Business Amendment business search
    $scope.back = function () {
        $location.path('/BusinessAmendmentIndex');
    };

    $scope.changeEntityType = function () {

        var businesstypeid = angular.isNullorEmpty($scope.amendmentEntityType) ? $scope.modal.oldAmendmentEntity.BusinessTypeID : $scope.amendmentEntityType.Key;
        // var businesstype = angular.isNullorEmpty($scope.amendmentEntityType) ? $scope.currentBusiness.BusinessType : $scope.amendmentEntityType.Value;
        var data = { params: { businessTypeid: businesstypeid } };
        //var data = { params: {businessTypeid: $scope.amendmentEntityType.Key, businessType: $scope.amendmentEntityType.Value } };
        // reloadwithNewBusinessType method is available in constants.js
        wacorpService.get(webservices.OnlineFiling.reloadwithNewBusinessType, data, function (response) {
            $scope.modal.Indicator = response.data.Indicator;
            $scope.modal.FilingType = response.data.FilingType;
            //$scope.modal.BusinessType = businesstype;
            $scope.modal.BusinessTypeID = businesstypeid;
            $scope.modal.BusinessTransaction.BusinessTypeID = businesstypeid;

            if (businesstypeid != 0) {
                $scope.modal.IsAmendmentEntityNameChange = true;
                // Check indicators Validation
                $scope.modal.isValidIndicator();
            }
        },
        function (error) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });

    }

    //OSOS--ID- 3163
    $scope.checkClassOfShares = function () {
        $scope.IsCorporateSharesCommonStockValidate = ($scope.modal.IsCorporateSharesCommonStock || $scope.modal.IsCorporateSharesPreferedStock) ? false : true;
    };

    // validate & continue Amendment for review
    $scope.Review = function (amendmentBusinessForm) {
        $scope.showEntityErrorMessage = true;
        $scope.validateErrorMessage = true;
        $scope.IsCorporateSharesCommonStockValidate = false;
        $scope.validateAgentErrors = $scope.modal.Agent.IsNewAgent ? true : ($scope.modal.Agent.IsAgentEdit ? true : false);
        $scope.validateOneAgent = $scope.modal.Agent.AgentID == 0 && !$scope.modal.Agent.IsNewAgent;
        if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'M') {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM;
        }
        else if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'B') {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB;
        }
        else {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = null;
        }

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[amendmentBusinessForm]);

        //Entity Name
        var businessNameCount = $scope.availableBusinessCount();
        var isBusinessNameExists = ($scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable))
         || $scope.modal.IsNameReserved;

        //var isBusinessNameExists = (($scope.modal.isBusinessNameAvailable == null || $scope.modal.isBusinessNameAvailable == undefined || $scope.modal.isBusinessNameAvailable == "") ? true : $scope.modal.isBusinessNameAvailable)
        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);


        var isEntityValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EntityName, $scope.modal, $scope.modal.BusinessTypeID) ||
                             ($scope[amendmentBusinessForm].NewEntityName.$valid
                             && businessNameValid
                             && ((!$scope.modal.IsNameReserved
                            //&& $scope.modal.isBusinessNameAvailable == ""
                             && wacorpService.isIndicatorValid($scope.modal))
                            || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != "")))
                              );

        if (!wacorpService.isIndicatorValid($scope.modal)) {
            $rootScope.$broadcast("checkIndicator");
        }

        var isJurisdictionFormValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Jurisdiction, $scope.modal, $scope.modal.BusinessTypeID) ||
                                            $scope[amendmentBusinessForm].JurisdictionForm.$valid);

        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID)
                                       || $scope[amendmentBusinessForm].EffectiveDate.$valid);

        var isDateOfAdoptionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DateOfAdoption, $scope.modal, $scope.modal.BusinessTypeID)
                                     || $scope[amendmentBusinessForm].DateOfAdoption.$valid);

        // registered agent

        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
                   ((!$scope.modal.Agent.IsNewAgent ? ($scope.modal.Agent.AgentID != 0 && $scope.modal.Agent.StreetAddress.FullAddress) ? true : (false && !$scope.modal.Agent.IsNoncommercialStreetAddress) : true) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 : true) && $scope[amendmentBusinessForm].RegisteredAgentForm.$valid));

        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;
        $scope.modal.Agent.IsAmendmentAgentInfoChange = !isRegisteredAgentValidStates || $scope.modal.Agent.IsAmendmentAgentInfoChange ? true : false;

        $scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        $scope.checkRAStreetAddress = wacorpService.isRAStreetAddressValid($scope.modal.Agent.StreetAddress); //to check RA street address is valid or not 

        $scope.validateNonCommercialStreetAddress = !isRegisteredAgentValid && !$scope.modal.Agent.IsNoncommercialStreetAddress && !$scope.checkRAStreetAddress ? true : false;

        //Governing Person 
        //var isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                 $scope.amendprincipalsCount("GOVERNINGPERSON") > 0);

        //Duration
        var isDurationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Duration, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[amendmentBusinessForm].DurationForm.$valid);
        var isCorporateSharesValid = true;
        if ($scope.ScreenPart($scope.modal.AllScreenParts.CorporateShares_NewFormation, $scope.modal, $scope.modal.BusinessTypeID)) {
            var isCorporateSharesValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.CorporateShares_NewFormation, $scope.modal, $scope.modal.BusinessTypeID)
               || $scope.modal.CorporateShares > 0 && $scope[amendmentBusinessForm].CorporateShares.$valid) && ($scope.modal.IsCorporateSharesCommonStock || $scope.modal.IsCorporateSharesPreferedStock) ? true : false;

            $scope.IsCorporateSharesCommonStockValidate = ($scope.modal.IsCorporateSharesCommonStock || $scope.modal.IsCorporateSharesPreferedStock) ? false : true;
        }
        // PurposeAndPowers
        var isPurposeAndPowersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PurposeAndPowers, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        ($scope[amendmentBusinessForm].PurposeAndPowers.$valid));

        var isPurposeOfCorporationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PurposeOfCorporation, $scope.modal, $scope.modal.BusinessTypeID)
                                       || $scope[amendmentBusinessForm].PurposeOfCorporationForm.$valid);

        var isAttestationofSocialPurposeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AttestationOfSocialPurpose, $scope.modal, $scope.modal.BusinessTypeID)
                                               || $scope[amendmentBusinessForm].AttestationofSocialPurposeForm.$valid);

        var isAdoptionOfArticlesOfAmendmentNonProfitValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AdoptionOfArticlesOfAmendment_NonProfit, $scope.modal, $scope.modal.BusinessTypeID)
                                       || $scope[amendmentBusinessForm].AdoptionOfArticlesOfAmendmentNonProfitForm.$valid);

        //var isOtherProvisionsValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.OtherProvisions, $scope.modal, $scope.modal.BusinessTypeID)
        //                               || $scope[amendmentBusinessForm].OtherProvisionsForm.$valid);

        //var isIncorporatorValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Incorporator, $scope.modal, $scope.modal.BusinessTypeID)
        //                             || $scope.principalsCount("Incorporator") > 0);

        //var isAttestationOfStatedProfessionValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AttestationOfStatedProfession, $scope.modal, $scope.modal.BusinessTypeID)
        //                              || $scope[amendmentBusinessForm].AttestationOfStatedProfessionForm.$valid);

        // principal office
        var isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                $scope[amendmentBusinessForm].PrincipalOffice.$valid);

        //$scope.modal.PrincipalOffice.IsOldDataExist ? (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                $scope[amendmentBusinessForm].PrincipalOffice.$valid) : true;

        var isPrincipalOfficeInWashingtonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                $scope[amendmentBusinessForm].PrincipalOffice.$valid);

        //$scope.modal.PrincipalOffice.IsOldDataExist ? (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) || $scope[amendmentBusinessForm].PrincipalOffice.$valid) : true;

        var isAuthorizedPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.AuthorizedPersonStaffConsole, $scope.modal, $scope.modal.BusinessTypeID) || $scope[amendmentBusinessForm].AuthorizedPersonForm.$valid);

        var isPLLCAttestationFormValidate = (!$scope.ScreenPart($scope.modal.AllScreenParts.PllcAttestation, $scope.modal, $scope.modal.BusinessTypeID) || $scope[amendmentBusinessForm].PLLCAttestationForm.$valid);

        var isGeneralPartnersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartners, $scope.modal, $scope.modal.BusinessTypeID)
                                 || $scope.principalsCount("GeneralPartner") > 0);
        //Prepared Amendment 
        var isPreparedAmendmentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PreparedAmendment, $scope.modal, $scope.modal.BusinessTypeID) ||
                                          $scope.modal.IsArticalsExist ? ($scope.modal.IsArticalsExist && $scope.modal.UploadFileInfo != null && $scope.modal.UploadFileInfo.length > constant.ZERO) : true);

        //Governing Person 
        var isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.amendprincipalsCount("GOVERNINGPERSON") > 0);

        $scope.isGeneralPartnersSignatureConfirmationValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartnersSignatureConfirmation, $scope.modal, $scope.modal.BusinessTypeID)
                                 || ($scope.modal.isGeneralPartnerSignatureConfirmation == true || $scope.modal.GeneralPartnersSignatureConfirmation == "true"));

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        var isCorrespondenceAddressValid = $scope[amendmentBusinessForm].CorrespondenceAddress.$valid;


        var isDistributionOfAssetsValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.DistributionOfAssets, $scope.modal, $scope.modal.BusinessTypeID)
                                        || $scope[amendmentBusinessForm].DistributionOfAssetsForm.$valid);
        //var isNotIncorporatorEntityName = wacorpService.validateIncorporatorListWithEntityName($rootScope.NewEntityNameCleanUp) == false ? true : false;
        //$scope.isIncorporatorEntityName = isNotIncorporatorEntityName == false ? true : false;


        //var isNotGeneralPartnerEntityName = wacorpService.validateGeneralPartnerWithEntityName($rootScope.NewEntityNameCleanUp) == false ? true : false;
        //$scope.isGeneralPartnerEntityName = isNotGeneralPartnerEntityName == false ? true : false;

        var isFormValid = isEntityValid && isEffectiveDateValid && isJurisdictionFormValid && isPrincipalOfficeValid
                            && isRegisteredAgentValid && isGoverningPersonValid && isDurationValid && isCorporateSharesValid && isPurposeAndPowersValid
                            && isPurposeOfCorporationValid && isAttestationofSocialPurposeValid
                            //&& isAttestationOfStatedProfessionValid 
                            //&& isNotIncorporatorEntityName && isNotGeneralPartnerEntityName
                            && isPrincipalOfficeValid && isAuthorizedPersonValid
                            && isPLLCAttestationFormValidate
                            && $scope.isGeneralPartnersSignatureConfirmationValid && isGeneralPartnersValid && isAdoptionOfArticlesOfAmendmentNonProfitValid && isDateOfAdoptionValid
                            && isPrincipalOfficeInWashingtonValid && isPreparedAmendmentValid && isAdditionalUploadValid && isCorrespondenceAddressValid && isDistributionOfAssetsValid
                            && isRegisteredAgentValidStates;


        // Check indicators Validation
        //if (!$scope.modal.IsNameReserved) {
        //    $scope.modal.isValidIndicator();
        //}

        if (isFormValid) {
            $scope.IsCorporateSharesCommonStockValidate = false;
            $scope.validateErrorMessage = false;
            $scope.validateAgentErrors = false;
            $scope.validateOneAgent = false;
            calcDuration();
            $scope.modal.PrincipalOffice.PhoneNumber = $scope.modal.PrincipalOffice.PhoneNumber;
            $scope.modal.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalMailingAddress);
            $scope.modal.PrincipalOffice.PrincipalStreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalStreetAddress);
            //$scope.modal.JurisdictionDesc = $scope.selectedJurisdiction($scope.JurisdictionList);
            $scope.modal.AmendedBusinessType = angular.isNullorEmpty($scope.amendmentEntityType) ? "" : $scope.amendmentEntityType.Key;
            $scope.modal.AmendedBusinessTypeDesc = angular.isNullorEmpty($scope.amendmentEntityType) ? "" : $scope.amendmentEntityType.Value;
            $scope.modal.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.EffectiveDate;
            $scope.modal.BusinessFiling.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.EffectiveDate;
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	            $scope.modal.IsEmailOptionChecked = false;
            }
            if ($scope.modal.DateOfAdoptionType == ResultStatus.DATEOFADOPTIONFILING)
                $scope.modal.BusinessFiling.DateOfAdoption = new Date();
            else
                $scope.modal.BusinessFiling.DateOfAdoption = $scope.modal.DateOfAdoption;
            $rootScope.currentBusiness = $scope.currentBusiness;
            $scope.modal.OldBusinessTypeID = $scope.currentbusinesstypeid;
            $scope.modal.PeriodofDurationDate = $scope.modal.PeriodofDurationDate;
            if ($scope.modal.DurationYears > 0) {
                var d = new Date();
                var year = d.getFullYear() + parseInt($scope.modal.DurationYears);
                var month = d.getMonth();
                var day = d.getDate();
                $scope.modal.DurationExpireDate = new Date(year, month, day)
            }
            $rootScope.modal = $scope.modal;
            $location.path('/businessAmendmentReview');
        }
        else {
            if (!isCorporateSharesValid) {
                $scope.modal.IsAmendmentCorpSharesChange = true;
            }

            if (!isEntityValid) {
                $scope.modal.IsAmendmentEntityNameChange = true;
            }

            if (isBusinessNameExists && !isEntityValid) {
                setTimeout(function () {
                    $("#txtBusiessName").trigger("blur");
                }, 500);
                //return false;
            }
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };


    $scope.DateofAdoptionOfArticlesOfAmendmentNonProfit = function () {
        if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'M') {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = '';
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit;
        }
        else if ($scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'B') {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = '';
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit;
        }
        else {
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM = '';
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB = '';
            $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = null;
        }
    }

    $scope.selectedJurisdiction = function (items) {
        var result = "";
        angular.forEach(items, function (item) {
            if ($scope.modal.Jurisdiction == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (screenPart != undefined && screenPart != 'undefined' && screenPart != '' && screenPart != null) {
            return (lookupService.canShowScreenPart(screenPart, modal, businessTypeID)) ? true : false;
        }
    };

    // get business entity types list for amendment
    $scope.getEntityTypes = function (entityname) {

        var config = { params: { name: entityname } };
        // getLookUpDataForAmendment method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpDataForAmendment, config, function (response) {

            if (response.data.length > 0) {
                $scope.amendmentEntityTypes = response.data;
                $scope.setEntityType(response.data);
                $scope.IsAmendEntityTypeShow = true;
            }
            else {
                $scope.IsAmendEntityTypeShow = false;
            }
        }, function (error) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });
    };

    $scope.setEntityType = function (items) {
        if (!angular.isNullorEmpty($scope.modal.BusinessType)) {
            angular.forEach(items, function (item) {
                if ($scope.modal.AmendedBusinessTypeDesc == item.Value) {
                    $scope.amendmentEntityType = item;
                }
            });
        }
    }
    // check duration mode
    $scope.IsPerpetual = function (obj) {
        if (obj == 'rdoDureationDate') {
            $scope.modal.IsPerpetual = false;
            //$scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
        else if (obj == 'rdoDureationYears') {
            $scope.modal.IsPerpetual = false;
            $scope.modal.DurationExpireDate = null;
        }
        else {
            $scope.modal.IsPerpetual = true;
            $scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
    }

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };

    //  check whether form is valid / not
    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    // validate principals count
    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    $scope.amendprincipalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    //duration calculation
    function calcDuration() {
        $scope.modal.DurationYears = $scope.modal.DurationYears == 0 ? null : $scope.modal.DurationYears;
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        $scope.modal.DurationExpireDate = wacorpService.dateFormatService($scope.modal.DurationExpireDate);

        if ($scope.modal.DurationYears > 0) {
            $scope.modal.DurationType = "rdoDureationYears";
        }
        else if ($scope.modal.DurationExpireDate != null) {
            $scope.modal.DurationType = "rdoDureationDate";
        }
        else {
            $scope.DurationType = "rdoPerpetual";
        }

        $scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? null : wacorpService.dateFormatService($scope.modal.DurationExpireDate);
        $scope.modal.DurationType = ($scope.modal.DurationYears == null && ($scope.modal.DurationExpireDate == null || $scope.modal.DurationExpireDate == "")) && $scope.modal.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
        if ($scope.modal.DurationType == 'rdoPerpetual') {
            $scope.modal.IsPerpetual = true;
        }
    }
    // check business count availability
    $scope.availableBusinessCount = function () {

        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {

            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };
    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.AmendedBusinessType = angular.isNullorEmpty($scope.amendmentEntityType) ? "" : $scope.amendmentEntityType.Key;
        $scope.modal.AmendedBusinessTypeDesc = angular.isNullorEmpty($scope.amendmentEntityType) ? "" : $scope.amendmentEntityType.Value;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.NewBusinessName = $scope.modal.BusinessName;

        $scope.modal.OnlineNavigationUrl = '/BusinessAmendment';
        $scope.modal.CartStatus = 'Incomplete';

        $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfit = $scope.modal.AdoptionofArticlesofAmendmentNonProfit == 'M' ? $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitM : $scope.modal.DateofAdoptionOfArticlesOfAmendmentNonProfitB;
        if ($scope.modal.NatureOfBusiness.NAICSCode && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // AmendmentSaveAsDraft is avaialable in constants.js
        wacorpService.post(webservices.OnlineFiling.AmendmentSaveAsDraft, $scope.modelDraft, function (response) {

            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
            }
            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                if ($scope.modal.NatureOfBusiness.NAICSCode && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                    $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.split(",");
                }
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    //Amendment Entity Type Change Radio button change click
    $scope.isAmendmentEntityTypeChange = function (value) {
        $scope.modal.removeErrorMessage =false;
        // No radio button Click
        if (!value) {
            if ($scope.amendmentEntityType != null) {
                $scope.amendmentEntityType = null;
                var businesstypeid = $scope.modal.oldAmendmentEntity.BusinessTypeID
                var data = { params: { businessTypeid: businesstypeid } };
                // reloadwithNewBusinessType method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.reloadwithNewBusinessType, data, function (response) {
                    $scope.modal.Indicator = response.data.Indicator;
                    $scope.modal.FilingType = response.data.FilingType;
                    $scope.modal.BusinessTypeID = businesstypeid;
                    $scope.modal.BusinessTransaction.BusinessTypeID = businesstypeid;
                    $scope.modal.IsAmendmentEntityNameChange = false;
                    $scope.modal.removeErrorMessage = true;
                    $scope.modal.BusinessName=$scope.modal.oldBusinessName;
                    if ($scope.modal.businessNames)
                    {
                       $scope.modal.businessNames.length = 0;
                    }
                    $rootScope.$broadcast('onBusinessTypeChange');
                });
                $scope.modal.IsAmendmentEntityType = false;
                //$scope.modal.IsAmendmentEntityNameChange = false;
            }
        }
        else {
            // Yes radio button Click
            $scope.modal.IsAmendmentEntityType = true;
        }
    };

    var domesticBusinessNameNo = $scope.$on("isBAmendmentEntityTypeChange", function (event, data) {
        $scope.isAmendmentEntityTypeChange(data);
    });

    $scope.$on('$destroy', function () {
        domesticBusinessNameNo(); // businessNameNo method is available in this controller only.
    });

    //Amendment Duration Change Radio button change click
    $scope.isAmendmentDurationChange = function (value) {
        // No radio button Click
        if (!value) {
            $scope.modal.DurationYears = $scope.modal.oldAmendmentEntity.DurationYears == 0 ? null : $scope.modal.oldAmendmentEntity.DurationYears;
            $scope.modal.DurationExpireDate = ($scope.modal.oldAmendmentEntity.DurationExpireDate == null || $scope.modal.oldAmendmentEntity.DurationExpireDate == "0001-01-01T00:00:00") ? null : wacorpService.dateFormatService($scope.modal.oldAmendmentEntity.DurationExpireDate);
            $scope.modal.DurationType = ($scope.modal.oldAmendmentEntity.DurationYears == null && ($scope.modal.oldAmendmentEntity.DurationExpireDate == null || $scope.modal.oldAmendmentEntity.DurationExpireDate == "")) && $scope.modal.oldAmendmentEntity.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.oldAmendmentEntity.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.oldAmendmentEntity.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
            $scope.modal.IsPerpetual = $scope.modal.oldAmendmentEntity.IsPerpetual;
            $scope.modal.IsAmendmentDurationChange = false;
        }
            // Yes radio button Click
        else {
            $scope.modal.IsAmendmentDurationChange = true;
        }
    };

    //Amendment Corp Shares Change Radio button change click
    $scope.isAmendmentCorpSharesChange = function (value) {
        // No radio button Click
        if (!value) {
            $scope.modal.CorporateShares = $scope.modal.oldAmendmentEntity.CorporateShares == 0 ? "" : $scope.modal.oldAmendmentEntity.CorporateShares;
            $scope.modal.IsArticalsExist = $scope.modal.oldAmendmentEntity.IsArticalsExist;
            $scope.modal.IsCorporateSharesCommonStock = $scope.modal.oldAmendmentEntity.IsCorporateSharesCommonStock;
            $scope.modal.IsCorporateSharesPreferedStock = $scope.modal.oldAmendmentEntity.IsCorporateSharesPreferedStock;
            $scope.modal.IsShareInformationChange = $scope.modal.oldAmendmentEntity.IsShareInformationChange;
            $scope.modal.ShareInformationChange = $scope.modal.oldAmendmentEntity.ShareInformationChange;
            $scope.modal.isAmendmentCorpSharesChange = false;
        }
            // Yes radio button Click
        else {
            $scope.modal.isAmendmentCorpSharesChange = true;
        }
    };
    $scope.removeCommas = function (value) {

        $scope.modal.CorporateShares = $scope.modal.CorporateShares != "0" && $scope.modal.CorporateShares != "" ? $scope.modal.CorporateShares.replace(",", "") : $scope.modal.CorporateShares;
    }

    $scope.onlyNumbersPaste = function (value) {
        // TFS 3116 - only Numbers Paste
        $scope.modal.CorporateShares =  $scope.modal.CorporateShares.replace(/\D/g, "") ;
    }

});
wacorpApp.controller('commercialStatementofChangeController', function ($scope, $location, $rootScope, wacorpService, $timeout) {

    //-------------------------------------------- Business Search list ---------------------------------------//
    // declare scope variables
    $scope.modal = $scope.modal || {};
    $scope.businessSearchCriteria = { IsOnline: true, SearchType: searchTypes.COMMERCIALSTATEMENTOFCHANGE, AgentId: $rootScope.repository.loggedUser.agentid };
    $scope.selectedBusiness = false;
    $scope.isCRACountValidate = false;
    $scope.isLookupClicked = false;
    $scope.craNameAvailableMsg = false;
    focus('tblBusinessSearch');

    $scope.CountriesList = [];
    $scope.StatesList = [];
    $scope.businessTypes = [];

    // navigate to initial report
    $scope.getNavigation = function () {
        $rootScope.BusinessIDs = "";
        angular.forEach($scope.BusinessList, function (business) {
            if (business.isSelect)
                $rootScope.BusinessIDs += business.BusinessID + ",";
        });
        $rootScope.commercialStatementofChangeModal = null;
        $rootScope.transactionID = null;
        $location.path('/CommercialStatementofChange');
    };
    // get business list data from server
    function loadbusinessList() {
        $scope.BusinessList = [];
        var data = $scope.businessSearchCriteria
        // getBusinessNames method is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.BusinessList = response.data;
            focus('tblBusinessSearch');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
    }, true);

    $scope.loadbusinessInfo = function () {
        loadbusinessList(); // loadbusinessList method is available in this controller only.
    };

    // select All cart items
    $scope.selectAll = function () {
        angular.forEach($scope.BusinessList, function (business) {
            business.isSelect = $scope.modal.selectAll;
            $scope.selectedBusiness = $scope.modal.selectAll;
        });
    };

    // item checkbox click
    $scope.selectChange = function (business) {
        var flag = true;
        var isBusinessSelected = false;
        //if (business.isSelect) { //TFS 13053
        //    if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf(business.BusinessStatus) < constant.ZERO) {
        //        business.isSelect = false;
        //        wacorpService.alertDialog(messages.selectedBusiness.replace('{0}', business.BusinessStatus));
        //    }
        //}
        angular.forEach($scope.BusinessList, function (business) {
            if (!business.isSelect) {
                flag = false;
                return;
            }
            if (business.isSelect) {
                isBusinessSelected = true;
                return;
            }
        });
        $scope.modal.selectAll = flag;
        $scope.selectedBusiness = isBusinessSelected;
    };


    //-------------------------------------- Statement of change screen functionality--------------------//

    $scope.Init = function () {
        $scope.unitedstates = "UNITED STATES";
        $scope.validateOneAgent = $scope.validateAgentErrors = $scope.validateAuthorizedErrors = false;
        $scope.messages = messages;
        var data = null;
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.commercialStatementofChangeModal = $rootScope.modal;
            //$rootScope.modal = null;
        }
        if ($rootScope.transactionID > constant.ZERO)
            data = {
                params: {
                    businessID: null, transactionID: $rootScope.transactionID,
                }
            };
        else
            data = {
                params: {
                    businessID: $rootScope.repository.loggedUser.agentid, transactionID: $rootScope.transactionID
                }
            };
        if (angular.isNullorEmpty($rootScope.commercialStatementofChangeModal)) {
            //if ($rootScope.BusinessIDs == undefined && $rootScope.transactionID == undefined) {
            //    var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
            //    wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
            //        $scope.newUser = response.data;
            //        $scope.modal.PrevRegisteredAgent.StreetAddress.FullAddress = $scope.newUser.Address.FullAddress;
            //        $scope.modal.PrevRegisteredAgent.MailingAddress.FullAddress = $scope.newUser.AltAddress.FullAddress;
            //        $location.path('/CommercialStatementofChange');
            //    })
            //}
            //else {
            // CommercialStatementofChangeCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.CommercialStatementofChangeCriteria, data, function (response) {
                $scope.modal = response.data;
                $scope.modal.BusinessIDs = $rootScope.BusinessIDs;
                //$scope.modal.RegisteredAgent.AgentType = $scope.modal.RegisteredAgent.AgentType || ResultStatus.INDIVIDUAL;
                $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || ResultStatus.INDIVIDUAL;
                $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                $scope.modal.PrevRegisteredAgent.ConfirmEmailAddress = $scope.modal.PrevRegisteredAgent.EmailAddress;

                $scope.modal.PrevRegisteredAgent.BusinessTypeID = ($scope.modal.PrevRegisteredAgent.BusinessTypeID == null || $scope.modal.PrevRegisteredAgent.BusinessTypeID == "0") ? "" : $scope.modal.PrevRegisteredAgent.BusinessTypeID.toString();
                $scope.modal.PrevRegisteredAgent.JurisdictionDesc = angular.isNullorEmpty($scope.modal.PrevRegisteredAgent.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.PrevRegisteredAgent.JurisdictionDesc;
                $scope.modal.PrevRegisteredAgent.Jurisdiction = ($scope.modal.PrevRegisteredAgent.Jurisdiction == null || $scope.modal.PrevRegisteredAgent.Jurisdiction == "0") ? "" : $scope.modal.PrevRegisteredAgent.Jurisdiction.toString();
                $scope.modal.PrevRegisteredAgent.JurisdictionCountry = ($scope.modal.PrevRegisteredAgent.JurisdictionCountry == null || $scope.modal.PrevRegisteredAgent.JurisdictionCountry == 0 || $scope.modal.PrevRegisteredAgent.JurisdictionCountry == "") ? usaCode : $scope.modal.PrevRegisteredAgent.JurisdictionCountry.toString();
                $scope.modal.PrevRegisteredAgent.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.PrevRegisteredAgent.JurisdictionCountry);
                $scope.modal.PrevRegisteredAgent.JurisdictionState = ($scope.modal.PrevRegisteredAgent.JurisdictionState == null || $scope.modal.PrevRegisteredAgent.JurisdictionState == 0) ? null : $scope.modal.PrevRegisteredAgent.JurisdictionState.toString();
                $scope.modal.PrevRegisteredAgent.StreetAddress = angular.copy($scope.modal.PrevRegisteredAgent.StreetAddress);

                $scope.modal.PrevRegisteredAgent.MailingAddress = angular.copy($scope.modal.PrevRegisteredAgent.MailingAddress);
                //***** Revised per TFS #1158 - KK, 12/31/2019
                //if ($scope.modal.PrevRegisteredAgent.MailingAddress.StreetAddress1 == null || $scope.modal.PrevRegisteredAgent.MailingAddress.StreetAddress1 == "") {
                //    $scope.modal.PrevRegisteredAgent.MailingAddress.State = null;
                //    $scope.modal.PrevRegisteredAgent.MailingAddress.Country = null;
                //}

                $scope.modal.PrevRegisteredAgent.OldEntityName = angular.copy($scope.modal.PrevRegisteredAgent.EntityName);
                $scope.modal.PrevRegisteredAgent.OldFirstName = angular.copy($scope.modal.PrevRegisteredAgent.FirstName);
                $scope.modal.PrevRegisteredAgent.OldLastName = angular.copy($scope.modal.PrevRegisteredAgent.LastName);
                $scope.isShowReturnAddress = true;


                if ($scope.modal.CartStatus && $scope.modal.CartStatus != 'Incomplete-Shopping Cart') {
                    var newdata = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                    // getUserDetails method is available in constants.js
                    wacorpService.get(webservices.UserAccount.getUserDetails, newdata, function (response) {
                        $scope.newUser = response.data;
                        $scope.modal.PrevRegisteredAgent.IsNewAgent = true;
                        $scope.modal.PrevRegisteredAgent.IsNonCommercial = true;
                        $scope.modal.PrevRegisteredAgent.AgentType = angular.copy($scope.newUser.Agent.AgentType);
                        $scope.modal.PrevRegisteredAgent.AgentID = angular.copy($scope.newUser.Agent.AgentID);
                        $scope.modal.PrevRegisteredAgent.EntityName = angular.copy($scope.newUser.Agent.EntityName);
                        $scope.modal.PrevRegisteredAgent.FirstName = angular.copy($scope.newUser.FirstName);
                        $scope.modal.PrevRegisteredAgent.LastName = angular.copy($scope.newUser.LastName);
                        //$scope.modal.PrevRegisteredAgent.FullName = wacorpService.agentFullNameService($scope.newUser);
                        $scope.modal.PrevRegisteredAgent.EmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.modal.PrevRegisteredAgent.ConfirmEmailAddress = angular.copy($scope.newUser.EmailID);
                        $scope.modal.PrevRegisteredAgent.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                        $scope.modal.PrevRegisteredAgent.StreetAddress = $scope.newUser.Address;

                        $scope.modal.PrevRegisteredAgent.MailingAddress = $scope.newUser.AltAddress;

                        $scope.modal.PrevRegisteredAgent.BusinessTypeID = ($scope.newUser.Agent.BusinessTypeID == null || $scope.newUser.Agent.BusinessTypeID == "0") ? "" : $scope.newUser.Agent.BusinessTypeID.toString();
                        $scope.modal.PrevRegisteredAgent.JurisdictionDesc = angular.isNullorEmpty($scope.newUser.Agent.JurisdictionDesc) ? "WASHINGTON" : $scope.newUser.Agent.JurisdictionDesc;
                        $scope.modal.PrevRegisteredAgent.Jurisdiction = ($scope.newUser.Agent.Jurisdiction == null || $scope.newUser.Agent.Jurisdiction == "0") ? "" : $scope.newUser.Agent.Jurisdiction.toString();
                        $scope.modal.PrevRegisteredAgent.JurisdictionCountry = ($scope.newUser.Agent.JurisdictionCountry == null || $scope.newUser.Agent.JurisdictionCountry == 0 || $scope.newUser.Agent.JurisdictionCountry == "") ? usaCode : $scope.newUser.Agent.JurisdictionCountry.toString();
                        $scope.modal.PrevRegisteredAgent.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.newUser.Agent.JurisdictionCountry);
                        $scope.modal.PrevRegisteredAgent.JurisdictionState = ($scope.newUser.Agent.JurisdictionState == null || $scope.newUser.Agent.JurisdictionState == 0) ? null : $scope.newUser.Agent.JurisdictionState.toString();

                        $scope.modal.PrevRegisteredAgent.OldEntityName = angular.copy($scope.newUser.Agent.EntityName);
                        $scope.modal.PrevRegisteredAgent.OldFirstName = angular.copy($scope.newUser.Agent.FirstName);
                        $scope.modal.PrevRegisteredAgent.OldLastName = angular.copy($scope.newUser.Agent.LastName);
                    })
                }
                $location.path('/CommercialStatementofChange');
                if ($scope.modal.IsActiveFilingExist) {
                    //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js 
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }

            }, function () { });
            //}
        }
        else {
            $scope.modal = $rootScope.commercialStatementofChangeModal;
            $scope.modal.PrevRegisteredAgent.BusinessTypeID = $scope.modal.PrevRegisteredAgent.BusinessTypeID.toString();
            $scope.modal.PrevRegisteredAgent.Jurisdiction = $scope.modal.PrevRegisteredAgent.Jurisdiction.toString();
            $scope.modal.PrevRegisteredAgent.JurisdictionCountry = $scope.modal.PrevRegisteredAgent.JurisdictionCountry.toString();
            $scope.modal.PrevRegisteredAgent.JurisdictionState = $scope.modal.PrevRegisteredAgent.JurisdictionState.toString();

            $timeout(function () {
                $("#ddlBusinessTypes").val($scope.modal.PrevRegisteredAgent.BusinessTypeID);
                $("#id-JurisdictionCountry").val($scope.modal.PrevRegisteredAgent.JurisdictionCountry);
                $("#id-JurisdictionState").val($scope.modal.PrevRegisteredAgent.JurisdictionState);
            }, 1000);

            $scope.isShowReturnAddress = true;

        }
    };

    $scope.continueSave = function (stmtChangeForm) {

        $scope.validateAuthorizedErrors = true;
        $scope.validateErrorMessage = true;

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[stmtChangeForm]);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isJurisdictionFormValid = ($scope.modal.PrevRegisteredAgent.AgentType == 'E' ? $scope[stmtChangeForm].JurisdictionForm.$valid : true);

        var craNameValid = $scope.modal.IsRALookupEnabled ? !$scope.isCRACountValidate : true;

        var craLookupValid = $scope.modal.IsRALookupEnabled ? $scope.isLookupClicked : true;

        var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.PrevRegisteredAgent.JurisdictionCountry);

        var isRegisteredAgentValidStates = !$scope.modal.PrevRegisteredAgent.StreetAddress.IsInvalidState && !$scope.modal.PrevRegisteredAgent.MailingAddress.IsInvalidState && !$scope.modal.PrevRegisteredAgent.StreetAddress.invalidPoBoxAddress;

        $scope.modal.PrevRegisteredAgent.BusinessType = $scope.selectedJurisdiction($scope.businessTypes, $scope.modal.PrevRegisteredAgent.BusinessTypeID);



        if (countryDesc == $scope.unitedstates) {
            var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.PrevRegisteredAgent.JurisdictionState);
            $scope.modal.PrevRegisteredAgent.Jurisdiction = angular.copy($scope.modal.PrevRegisteredAgent.JurisdictionState);
            $scope.modal.PrevRegisteredAgent.JurisdictionDesc = angular.copy(stateDesc);
            $scope.modal.PrevRegisteredAgent.JurisdictionStateDesc = angular.copy(stateDesc);
            $scope.modal.PrevRegisteredAgent.JurisdictionCountryDesc = angular.copy(countryDesc);
            $scope.modal.PrevRegisteredAgent.JurisdictionCategory = 'S';
        }
        else {
            $scope.modal.PrevRegisteredAgent.Jurisdiction = angular.copy($scope.modal.PrevRegisteredAgent.JurisdictionCountry);
            $scope.modal.PrevRegisteredAgent.JurisdictionDesc = angular.copy(countryDesc);
            $scope.modal.PrevRegisteredAgent.JurisdictionCountryDesc = angular.copy(countryDesc);
            $scope.modal.PrevRegisteredAgent.JurisdictionStateDesc = null;
            $scope.modal.PrevRegisteredAgent.JurisdictionCategory = 'C';
        }
        //$scope.validateAgentErrors = $scope.modal.RegisteredAgent.IsNewAgent;
        //$scope.validateOneAgent = $scope.modal.RegisteredAgent.AgentID == constant.ZERO && !$scope.modal.RegisteredAgent.IsNewAgent;



        if ($scope[stmtChangeForm].CorrespondenceAddress != null) {
            var isCorrespondenceAddressValid = $scope[stmtChangeForm].CorrespondenceAddress.$valid;
        } else {
            var isCorrespondenceAddressValid = true;
        }






        //var isPreviousRegisteredAgentValid = $scope[stmtChangeForm].PrevRegisteredAgentForm.$valid;
        if ($scope[stmtChangeForm].AuthorizedPersonForm.$valid && isAdditionalUploadValid && $scope[stmtChangeForm].PrevRegisteredAgentForm.$valid && $scope[stmtChangeForm].AttestationForm.$valid && isJurisdictionFormValid && craNameValid && craLookupValid && isRegisteredAgentValidStates && isCorrespondenceAddressValid) {
            $scope.validateOneAgent = $scope.validateAgentErrors = $scope.validateAuthorizedErrors = false;
            //$scope.modal.RegisteredAgent.MailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.RegisteredAgent.MailingAddress);
            //$scope.modal.RegisteredAgent.StreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.RegisteredAgent.StreetAddress);
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.PrevRegisteredAgent.MailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrevRegisteredAgent.MailingAddress);
            $scope.modal.PrevRegisteredAgent.StreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrevRegisteredAgent.StreetAddress);
            $scope.OldEntityName = $scope.OldEntityName;
            $scope.OldFirstName = $scope.OldFirstName;
            $scope.OldLastName = $scope.OldLastName;
            $rootScope.commercialStatementofChangeModal = $scope.modal;
            $location.path('/CommercialStatementofChangeReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // back to business search
    $scope.back = function () {
        $location.path('/CommercialStatementofChange');
    };

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        //$scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/CommercialStatementofChange';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        if ($scope.modelDraft.RegisteredAgent.MailingAddress.StreetAddress1 === undefined) {
            $scope.modelDraft.RegisteredAgent.MailingAddress.State = undefined;
            $scope.modelDraft.RegisteredAgent.MailingAddress.Country = undefined;
            $scope.modelDraft.RegisteredAgent.MailingAddress.CountyName = undefined;
            $scope.modelDraft.RegisteredAgent.MailingAddress.CountryName = undefined;
        };
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });

        // CommercialStatementofChangeSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CommercialStatementofChangeSaveAsDraft, $scope.modelDraft, function (response) {

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: InvalidFilingMsg method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    //$scope.clearAgentInfo = function (agentType) {
    //    if (agentType == 'I') {
    //        $scope.modal.PrevRegisteredAgent.EntityName = '';
    //        //$scope.agent.OfficeOrPosition = '';
    //    }
    //    else if (agentType == 'E') {
    //        $scope.modal.PrevRegisteredAgent.FirstName = '';
    //        $scope.modal.PrevRegisteredAgent.LastName = '';
    //        $scope.modal.PrevRegisteredAgent.EntityName = '';
    //        //$scope.agent.OfficeOrPosition = '';
    //    }
    //    else {
    //        $scope.modal.PrevRegisteredAgent.FirstName = '';
    //        $scope.modal.PrevRegisteredAgent.LastName = '';
    //        $scope.modal.PrevRegisteredAgent.EntityName = '';
    //    }
    //}

    var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
    // GetLookUpData method is available in constants.js
    wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
        $scope.CountriesList = response.data;
        $timeout(function () {
            $("#id-JurisdictionCountry").val($scope.modal.PrevRegisteredAgent.JurisdictionCountry);
            $("#id-JurisdictionState").val($scope.modal.PrevRegisteredAgent.JurisdictionState);
        }, 1000);
    }, function (response) {
    });

    var lookupStatesParams = { params: { name: 'JurisdictionStates' } };
    // GetLookUpData method is available in constants.js
    wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
        $scope.StatesList = response.data;
    }, function (response) {
    });

    var config = { params: { name: 'AdvancedBusinessType' } };
    // GetLookUpData method is available in constants.js
    wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.businessTypes = response.data; });


    $scope.CopyAgentStreetFromMailing = function () {
        //Holding Returned Mail Flags for RA
        var isRAMailingAddressReturnedMail = $scope.modal.PrevRegisteredAgent.MailingAddress.IsAddressReturnedMail;

        $scope.mailingAddressID = $scope.modal.PrevRegisteredAgent.MailingAddress.ID;
        if ($scope.modal.PrevRegisteredAgent.IsSameAsMailingAddress) {
            angular.copy($scope.modal.PrevRegisteredAgent.StreetAddress, $scope.modal.PrevRegisteredAgent.MailingAddress);
            $scope.modal.PrevRegisteredAgent.MailingAddress.ID = $scope.mailingAddressID;
        }
        else
            angular.copy("", $scope.modal.PrevRegisteredAgent.MailingAddress);

        //Setting the Returned Mail Values
        $scope.modal.PrevRegisteredAgent.MailingAddress.IsAddressReturnedMail = isRAMailingAddressReturnedMail;

        if ($scope.modal.PrevRegisteredAgent.IsSameAsMailingAddress)
            $scope.$broadcast("IsMailingRAAddress", true);
        else if (!$scope.modal.PrevRegisteredAgent.IsSameAsMailingAddress)
            $scope.$broadcast("IsMailingRAAddress", false);
    };

    $scope.cancelAgent = function () {

        $scope.modal.PrevRegisteredAgent.FirstName = '';
        $scope.modal.PrevRegisteredAgent.LastName = '';
        $scope.modal.PrevRegisteredAgent.EntityName = '';
        $scope.modal.PrevRegisteredAgent.EmailAddress = '';
        $scope.modal.PrevRegisteredAgent.ConfirmEmailAddress = '';
        $scope.modal.PrevRegisteredAgent.PhoneNumber = '';
        //StreetAddress
        $scope.modal.PrevRegisteredAgent.StreetAddress.StreetAddress1 = '';
        $scope.modal.PrevRegisteredAgent.StreetAddress.StreetAddress2 = '';
        $scope.modal.PrevRegisteredAgent.StreetAddress.Zip5 = '';
        $scope.modal.PrevRegisteredAgent.StreetAddress.Zip4 = '';
        $scope.modal.PrevRegisteredAgent.StreetAddress.Country = '';
        $scope.modal.PrevRegisteredAgent.StreetAddress.City = '';
        //MailingAddress
        $scope.modal.PrevRegisteredAgent.MailingAddress.StreetAddress1 = '';
        $scope.modal.PrevRegisteredAgent.MailingAddress.StreetAddress2 = '';
        $scope.modal.PrevRegisteredAgent.MailingAddress.Zip5 = '';
        $scope.modal.PrevRegisteredAgent.MailingAddress.Zip4 = '';
        $scope.modal.PrevRegisteredAgent.MailingAddress.Country = '';
        $scope.modal.PrevRegisteredAgent.MailingAddress.City = '';
        $scope.modal.PrevRegisteredAgent.AgentType = 'I';

    }

    $scope.CountryChangeDesc = function () {
        $scope.modal.PrevRegisteredAgent.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
        if ($scope.modal.PrevRegisteredAgent.JurisdictionCountryDesc.toUpperCase() == 'UNITED STATES') {
            $scope.modal.PrevRegisteredAgent.JurisdictionState = '';
        };
    };

    $scope.selectedJurisdiction = function (items, selectedVal) {
        var result = "";
        angular.forEach(items, function (item) {
            if (selectedVal == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }

    $scope.searchCommercialAgents = function searchCommercialAgents(PrevRegisteredAgentForm) {

        $scope.isCRACountValidate = false;
        $scope.isLookupClicked = true;

        if ($scope.modal.PrevRegisteredAgent.AgentType == "E") {
            if (!$scope.modal.PrevRegisteredAgent.EntityName) {
                $scope.validateErrorMessage = true;
                return false;
            }
            if (($scope.modal.PrevRegisteredAgent.OldEntityName != null && $scope.modal.PrevRegisteredAgent.OldEntityName.trim()) == ($scope.modal.PrevRegisteredAgent.EntityName != null && $scope.modal.PrevRegisteredAgent.EntityName.trim())) {
                $scope.isCRACountValidate = false;
                $scope.craNameAvailableMsg = true;
                $scope.isLookupClicked = true;
                return false;
            }
        }
        else {
            if (!$scope.modal.PrevRegisteredAgent.FirstName || !$scope.modal.PrevRegisteredAgent.LastName) {
                $scope.validateErrorMessage = true;
                return false;
            }

            $scope.IsHiddenAgentName = ($scope.modal.PrevRegisteredAgent.OldFirstName != null && $scope.modal.PrevRegisteredAgent.OldFirstName.trim()) + ' ' + ($scope.modal.PrevRegisteredAgent.OldLastName != null && $scope.modal.PrevRegisteredAgent.OldLastName.trim());
            $scope.IsModelAgentName = ($scope.modal.PrevRegisteredAgent.FirstName != null && $scope.modal.PrevRegisteredAgent.FirstName.trim()) + ' ' + ($scope.modal.PrevRegisteredAgent.LastName != null && $scope.modal.PrevRegisteredAgent.LastName.trim());

            if ($scope.IsHiddenAgentName == $scope.IsModelAgentName) {
                $scope.isCRACountValidate = false;
                $scope.craNameAvailableMsg = true;
                $scope.isLookupClicked = true;
                return false;
            }
        }



        var criteria = {
            FirstName: $scope.modal.PrevRegisteredAgent.AgentType == "I" ? ($scope.modal.PrevRegisteredAgent.FirstName != null && $scope.modal.PrevRegisteredAgent.FirstName.trim()) : "" || '', LastName: $scope.modal.PrevRegisteredAgent.AgentType == "I" ? ($scope.modal.PrevRegisteredAgent.LastName != null && $scope.modal.PrevRegisteredAgent.LastName.trim()) : "" || '', BusinessName: $scope.modal.PrevRegisteredAgent.AgentType == "E" ? ($scope.modal.PrevRegisteredAgent.EntityName != null && $scope.modal.PrevRegisteredAgent.EntityName.trim()) : "" || '',
        };

        // getCommercialAgentAvailableOrNot method is available in constants.js
        wacorpService.post(webservices.Common.getCommercialAgentAvailableOrNot, criteria, function (response) {
            if (response.data != null) {
                $scope.modal.PrevRegisteredAgent.TotalCount = angular.copy(response.data);

                if ($scope.modal.PrevRegisteredAgent.TotalCount != '0' && $scope.modal.PrevRegisteredAgent.TotalCount != undefined) {
                    $scope.isCRACountValidate = true;
                }
                else {
                    $scope.isCRACountValidate = false;
                    $scope.craNameAvailableMsg = true;
                }
            }
            else
                // Folder Name: app Folder
                // Alert Name: noDataFound method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.noDataFound);
        },
            function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data.Message);
            }
        );
    }

    $scope.enableIndividualLookup = function () {
        if ($scope.modal.PrevRegisteredAgent.AgentType == "I") {
            $scope.modal.IsRALookupEnabled = true;
            $scope.isLookupClicked = false;
        }

    }

    $scope.enableEntityLookup = function () {
        if ($scope.modal.PrevRegisteredAgent.AgentType == "E" && $scope.modal.PrevRegisteredAgent.EntityName != "") {
            $scope.modal.IsRALookupEnabled = true;
            $scope.isLookupClicked = false;
        }
    }

    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
    //$scope.setPastedUBI = function (e) {
    //    var pastedText = "";
    //    if (typeof e.originalEvent.clipboardData !== "undefined") {
    //        pastedText = e.originalEvent.clipboardData.getData('text/plain');
    //        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
    //        $scope.modal.PrevRegisteredAgent.UBINumber = pastedText;
    //        e.preventDefault();
    //    } else {
    //        $timeout(function () {
    //            pastedText = angular.element(e.currentTarget).val();
    //            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
    //            $scope.modal.PrevRegisteredAgent.UBINumber = pastedText;
    //        });
    //    }
    //};
    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036

    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
    //$scope.setUBILength = function (e) {
    //     if ($scope.modal.PrevRegisteredAgent.UBINumber != undefined && $scope.modal.PrevRegisteredAgent.UBINumber != null && $scope.modal.PrevRegisteredAgent.UBINumber!="" && $scope.modal.PrevRegisteredAgent.UBINumber.length >= 9) {
    //        // Allow: backspace, delete, tab, escape, enter and .
    //        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
    //            // Allow: Ctrl+A, Command+A
    //            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
    //            // Allow: home, end, left, right, down, up
    //            (e.keyCode >= 35 && e.keyCode <= 40)) {
    //            // let it happen, don't do anything
    //            return;
    //        }
    //        // Ensure that it is a number and stop the keypress
    //        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    //            e.preventDefault();
    //        }
    //        e.preventDefault();
    //    }
    //};
    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036

    //select the agent type Individual
    $scope.selectAgentTypeIndividual = function () {
        $scope.modal.PrevRegisteredAgent.EntityName = '';
        $scope.craNameAvailableMsg = false;
    };

    $scope.selectAgentTypeEntity = function () {
        $scope.craNameAvailableMsg = false;
    };

    //to clear RA mailing Address when Street address is modified 
    var clearCSCRAStreetAddressOnChange = $scope.$on("clearCSCRAMailingAddress", function (evt, data) {
        if ($scope.modal.PrevRegisteredAgent.IsSameAsMailingAddress) {
            if (wacorpService.compareAddress($scope.modal.PrevRegisteredAgent.StreetAddress, $scope.modal.PrevRegisteredAgent.MailingAddress)) {
                $scope.modal.PrevRegisteredAgent.IsSameAsMailingAddress = false;
                $scope.CopyAgentStreetFromMailing();
            }
        }
        evt.defaultPrevented = true;
    });
    $scope.$on('$destroy', clearCSCRAStreetAddressOnChange);

});

wacorpApp.controller('commercialStatementofChangeReviewController', function ($scope, $location, $rootScope, wacorpService) {
    //-------------------------------------- Statement of change screen functionality--------------------//
    $scope.Init = function () {
        if (angular.isNullorEmpty($rootScope.commercialStatementofChangeModal))
            $location.path('/CommercialStatementofChange');
        else
            $scope.modal = $rootScope.commercialStatementofChangeModal;
    };

    $scope.back = function () {
        $rootScope.commercialStatementofChangeModal = $scope.modal;
        $location.path('/CommercialStatementofChange');
    };

    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CommercialStatementofChangeAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CommercialStatementofChangeAddToCart, $scope.modal, function (response) {
            $rootScope.commercialStatementofChangeModal = null;
            $rootScope.modal = null;
            $rootScope.BusinessType = null;
            $location.path('/shoppingCart');
           },
        function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        // CommercialStatementofChangeAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CommercialStatementofChangeAddToCart, $scope.modal, function (response) {
            $rootScope.commercialStatementofChangeModal = null;
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
            $location.path('/Dashboard');
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('statementofTerminationController', function ($scope, $location, $rootScope, wacorpService) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;

    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        //if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.BusinessStatus) >= constant.ZERO) {
        $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
        $rootScope.statementofTerminationModal = null;
        $rootScope.transactionID = null;
        $location.path('/StatementofTermination/');
        //}
        //else {
        //    wacorpService.alertDialog(messages.selectedBusiness.replace('{0}', $scope.selectedBusiness.BusinessStatus));
        //}
    }

    //-------------------------------------- Statement of Resignation screen functionality--------------------//

    $scope.Init = function () {
        $scope.validateErrorMessage = false;
        //$scope.modal.IsAdditionalDocumentsExist = false;
        $scope.messages = messages;
        var data = null;
        if ($rootScope.transactionID > constant.ZERO)
            data = {
                params: {
                    businessID: null, transactionID: $rootScope.transactionID,
                }
            };
        else
            data = {
                params: {
                    businessID: $rootScope.BusinessID, transactionID: $rootScope.transactionID
                }
            };
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.statementofTerminationModal = $rootScope.modal;
            //$rootScope.modal = null;
        }
        if (angular.isNullorEmpty($rootScope.statementofTerminationModal)) {
            if ($rootScope.BusinessID == undefined && $rootScope.transactionID == undefined) {
                $location.path('/StatementofTerminationIndex');
            }
            else {
                // StatementofTerminationCriteria method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.StatementofTerminationCriteria, data, function (response) {
                    $scope.modal = response.data;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || ResultStatus.INDIVIDUAL;
                    var notificationaddress = {
                        ZipExtension: null, AddressEntityType: null, IsAddressSame: false, baseEntity: {
                            FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: 0, ModifiedIPAddress: null
                        }, FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                        State: codes.WA, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null,
                        PostalCode: null, County: null, CountyName: null
                    }
                    //$scope.modal.NotificationAddress = notificationaddress;

                    $scope.modal.NotificationAddress.State = $scope.modal.NotificationAddress.State == null || $scope.modal.NotificationAddress.State == "" ? codes.WA : $scope.modal.NotificationAddress.State;
                    $scope.modal.NotificationAddress.Country = $scope.modal.NotificationAddress.Country == null || $scope.modal.NotificationAddress.Country == "" ? codes.USA : $scope.modal.NotificationAddress.Country;

                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.isShowReturnAddress = true;
                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js 
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;

                }, function (response) { });
            }
        }

        else {
            $scope.modal = $rootScope.statementofTerminationModal;
            $scope.isShowReturnAddress = true;
        }
    };

    $scope.continueSave = function (stmtTerminationForm) {
        $scope.validateErrorMessage = true;

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        //wacorpService.nullCheckAddressCompnent($scope.modal, $scope[stmtTerminationForm]);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isStatementOfResination = $scope.modal.IsStatementOfResignationAttached ? $scope.modal.IsStatementOfResignationAttached : false;

        var isCorrespondenceAddressValid = $scope[stmtTerminationForm].CorrespondenceAddress.$valid;

        var isNonCommercialStreetAddressValid = (!$scope.modal.AgentEntity.IsNewAgent ? (($scope.modal.AgentEntity.AgentID != 0 && $scope.modal.AgentEntity.StreetAddress.FullAddress) ? true : (false && !$scope.modal.AgentEntity.IsNoncommercialStreetAddress)) : true)

        $scope.validateNonCommercialStreetAddress = !isNonCommercialStreetAddressValid && !$scope.modal.AgentEntity.IsNoncommercialStreetAddress ? true : false;

        if ($scope[stmtTerminationForm].AuthorizedPersonForm.$valid && $scope[stmtTerminationForm].NotificationAddress.$valid && isAdditionalUploadValid && isStatementOfResination && isCorrespondenceAddressValid && isNonCommercialStreetAddressValid) {
            $scope.validateErrorMessage = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.NotificationAddress.FullAddress = wacorpService.fullAddressService($scope.modal.NotificationAddress);
            $rootScope.statementofTerminationModal = $scope.modal;
            $rootScope.modal = $scope.modal;
            $location.path('/StatementofTerminationReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // back to business search
    $scope.back = function () {
        $location.path('/StatementofTerminationIndex');
    };

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/StatementofTermination';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // StatementofTerminationSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.StatementofTerminationSaveAsDraft, $scope.modelDraft, function (response) {

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.onchangeResgignation = function () {

        $scope.validateErrorMessage = false;
        if (!$scope.modal.IsStatementOfResignationAttached) {
            $scope.modal.IsStatementOfResignationAttached = false;
            $scope.validateErrorMessage = true;
        }
        else{
            $scope.modal.IsStatementOfResignationAttached = true;
        }
    }
});

wacorpApp.controller('statementofTerminationReviewController', function ($scope, $location, $rootScope, wacorpService) {
    //-------------------------------------- Statement of change screen functionality--------------------//
    $scope.Init = function () {
        if (angular.isNullorEmpty($rootScope.statementofTerminationModal))
            $location.path('/StatementofTerminationIndex');
        else
            $scope.modal = $rootScope.statementofTerminationModal;
    };

    $scope.back = function () {
        $rootScope.statementofTerminationModal = $scope.modal;
        $location.path('/StatementofTermination');
    };

    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        //TFS 2751 hiding NP Checkboxes in PDF - geetha testing
        if (typeof (document.getElementById("divNPCheckboxes")) !== 'undefined') {
            $("#divNPCheckboxes").hide();
        };
        //TFS 2751

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // StatementofTerminationAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.StatementofTerminationAddToCart, $scope.modal, function (response) {
            $rootScope.statementofTerminationModal = null;
            $rootScope.modal = null;
            $rootScope.BusinessType = null;
            $location.path('/shoppingCart');
          
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        // StatementofTerminationAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.StatementofTerminationAddToCart, $scope.modal, function (response) {
            $rootScope.statementofTerminationModal = null;
            $rootScope.BusinessType = null;
           // if ($scope.modal.BusinessTransaction.TransactionId > 0)
                $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('commercialStatementofTerminationController', function ($scope, $location, $rootScope, wacorpService) {

    //-------------------------------------------- Business Search list ---------------------------------------//
    // declare scope variables
    $scope.modal = $scope.modal || {};
    $scope.businessSearchCriteria = { IsOnline: true, SearchType: searchTypes.COMMERCIALSTATEMENTOFCHANGE, AgentId: $rootScope.repository.loggedUser.agentid };
    $scope.selectedBusiness = false;
    focus('tblBusinessSearch');

    // navigate to initial report
    $scope.getNavigation = function () {
        $rootScope.BusinessIDs = "";
        angular.forEach($scope.BusinessList, function (business) {
            if (business.isSelect)
                $rootScope.BusinessIDs += business.BusinessID + ",";
        });
        $rootScope.commercialStatementofTerminationModal = null;
        $rootScope.transactionID = null;
        $location.path('/CommercialStatementofTermination');
    };
    // get business list data from server
    function loadbusinessList() {
        $scope.BusinessList = [];
        var data = $scope.businessSearchCriteria
        // getBusinessNames method is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.BusinessList = response.data;
            focus('tblBusinessSearch');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpServicev.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
    }, true);

    $scope.loadbusinessInfo = function () {
        loadbusinessList(); // loadbusinessList method is available in this controller only.
    };

    // select All cart items
    $scope.selectAll = function () {
        angular.forEach($scope.BusinessList, function (business) {
            business.isSelect = [ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf(business.BusinessStatus) >= constant.ZERO ? $scope.modal.selectAll : false;
            $scope.selectedBusiness = $scope.modal.selectAll;
        });
    };

    // item checkbox click
    $scope.selectChange = function (business) {
        var flag = true;
        var isBusinessSelected = false;
        if (business.isSelect) {
            if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf(business.BusinessStatus) < constant.ZERO) {
                business.isSelect = false;
                // Folder Name: app Folder
                // Alert Name: selectedBusiness method is available in alertMessages.js 
                wacorpService.alertDialog(messages.selectedBusiness.replace('{0}', business.BusinessStatus));
            }
        }
        angular.forEach($scope.BusinessList, function (business) {
            if (!business.isSelect) {
                flag = false;
                return;
            }
            if (business.isSelect) {
                isBusinessSelected = true;
                return;
            }
        });
        $scope.modal.selectAll = flag;
        $scope.selectedBusiness = isBusinessSelected;
    };


    //-------------------------------------- Statement of change screen functionality--------------------//

    $scope.Init = function () {
        $scope.validateErrorMessage = false;
        $scope.messages = messages;
        var data = null;
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.commercialStatementofTerminationModal = $rootScope.modal;
            //$rootScope.modal = null;
        }
        if ($rootScope.transactionID > constant.ZERO)
            data = {
                params: {
                    businessID: null, transactionID: $rootScope.transactionID,
                }
            };
        else
            data = {
                params: {
                    businessID: $rootScope.BusinessIDs, transactionID: $rootScope.transactionID
                }
            };
        if (angular.isNullorEmpty($rootScope.commercialStatementofTerminationModal)) {
            //if ($rootScope.BusinessIDs == undefined && $rootScope.transactionID == undefined) {
            //    $location.path('/CommercialStatementofTerminationIndex');
            //}
            //else {
            // CommercialStatementofTerminationCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.CommercialStatementofTerminationCriteria, data, function (response) {
                $scope.modal = response.data;
                $scope.modal.RegisteredAgent = undefined;
                $scope.modal.BusinessIDs = $rootScope.BusinessIDs;
                $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || ResultStatus.INDIVIDUAL;
                $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                $scope.isShowReturnAddress = true;
                var newdata = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
                // getUserDetails method is available in constants.js
                wacorpService.get(webservices.UserAccount.getUserDetails, newdata, function (response) {
                    $scope.newUser = response.data;
                    $scope.modal.PrevRegisteredAgent.AgentType = angular.copy($scope.newUser.Agent.AgentType);
                    $scope.modal.PrevRegisteredAgent.AgentID = angular.copy($scope.newUser.Agent.AgentID);
                    $scope.modal.PrevRegisteredAgent.EntityName = angular.copy($scope.newUser.Agent.EntityName);
                    $scope.modal.PrevRegisteredAgent.FirstName = angular.copy($scope.newUser.FirstName);
                    $scope.modal.PrevRegisteredAgent.LastName = angular.copy($scope.newUser.LastName);
                    $scope.modal.PrevRegisteredAgent.FullName = angular.copy($scope.newUser.FullName);
                    //$scope.modal.PrevRegisteredAgent.FullName = wacorpService.agentFullNameService($scope.newUser);
                    $scope.modal.PrevRegisteredAgent.EmailAddress = angular.copy($scope.newUser.EmailID);
                    $scope.modal.PrevRegisteredAgent.ConfirmEmailAddress = angular.copy($scope.newUser.EmailID);
                    $scope.modal.PrevRegisteredAgent.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                    $scope.modal.PrevRegisteredAgent.StreetAddress = $scope.newUser.Address;
                    $scope.modal.PrevRegisteredAgent.MailingAddress = $scope.newUser.AltAddress;
                })
                $location.path('/CommercialStatementofTermination');
                if ($scope.modal.IsActiveFilingExist) {
                    //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js 
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }
            }, function (response) { });
            //}
        }
        else {
            $scope.modal = $rootScope.commercialStatementofTerminationModal;
            $scope.isShowReturnAddress = true;
        }
    };

    $scope.continueSave = function (stmtTerminationForm) {

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[stmtTerminationForm]);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isCorrespondenceAddressValid = $scope[stmtTerminationForm].CorrespondenceAddress.$valid;

        var isRegisteredAgentValidStates = !$scope.modal.PrevRegisteredAgent.StreetAddress.IsInvalidState && !$scope.modal.PrevRegisteredAgent.MailingAddress.IsInvalidState && !$scope.modal.PrevRegisteredAgent.StreetAddress.invalidPoBoxAddress;

        $scope.validateErrorMessage = true;
        if ($scope[stmtTerminationForm].AuthorizedPersonForm.$valid && isAdditionalUploadValid && $scope[stmtTerminationForm].AttestationForm.$valid && isCorrespondenceAddressValid && isRegisteredAgentValidStates) {
            $scope.validateErrorMessage = false;
            $scope.modal.PrevRegisteredAgent.StreetAddress.FullAddress = $scope.modal.PrevRegisteredAgent.StreetAddress.StreetAddress1 == '' ? '' : $scope.modal.PrevRegisteredAgent.StreetAddress.FullAddress;
            $scope.modal.PrevRegisteredAgent.MailingAddress.FullAddress = $scope.modal.PrevRegisteredAgent.MailingAddress.StreetAddress1 == ''?'':$scope.modal.PrevRegisteredAgent.MailingAddress.FullAddress;
            $rootScope.commercialStatementofTerminationModal = $scope.modal;
            $location.path('/CommercialStatementofTerminationReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // back to business search
    $scope.back = function () {
        $location.path('/CommercialStatementofTermination');
    };
    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        //$scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/CommercialStatementofTermination';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CommercialStatementofTerminationSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CommercialStatementofTerminationSaveAsDraft, $scope.modelDraft, function (response) {

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.onAttestationChange = function () {

        $scope.validateErrorMessage = false;
        if(!$scope.modal.IsAgentAttestation){
            $scope.modal.IsAgentAttestation = false;
            $scope.validateErrorMessage = true;
        }
        else{
            $scope.modal.IsAgentAttestation = true;
        }

        if (!$scope.modal.IsAnotherAgentAttestation) {
            $scope.modal.IsAnotherAgentAttestation = false;
            $scope.validateErrorMessage = true;
        }
        else {
            $scope.modal.IsAnotherAgentAttestation = true;
        }

    }
});

wacorpApp.controller('commercialStatementofTerminationReviewController', function ($scope, $location, $rootScope, wacorpService) {
    //-------------------------------------- Statement of change screen functionality--------------------//
    $scope.Init = function () {
         if (angular.isNullorEmpty($rootScope.commercialStatementofTerminationModal))
            $location.path('/CommercialStatementofTerminationIndex');
        else
            $scope.modal = $rootScope.commercialStatementofTerminationModal;
    };

    $scope.back = function () {
        $rootScope.commercialStatementofTerminationModal = $scope.modal;
        $location.path('/CommercialStatementofTermination');
    };

    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CommercialStatementofTerminationAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CommercialStatementofTerminationAddToCart, $scope.modal, function (response) {
            $rootScope.commercialStatementofTerminationModal = null;
            $rootScope.modal = null;
            $rootScope.BusinessType = null;
            $location.path('/shoppingCart');
            
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        // CommercialStatementofTerminationAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CommercialStatementofTerminationAddToCart, $scope.modal, function (response) {
            $rootScope.commercialStatementofTerminationModal = null;
            $rootScope.BusinessType = null;
           // if ($scope.modal.BusinessTransaction.TransactionId > 0)
            $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('commercialListingStatementController', function ($scope, $location, $rootScope, wacorpService, $timeout) {
    //-------------------------------------- Commercial Listing Statement--------------------//

    var agentResetScope = {
        AgentID: constant.ZERO, EntityName: null, FirstName: null, LastName: null, IsNonCommercial: false, EmailAddress: null,
        ConfirmEmailAddress: null, AgentType: ResultStatus.INDIVIDUAL, AgentTypeID: constant.ZERO,
        StreetAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
            baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null, State: codes.WA, OtherState: null,
            Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        MailingAddress: {
            ZipExtension: null, AddressEntityType: null, IsAddressSame: false,
            baseEntity: { FilerID: constant.ZERO, UserID: constant.ZERO, CreatedBy: constant.ZERO, IPAddress: null, ModifiedBy: constant.ZERO, ModifiedIPAddress: null },
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null, State: codes.WA, OtherState: null,
            Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        IsUserRegisteredAgent: false, PhoneNumber: null, IsRegisteredAgentConsent: true, Title: null, IsSameAsMailingAddress: false,//TFS 1143  original -> IsRegisteredAgentConsent: false
        CreatedBy: null, AgentCreatdDate: null, AgentCreatdIP: null, IsNewAgent: false
    };

    $scope.Init = function () {
        $scope.page = constant.ZERO;
        $scope.pagesCount = constant.ZERO;
        $scope.totalCount = constant.ZERO;
        $scope.searchType = $scope.searchType || "";
        $scope.businessSearchCriteria = { Type: searchTypes.BUSINESSNO, ID: "", IsSearch: true, PageID: constant.ONE, PageCount: constant.TEN, BusinessTypeId: constant.ZERO, IsOnline: true, SearchType: "CRARepresentedEntities", isSearchClick: false };
        $scope.selectedBusiness = null;
        $scope.selectedBusinessID = constant.ZERO;
        $scope.search = loadbusinessList;
        $scope.searchval = '';
        $scope.isButtonSerach = false;
        $scope.sectionName = $scope.sectionName || '';
        focus("searchField");
        $scope.isRepresentedShowErrorFlag = false;




        $scope.validateErrorMessage = false;
        $scope.isCRACountValidate = false;
        $scope.isLookupClicked = false;
        $scope.craNameAvailableMsg = false;
        $scope.messages = messages;
        $scope.CountriesList = [];
        $scope.StatesList = [];
        $scope.businessTypes = [];
        //$scope.CountryChangeDesc();
        $scope.unitedstates = "UNITED STATES";
        var data = null;

        var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
            $scope.CountriesList = response.data;
        }, function (response) {
        });

        var lookupStatesParams = { params: { name: 'JurisdictionStates' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
            $scope.StatesList = response.data;
        }, function (response) {
        });

        var config = { params: { name: 'AdvancedBusinessType' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.Lookup.getLookUpData, config, function (response) { $scope.businessTypes = response.data; });

        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.commercialListingStatementModal = $rootScope.modal;
            //$rootScope.modal = null;
        }
        if ($rootScope.transactionID > constant.ZERO)
            data = {
                params: {
                    agentID: null, transactionID: $rootScope.transactionID,
                }
            };
        else
            data = {
                params: {
                    agentID: $rootScope.repository.loggedUser.agentid, transactionID: $rootScope.transactionID
                }
            };
        if (angular.isNullorEmpty($rootScope.commercialListingStatementModal)) {
            // CommercialListingStatementCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.CommercialListingStatementCriteria, data, function (response) {
                $scope.modal = response.data;
                $scope.modal.RegisteredAgent.AgentType = $scope.modal.RegisteredAgent.AgentType || ResultStatus.INDIVIDUAL;
                $scope.modal.RegisteredAgent.IsNewAgent = true;
                $scope.isUserAgent = true;
                $scope.modal.RegisteredAgent.IsNonCommercial = false;
                $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || ResultStatus.INDIVIDUAL;
                $scope.modal.RegisteredAgent.BusinessTypeID = ($scope.modal.RegisteredAgent.BusinessTypeID == null || $scope.modal.RegisteredAgent.BusinessTypeID == "0") ? "" : $scope.modal.RegisteredAgent.BusinessTypeID.toString();

                $scope.modal.RegisteredAgent.JurisdictionDesc = angular.isNullorEmpty($scope.modal.RegisteredAgent.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.RegisteredAgent.JurisdictionDesc;
                $scope.modal.RegisteredAgent.Jurisdiction = ($scope.modal.RegisteredAgent.Jurisdiction == null || $scope.modal.RegisteredAgent.Jurisdiction == "0") ? "" : $scope.modal.RegisteredAgent.Jurisdiction.toString();
                $scope.modal.RegisteredAgent.JurisdictionCountry = ($scope.modal.RegisteredAgent.JurisdictionCountry == null || $scope.modal.RegisteredAgent.JurisdictionCountry == 0 || $scope.modal.RegisteredAgent.JurisdictionCountry == "") ? usaCode : $scope.modal.RegisteredAgent.JurisdictionCountry.toString();
                $scope.modal.RegisteredAgent.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.RegisteredAgent.JurisdictionCountry);
                $scope.modal.RegisteredAgent.JurisdictionState = ($scope.modal.RegisteredAgent.JurisdictionState == null || $scope.modal.RegisteredAgent.JurisdictionState == 0) ? null : $scope.modal.RegisteredAgent.JurisdictionState.toString();

                $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                $scope.isShowReturnAddress = true;
                if ($scope.modal.BusinessTransaction.TransactionId == 0)
                    $scope.getAgentUserDetails(true); // getAgentUserDetails method is available in this controller only.
            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.commercialListingStatementModal;
            $scope.modal.RegisteredAgent.BusinessTypeID = $scope.modal.RegisteredAgent.BusinessTypeID.toString();
            $scope.modal.RegisteredAgent.Jurisdiction = $scope.modal.RegisteredAgent.Jurisdiction.toString();
            $scope.modal.RegisteredAgent.JurisdictionCountry = $scope.modal.RegisteredAgent.JurisdictionCountry.toString();
            $scope.modal.RegisteredAgent.JurisdictionState = $scope.modal.RegisteredAgent.JurisdictionState.toString();
            $scope.isShowReturnAddress = true;
        }
    };

    $scope.selectedJurisdiction = function (items, selectedVal) {
        var result = "";
        angular.forEach(items, function (item) {
            if (selectedVal == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }

    //$scope.CountryChangeDesc = function () {
    //    $scope.modal.RegisteredAgent.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.RegisteredAgent.JurisdictionCountry);

    //};

    //Copy the Street  address to  Mailing Address
    $scope.CopyAgentMailingFromStreet = function () {
        if ($scope.modal.RegisteredAgent.IsSameAsMailingAddress)
            angular.copy($scope.modal.RegisteredAgent.StreetAddress, $scope.modal.RegisteredAgent.MailingAddress);
        else
            angular.copy(agentResetScope.MailingAddress, $scope.modal.RegisteredAgent.MailingAddress);

        if ($scope.modal.RegisteredAgent.IsSameAsMailingAddress)
            $scope.$broadcast("IsMailingRAAddress", true);
        else if (!$scope.modal.RegisteredAgent.IsSameAsMailingAddress)
            $scope.$broadcast("IsMailingRAAddress", false);
    };

    //Clear the Agent Information
    $scope.clearAgent = function () {
        $scope.modal.RegisteredAgent = angular.copy(agentResetScope);
        $scope.isUserAgent = false;
    };

    //Get User details during select user as Iam register agent
    $scope.getAgentUserDetails = function (isUserAgent) {
        if (isUserAgent) {
            var data = { params: { membershipid: $rootScope.repository.loggedUser.membershipid } };
            // getUserDetails method is available in constants.js
            wacorpService.get(webservices.UserAccount.getUserDetails, data, function (response) {
                $scope.newUser = response.data;

                $scope.modal.RegisteredAgent.AgentType = (response.data.FilerTypeId == "FI" ? ($scope.newUser.isIndividual == false ? "E" : "I") : response.data.Agent.AgentType);
                $scope.modal.RegisteredAgent.FirstName = angular.copy($scope.newUser.FirstName);
                $scope.modal.RegisteredAgent.LastName = angular.copy($scope.newUser.LastName);
                $scope.modal.RegisteredAgent.EntityName = angular.copy($scope.newUser.Agent.OrganizationName);
                $scope.modal.RegisteredAgent.EmailAddress = angular.copy($scope.newUser.EmailID);
                $scope.modal.RegisteredAgent.ConfirmEmailAddress = angular.copy($scope.newUser.ConfirmEmailAddress);
                $scope.modal.RegisteredAgent.PhoneNumber = angular.copy($scope.newUser.PhoneNumber);
                $scope.modal.RegisteredAgent.StreetAddress = ($scope.newUser.Address.State == codes.WA) ? angular.copy($scope.newUser.Address) : angular.copy(agentResetScope.MailingAddress);
                $scope.modal.RegisteredAgent.MailingAddress = ($scope.newUser.AltAddress.State == codes.WA) ? angular.copy($scope.newUser.AltAddress) : angular.copy(agentResetScope.StreetAddress);
                $scope.isUserAgent = true;
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data.Message);
            });
        }
        else {
            $scope.modal.RegisteredAgent = angular.copy(agentResetScope);
        }
        $scope.modal.RegisteredAgent.IsNewAgent = true;
        $scope.modal.RegisteredAgent.IsNonCommercial = false;
    };

    //Continue to save to cart
    $scope.continueSave = function (listingStatementForm) {
        $scope.isShowReturnAddress = true;
        $scope.validateErrorMessage = true;

        $scope.isRepresentedShowErrorFlag = false;


        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[listingStatementForm]);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isJurisdictionFormValid = ($scope.modal.RegisteredAgent.AgentType == 'E' ? $scope[listingStatementForm].JurisdictionForm.$valid : true);

        var isBusinessTypeFormValid = ($scope.modal.RegisteredAgent.AgentType == 'E' ? $scope[listingStatementForm].BusinessTypeForm.$valid : true);

        var isRegisteredAgentValidStates = !$scope.modal.RegisteredAgent.StreetAddress.IsInvalidState && !$scope.modal.RegisteredAgent.MailingAddress.IsInvalidState && !$scope.modal.RegisteredAgent.StreetAddress.invalidPoBoxAddress;

        var craNameValid = !$scope.isCRACountValidate;

        var craLookupValid = $scope.isLookupClicked;

        var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.RegisteredAgent.JurisdictionCountry);

        $scope.modal.RegisteredAgent.BusinessType = $scope.selectedJurisdiction($scope.businessTypes, $scope.modal.RegisteredAgent.BusinessTypeID);

        var isCorrespondenceAddressValid = $scope[listingStatementForm].CorrespondenceAddress.$valid;

        if (countryDesc == $scope.unitedstates) {
            var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.RegisteredAgent.JurisdictionState);
            $scope.modal.RegisteredAgent.Jurisdiction = angular.copy($scope.modal.RegisteredAgent.JurisdictionState);
            $scope.modal.RegisteredAgent.JurisdictionDesc = angular.copy(stateDesc);
            $scope.modal.RegisteredAgent.JurisdictionStateDesc = angular.copy(stateDesc);
            $scope.modal.RegisteredAgent.JurisdictionCountryDesc = angular.copy(countryDesc);
            $scope.modal.RegisteredAgent.JurisdictionCategory = 'S';
        }
        else {
            $scope.modal.RegisteredAgent.Jurisdiction = angular.copy($scope.modal.RegisteredAgent.JurisdictionCountry);
            $scope.modal.RegisteredAgent.JurisdictionDesc = angular.copy(countryDesc);
            $scope.modal.RegisteredAgent.JurisdictionCountryDesc = angular.copy(countryDesc);
            $scope.modal.RegisteredAgent.JurisdictionStateDesc = null;
            $scope.modal.RegisteredAgent.JurisdictionCategory = 'C';
        }

        if ($scope[listingStatementForm].$valid && isJurisdictionFormValid && isBusinessTypeFormValid && craNameValid && craLookupValid
            && isAdditionalUploadValid && isCorrespondenceAddressValid && isRegisteredAgentValidStates) {
            $scope.validateErrorMessage = false;

            //$scope.modal.UBINumber = $scope.modal.RegisteredAgent.UBINumber;//TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
            $scope.modal.BusinessName = $scope.modal.RegisteredAgent.EntityName;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.RegisteredAgent.MailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.RegisteredAgent.MailingAddress);
            $scope.modal.RegisteredAgent.StreetAddress.FullAddress = wacorpService.fullAddressService($scope.modal.RegisteredAgent.StreetAddress);
            $scope.modal.RegisteredAgent.IsNewAgent = true;
            $scope.modal.RegisteredAgent.IsNonCommercial = false;
            $rootScope.commercialListingStatementModal = $scope.modal;
            $location.path('/CommercialListingStatementReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {

        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        //$scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;//TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
        $scope.modal.OnlineNavigationUrl = '/CommercialListingStatement';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });
        // CommercialListingStatementSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CommercialListingStatementSaveAsDraft, $scope.modelDraft, function (response) {

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
    //$scope.setPastedUBI = function (e) {
    //    var pastedText = "";
    //    if (typeof e.originalEvent.clipboardData !== "undefined") {
    //        pastedText = e.originalEvent.clipboardData.getData('text/plain');
    //        pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
    //        $scope.modal.RegisteredAgent.UBINumber = pastedText;
    //        e.preventDefault();
    //    } else {
    //        $timeout(function () {
    //            pastedText = angular.element(e.currentTarget).val();
    //            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
    //            $scope.modal.RegisteredAgent.UBINumber = pastedText;
    //        });
    //    }
    //};
    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036

    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
    //$scope.setUBILength = function (e) {
    //    if ($scope.modal.RegisteredAgent.UBINumber != undefined && $scope.modal.RegisteredAgent.UBINumber != null && $scope.modal.RegisteredAgent.UBINumber!="" && $scope.modal.RegisteredAgent.UBINumber.length >= 9) {
    //        // Allow: backspace, delete, tab, escape, enter and .
    //        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
    //            // Allow: Ctrl+A, Command+A
    //            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
    //            // Allow: home, end, left, right, down, up
    //            (e.keyCode >= 35 && e.keyCode <= 40)) {
    //            // let it happen, don't do anything
    //            return;
    //        }
    //        // Ensure that it is a number and stop the keypress
    //        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    //            e.preventDefault();
    //        }
    //        e.preventDefault();
    //    }

    //};
    //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036

    $scope.isLookupValid = false;

    $scope.searchCommercialAgents = function searchCommercialAgents(registerAgentForm) {
        $scope.isCRACountValidate = false;
        $scope.isLookupClicked = true;

        if ($scope.modal.RegisteredAgent.AgentType) {
            if ($scope.modal.RegisteredAgent.AgentType == 'E' && $scope.modal.RegisteredAgent.EntityName == undefined) {
                $scope.isLookupValid = true;
                return false;
            }
            else if ($scope.modal.RegisteredAgent.AgentType == 'I' && ($scope.modal.RegisteredAgent.FirstName == undefined || $scope.modal.RegisteredAgent.LastName == undefined)) {
                $scope.isLookupValid = true;
                return false;
            }
            else {
                $scope.isLookupValid = false;
                var criteria = {
                    FirstName: ($scope.modal.RegisteredAgent.AgentType == 'E' ? '' : $scope.modal.RegisteredAgent.FirstName || ''), LastName: ($scope.modal.RegisteredAgent.AgentType == 'E' ? '' : $scope.modal.RegisteredAgent.LastName || ''), BusinessName: ($scope.modal.RegisteredAgent.AgentType == 'E' ? $scope.modal.RegisteredAgent.EntityName || '' : ''),
                };
                wacorpService.post(webservices.Common.getCommercialAgentAvailableOrNot, criteria,
                    function (response) {
                        if (response.data != null) {
                            $scope.modal.RegisteredAgent.TotalCount = angular.copy(response.data);

                            if ($scope.modal.RegisteredAgent.TotalCount != '0' && $scope.modal.RegisteredAgent.TotalCount != undefined) {
                                $scope.isCRACountValidate = true;
                                $scope.craNameAvailableMsg = false;
                            }
                            else {
                                $scope.isCRACountValidate = false;
                                $scope.craNameAvailableMsg = true;
                            }
                        }
                        else
                            // Folder Name: app Folder
                            // Alert Name: noDataFound method is available in alertMessages.js 
                            wacorpService.alertDialog($scope.messages.noDataFound);
                    },
                    function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data.Message);
                    }
                );
            }
        }
    }

    $scope.enableIndividualLookup = function () {
        if ($scope.modal.RegisteredAgent.AgentType == "I") {
            $scope.isLookupClicked = false;
            $scope.craNameAvailableMsg = false;
            $scope.isCRACountValidate = false;
        }
    }

    $scope.enableEntityLookup = function () {
        if ($scope.modal.RegisteredAgent.AgentType == "E" && $scope.modal.RegisteredAgent.EntityName != "") {
            $scope.isLookupClicked = false;
            $scope.craNameAvailableMsg = false;
            $scope.isCRACountValidate = false;
        }
    }



    // Business Search

    // search business list
    $scope.searchBusiness = function () {

        if ($scope.businessSearchCriteria.ID == "" || $scope.businessSearchCriteria.ID == null) {
            $scope.isRepresentedShowErrorFlag = true;
            return false;
        }
        else {
            $scope.isRepresentedShowErrorFlag = false;
            //if ($scope[searchform].$valid) {
            $scope.businessSearchCriteria.isSearchClick = true;
            $scope.isShowErrorFlag = false;
            $scope.isButtonSerach = true;
            $scope.selectedBusiness = null;
            $rootScope.selectedBusiness = null;
            $rootScope.selectedBusinessID = constant.ZERO;
            $scope.selectedBusinessID = constant.ZERO;
            loadbusinessList(constant.ZERO); // loadbusinessList method is available in this controller only.
            //}
        }
    };
    //clear text on selecting radio button
    $scope.cleartext = function () {
        $scope.businessSearchCriteria.ID = null;
    };

    // clear fields
    $scope.clearFun = function () {
        $scope.businessSearchCriteria.ID = "";
        $scope.businessSearchCriteria.isSearchClick = false;
        $scope.isRepresentedShowErrorFlag = false;
    };

    // cancel popup
    $scope.cancelFun = function () {
        $("#divSearchResult").modal('toggle');
        $scope.selectedBusiness = null;
        $rootScope.selectedBusiness = null;
        $rootScope.selectedBusinessID = constant.ZERO;
        $scope.selectedBusinessID = constant.ZERO;
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
        $scope.selectedBusinessID = business.BusinessID;
        $rootScope.selectedBusinessID = $scope.selectedBusinessID;
        $rootScope.selectedBusiness = $scope.selectedBusiness;
    };

    $scope.submitBusiness = function () {
        $scope.isRepresentedShowErrorFlag = false;
        if ($scope.selectedBusiness && $scope.selectedBusiness.BusinessID != constant.ZERO) {
            if ($scope.modal.CRABusinessList.length == constant.ZERO) {
                $scope.modal.CRABusinessList.push($scope.selectedBusiness);
                $("#divSearchResult").modal('toggle');
            }
            else {
                var k = 0;
                $scope.modal.CRABusinessList.forEach(function (element) {
                    if (element.BusinessID == $scope.selectedBusiness.BusinessID) {
                        k = k + 1;
                    }
                });

                if (k > 0) {
                    // Folder Name: app Folder
                    // Alert Name: representedEntityExists method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.representedEntityExists);
                    return false;
                }
                else {
                    $scope.modal.CRABusinessList.push($scope.selectedBusiness);
                    $("#divSearchResult").modal('toggle');
                    k = 0;                  
                }
            }
        }
    };

    //Delete business
    $scope.deleteBusiness = function (selectedBusiness) {
        // Folder Name: app Folder
        // Alert Name: ConfirmMessage method is available in alertMessages.js 
        wacorpService.confirmOkCancel($scope.messages.Confirm.ConfirmMessage, function () {
            var index = $scope.modal.CRABusinessList.indexOf(selectedBusiness);
            $scope.modal.CRABusinessList.splice(index, 1);
        });
    };


    // get business list data from server
    function loadbusinessList(page) {
        $scope.isRepresentedShowErrorFlag = false;
        page = page || constant.ZERO;
        $scope.businessSearchCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        $scope.selectedBusiness = null;

        var data = angular.copy($scope.businessSearchCriteria);
        $scope.isButtonSerach = page == 0;
        data.ID = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID : $scope.searchval);
        // getBusinessNames method is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.selectedBusiness = null;

            $rootScope.searchCriteria = {
                searList: response, page: page,
                searchType: $scope.businessSearchCriteria.Type,
                searchValue: $scope.businessSearchCriteria.ID,
                pagesCount: $scope.pagesCount,

            };

            loadList($rootScope.searchCriteria); // loadList method is available in this controller only.
            if (page == constant.ZERO)
                $("#divSearchResult").modal('toggle');
        }, function (response) {
            $scope.selectedBusiness = null;
            $scope.selectedBusinessID = constant.ZERO;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });

    }

    // select search type
    $scope.selectSearchType = function () {
        $scope.businessSearchCriteria.ID = "";
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == constant.ZERO) {
            $scope.totalCount = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.page = constant.ZERO;
        }
    }, true);

    $scope.setPastedUBISearch = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.businessSearchCriteria.ID = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.businessSearchCriteria.ID = pastedText;
            });
        }
    };

    function loadList(responseData, flag) {

        var response = responseData.searList;
        var page = responseData.page;
        if (flag) {
            $scope.businessSearchCriteria.Type = responseData.searchType;
            $scope.businessSearchCriteria.ID = responseData.searchValue;
        }

        $scope.BusinessList = response.data;
        if ($scope.isButtonSerach && response.data.length > 0) {
            var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
            var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                        ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
            $scope.pagesCount = response.data.length < $scope.businessSearchCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
            $scope.totalCount = totalcount;
            $scope.searchval = angular.copy($scope.isButtonSerach ? $scope.businessSearchCriteria.ID : $scope.searchval);

            //Putting all the code in rootscope for Back Button Purpose
            $rootScope.pagesCount = $scope.pagesCount;
            $rootScope.totalCount = $scope.totalCount;
            $rootScope.businessSearchCriteria = $scope.businessSearchCriteria;
            $rootScope.searchval = $scope.searchval
        }
        //Getting Data from rootscope for Back Button Purpose
        if (response.data.length > 0) {
            $scope.totalCount = $rootScope.totalCount;
            $scope.pagesCount = $rootScope.pagesCount;
            $scope.businessSearchCriteria = $rootScope.businessSearchCriteria;
            $scope.searchval = $rootScope.searchval;
        }

        $scope.selectedBusinessID = $rootScope.selectedBusinessID;
        $scope.selectedBusiness = $rootScope.selectedBusiness;
        $scope.page = page;
        $scope.BusinessListProgressBar = false;
        focus("tblBusinessSearch");
    }


    if ($rootScope.searchCriteria) {
        // $scope.isButtonSerach = true;
        loadList($rootScope.searchCriteria, true); // loadList method is available in this controller only.
        //  $scope.isButtonSerach = false;
        $scope.businessSearchCriteria.isSearchClick = true;
    }

    $scope.setUBILengthSearch = function (e) {
        if ($scope.businessSearchCriteria.ID != undefined && $scope.businessSearchCriteria.ID != null && $scope.businessSearchCriteria.ID != "" && $scope.businessSearchCriteria.ID.length >= 9)
        {
            if (e.which != 97) {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                    // Allow: Ctrl+A, Command+A
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right, down, up
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
                e.preventDefault();
            }
        }
    };

    //select the agent type Individual
    $scope.selectAgentTypeIndividual = function () {
        $scope.modal.RegisteredAgent.EntityName = '';
    };

    $scope.checkRAEmail = function () {
        if ($scope.listingStatementForm.registerAgentForm.EmailID.$viewValue == "" && ($scope.modal.RegisteredAgent.EmailAddress == "" || $scope.modal.RegisteredAgent.EmailAddress == null || $scope.modal.RegisteredAgent.EmailAddress == undefined)) {
            //Here we are calling the method which is declared in another controller(EmailOption.js)
            $rootScope.$broadcast('onEmailEmpty');
        }
    };
        //to clear RA mailing Address when Street address is modified
    var clearCommercialRAMailingData = $scope.$on("CommercialRAStreetAddress", function (evt, data) {
        if ($scope.modal.RegisteredAgent.IsSameAsMailingAddress) {
            if (wacorpService.compareAddress($scope.modal.RegisteredAgent.StreetAddress,$scope.modal.RegisteredAgent.MailingAddress))
            {
                $scope.modal.RegisteredAgent.IsSameAsMailingAddress = false;
                $scope.CopyAgentMailingFromStreet();
            }
        }
        evt.defaultPrevented = true;
    });
    $scope.$on('$destroy', clearCommercialRAMailingData);

});

wacorpApp.controller('commercialListingStatementReviewController', function ($scope, $location, $rootScope, wacorpService) {
    //-------------------------------------- Statement of change screen functionality--------------------//
    $scope.Init = function () {
        if (angular.isNullorEmpty($rootScope.commercialListingStatementModal))
            $location.path('/CommercialListingStatement');
        else
            $scope.modal = $rootScope.commercialListingStatementModal;
    };
    $scope.back = function () {
        $rootScope.commercialListingStatementModal = $scope.modal;
        $location.path('/CommercialListingStatement');
    };

    $scope.AddToCart = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.FilerId = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CommercialListingStatementAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CommercialListingStatementAddToCart, $scope.modal, function (response) {
            $rootScope.commercialListingStatementModal = null;
            $rootScope.modal = null;
            $location.path('/shoppingCart');
           
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.FilerId = $rootScope.repository.loggedUser.userid;
        // CommercialListingStatementAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CommercialListingStatementAddToCart, $scope.modal, function (response) {
            $rootScope.commercialListingStatementModal = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
            $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

/*
Author      : Kishore Penugonda
File        : copyRequestController.js
Description : print,download the certificates and payment
*/
wacorpApp.controller('copyRequestController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, $filter) {

    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    $scope.modalEntity = { CertifiedCopies: [], BusinessTransaction: {}, BusinessInfo: {}, UserId: 0, TotalAmount: 0, FilingTypeId: 0 };
    $scope.modal = { CertifiedCopies: [], BusinessTransaction: {}, BusinessInfo: {}, UserId: 0, TotalAmount: 0, FilingTypeId: 0 };
    $scope.businessSearchCriteria = { Type: searchTypes.BUSINESSNO, ID: "", IsSearch: true, PageID: 1, PageCount: 10, BusinessTypeId: 0, IsOnline: true, SearchType: "", isSearchClick: false };
    $scope.filingAmount = WAFeeProvider.AGENTREGISTRATIONFEE;
    $scope.surChargeAmt = 0;
    $scope.totalNoOfPages = 0;
    $scope.surChargeAmt_1 = 0;
    $scope.totalIterationsCount = 0;
    $scope.transactionDocumentsList = [];
    $scope.SearchType = "searchCorporations";
    $scope.CertificateOfFactRequired = false;
    /* --------Business Search Functionality------------- */
    function getNavigation() {
        //if (["Active", "Delinquent", "Inactive"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
        $location.path('/CopyRequest/' + $rootScope.selectedBusinessID);
        //}
        //else {
        //    wacorpService.alertDialog('Selected business is ' + $scope.selectedBusiness.BusinessStatus);
        //}
    }

    $scope.initRCSearch = function () {
        $scope.navCopyRequest();
    }

    /* --------Certified Copies------------- */
    $scope.initCopyRequest = function () {
        $scope.loadBusinessFilings(); // loadBusinessFilings method is available in this controller only.
    };

    $scope.editCartFilings = function () {
        var data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 0 } };
        wacorpService.get(webservices.OnlineFiling.getCopyRequestBusinessCriteria, data, function (response) {
            $scope.selectedModal = response.data;
            $scope.loadBusinessFilings(response.data.BusinessID);// loadBusinessFilings method is available in this controller only.
        }, function (response) { });
    };

    $scope.loadBusinessFilings = function () {
        var data = null;
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            // $scope.modal = $rootScope.modal;
            $rootScope.modal = $rootScope.modal;
        }
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 110 is RECORDS/CERTIFICATE REQUEST
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 110 } };
        else
            data = { params: { businessID: $routeParams.id, transactionID: null, filingTypeID: 110, cftType: $routeParams.cftType } };

        $scope.modal.CFTType = $routeParams.cftType;
        // getCopyRequestBusinessCriteria method is available in constants.js
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            wacorpService.get(webservices.OnlineFiling.getCopyRequestBusinessCriteria, data, function (response) {
                if (response.data != null) {
                    $rootScope.cftType = null;
                    $scope.modal = response.data;
                    $rootScope.modal = response.data;
                    if ($rootScope.modal != null || $rootScope.modal != undefined) {
                        $scope.modal.OnlineCartDraftID = $rootScope.modal.OnlineCartDraftID;
                        $scope.modal.CorrespondenceAddress = $rootScope.modal.CorrespondenceAddress;
                    }

                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;

                    //$scope.addFilingToList($scope.modal);
                    // here BusinessTypeID = 5 is CERTIFIED COPIES
                    $scope.modal.BusinessInfo.BusinessTypeID = 110;
                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    $scope.modal.BusinessTransaction.OrganizationType = $scope.modal.CFTType;
                    if ($rootScope.transactionID > 0) {
                        $scope.setSelectedFilings(response.data.CertifiedCopies); // setSelectedFilings method is available in this controller only.
                    }
                    else if ($rootScope.modal.CertifiedCopies.length != 0) {
                        if ($rootScope.modal != null || $rootScope.modal != undefined) {
                            $scope.modal = $rootScope.modal;
                        }
                        $scope.setSelectedFilings($rootScope.modal.CertifiedCopies); // setSelectedFilings method is available in this controller only.
                    }

                    if ($scope.modal.BusinessInfo.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js 
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                    $scope.modal.BusinessInfo.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.BusinessInfo.OldDBABusinessName) ? $scope.modal.BusinessInfo.OldDBABusinessName : $scope.modal.BusinessInfo.DBABusinessName;
                }
            }, function (businessFilingResponse) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(businessFilingResponse.data);
            });
        }
        else
        {
            $scope.modal = $rootScope.modal;

            //To make Certificate Of Fact Mandetory
            var isCertificateOFFactReq = false;
            angular.forEach($scope.modal.CertifiedCopies, function (selectedItem) {
                if (selectedItem != null && selectedItem != undefined && selectedItem.FilingTypeName == 'CERTIFICATE OF FACT' && selectedItem.CopyRequest > 0) {
                    isCertificateOFFactReq = true;
                }
            });
            if (isCertificateOFFactReq) {
                $scope.CertificateOfFactRequired = true;
            }
            else {
                $scope.CertificateOfFactRequired = false;
            }
        }
    };
    $scope.addFilingToList = function (modal) {
        var newBusinessFiling = angular.copy(modal.BusinessFiling);
        //newBusinessFiling.FilingNumber = 0;
        //newBusinessFiling.NumberOfPages = 0;
        //newBusinessFiling.Amount = 0;
        //if (modal.BusinessInfo.BusinessCategory == "DOMESTIC ENTITY") {
        //    newBusinessFiling.FilingTypeID = 26;
        //    newBusinessFiling.FilingTypeName = "Certificate of Existance (Short Form)";
        //}
        //else if (modal.BusinessInfo.BusinessCategory == "FOREIGN ENTITY") {
        //    newBusinessFiling.FilingTypeID = 25;
        //    newBusinessFiling.FilingTypeName = "Certificate of Registration (Long Form)";
        //}
        //else
        //{
        //    newBusinessFiling.FilingTypeName = "";
        //}
        //modal.CertifiedCopies.unshift(newBusinessFiling);
    }

    $scope.setSelectedFilings = function (items) {
        if ($scope.modal.CFTType != undefined && $scope.modal.CFTType != "") {
            $scope.modal.BusinessInfo.BusinessID = $scope.modal.CharitiesEntityInfo.CFTId
        }
        else {
            $scope.modal.BusinessInfo.BusinessID = $scope.modal.BusinessInfo.BusinessID;
        }
        var businessfilingconfig = { params: { businessId: $scope.modal.BusinessInfo.BusinessID, cftType: $scope.modal.CFTType } };
        // getAllCertifiedCopies method is available in constants.js
        wacorpService.get(webservices.CopyRequest.getAllCertifiedCopies, businessfilingconfig,
            function (response) {
                $scope.modal.CertifiedCopies = response.data;
                $scope.addFilingToList($scope.modal);
                for (var i = 0; i < items.length; i++) {
                    for (var j = 0; j < $scope.modal.CertifiedCopies.length; j++) {
                        if (items[i].FilingNumber == $scope.modal.CertifiedCopies[j].FilingNumber && items[i].FilingTypeName == $scope.modal.CertifiedCopies[j].FilingTypeName) {
                            $scope.modal.CertifiedCopies[j].CopyRequest = items[i].CopyRequest;
                            $scope.modal.CertifiedCopies[j].ApostilleCopies = items[i].ApostilleCopies;
                            $scope.modal.CertifiedCopies[j].Comments = items[i].Comments;
                            $scope.GetFilingFee(items[i].FilingNumber);
                            break;
                        }
                    }
                }

                //To make Certificate Of Fact Mandetory
                var isCertificateOFFactReq = false;
                angular.forEach($scope.modal.CertifiedCopies, function (selectedItem) {
                    if (selectedItem != null && selectedItem != undefined && selectedItem.FilingTypeName == 'CERTIFICATE OF FACT' && selectedItem.CopyRequest > 0) {
                        isCertificateOFFactReq = true;
                    }
                });
                if (isCertificateOFFactReq) {
                    $scope.CertificateOfFactRequired = true;
                }
                else {
                    $scope.CertificateOfFactRequired = false;
                }
            },
        function (response) {

        });
    }

    $scope.Continue = function () {
        $scope.validateErrorMessage = true;
        var isCorrespondenceAddress = ($scope.CorrespondenceAddress.$valid);
        //var isCertificateOfFactRequired = true;
        //if ($scope.CertificateOfFactRequired == true) {
        //    isCertificateOfFactRequired = $scope.CopyRequest.txtCertificateOfFactComments.$valid;
        //}
        var isCertificateOfFactRequired = $scope.CopyRequest.txtCertificateOfFactComments.$valid;
        $scope.selectedModal = angular.copy($scope.modal);
        var selectedFilings = [];
        angular.forEach($scope.modal.CertifiedCopies, function (item) {
            if (item.CopyRequest > 0)
                selectedFilings.push(item);
        });
        var isFormValidate = isCorrespondenceAddress && isCertificateOfFactRequired
        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            if (selectedFilings.length > 0) {
                $scope.selectedModal.CertifiedCopies = selectedFilings;
                $scope.selectedModal.BusinessTransaction.CopyRequestEntityList = selectedFilings;// Assign to businesstransaction to CopyRequestEntityList
                $scope.isReview = true;
            }
            else {
                $scope.isReview = false;
                // Folder Name: app Folder
                // Alert Name: emptyCartMsg method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.CopyRequest.emptyCartMsg);
            }
        }
        else {
            $scope.isReview = false;
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };

    // add certificates to cart
    $scope.addToCart = function () {
        $scope.selectedModal.UserId = $rootScope.repository.loggedUser.userid;
        if ($scope.selectedModal.CertifiedCopies.length > 0) {
            
            //TFS 1143 submitting filing means you have said agent consents
            if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
                $scope.modal.Agent.IsRegisteredAgentConsent =
                    true;
            }
            if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
                $scope.modal.IsRegisteredAgentConsent = true; 
            }
            //TFS 1143

            // addCertificatesCart method is available in constants.js
            wacorpService.post(webservices.OnlineFiling.addCertificatesCart, $scope.selectedModal, function (response) {
                $rootScope.transactionID = null;
                if (response.data.ID > 0)
                    $location.path('/shoppingcart');
                else
                    $location.path('/Dashboard');
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        }
        else
            // Folder Name: app Folder
            // Alert Name: emptyCartMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.CopyRequest.emptyCartMsg);
    };

    $scope.$watch('modal', function () {
        if ($scope.modal.CertifiedCopies == undefined)
            return;
        if ($scope.modal.CertifiedCopies.length > 0) {
            var total = 0;
            var totalPages = 0;
            angular.forEach($scope.modal.CertifiedCopies, function (item) {

                var noOfPages = item.NumberOfPages;
                noOfPages = isNaN(noOfPages) ? 0 : noOfPages;

                if (item.FilingNumber != 0) {
                    totalPages = noOfPages + totalPages;
                }
                var allcertcount = 0;
                //if (item.FilingTypeName == "ALL FILED DOCUMENTS "  && item.CopyRequest != 0) {
                //    for (var i = 0; i < $scope.modal.CertifiedCopies.length; i++) {
                //        if ($scope.modal.CertifiedCopies[i].FilingNumber != 0 && $scope.modal.CertifiedCopies[i].NumberOfPages > 0) {
                //            allcertcount += 1;
                //        }
                //    }
                //}

                //if (item.FilingTypeName == "ALL FILED DOCUMENTS " && item.CopyRequest != 0) {
                //    total += (item.CopyRequest * item.Amount) + (10 * (allcertcount * item.CopyRequest)) +(item.ApostilleFee * item.ApostilleCopies);
                //    item.TotalAmount = (item.CopyRequest * item.Amount) + (10 * (allcertcount * item.CopyRequest)) + (item.ApostilleFee * item.ApostilleCopies);
                //}
                //else {
                //    total += (item.CopyRequest * item.Amount) + ((item.CertifiedFee == 0 ? 10 : item.CertifiedFee) * item.CopyRequest) + (item.ApostilleFee * item.ApostilleCopies);
                //    item.TotalAmount = (item.CopyRequest * item.Amount) + ((item.CertifiedFee == 0 ? 10 : item.CertifiedFee) * item.CopyRequest) + (item.ApostilleFee * item.ApostilleCopies);
                //}
                total += (item.CopyRequest * item.Amount) + ((item.CertifiedFee == 0 ? 10 : item.CertifiedFee) * item.CopyRequest) + (item.ApostilleFee * item.ApostilleCopies);
                item.TotalAmount = (item.CopyRequest * item.Amount) + ((item.CertifiedFee == 0 ? 10 : item.CertifiedFee) * item.CopyRequest) + (item.ApostilleFee * item.ApostilleCopies);
                $scope.totalNoOfPages = (item.NumberOfPages * item.CopyRequest) + $scope.totalNoOfPages;
            });

            //$filter('filter')($scope.modal.CertifiedCopies, { FilingTypeName: "ALL FILED DOCUMENTS " })[0].NumberOfPages = totalPages;
            if ($scope.totalNoOfPages > 100) {
                $scope.totalIterationsCount = parseInt(($scope.totalNoOfPages - 100) / 50) + parseInt($scope.totalNoOfPages % 50 > 0 ? 1 : 0);
            }
            else {
                $scope.totalIterationsCount = parseInt(($scope.totalNoOfPages - 100) / 50) ;
            }
            $scope.surChargeAmt_1 = $scope.totalIterationsCount * 13;

            if ($scope.totalIterationsCount > 0) {
                $scope.surChargeAmt = $scope.surChargeAmt_1;
                //total = $scope.surChargeAmt_1 + total; -- 2800
            }
            else {
                $scope.surChargeAmt = 0;
            }
            $scope.modal.TotalAmount = total;
            $scope.totalIterationsCount = 0;
            $scope.surChargeAmt_1 = 0;
            $scope.totalNoOfPages = 0;
        }
        else
            $scope.modal.TotalAmount = 0;
    }, true);

    //navigate to business information
    $scope.showBusineInfo = function (id, businessType) {
        $rootScope.isBackButtonHide = false;
        $scope.businesssearchcriteria.businessid = id;
        $scope.businesssearchcriteria.businesstype = businessType;
        $cookieStore.put('businesssearchcriteria', $scope.businesssearchcriteria);
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        $scope.navBusinessInformation();
    }

    //navigate to home
    $scope.gotoHome = function () {
        // ScopesData.removeByKey('businesssearchcriteria');
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        $scope.navHome();
    };

    $scope.back = function () {
        if ($scope.isReview)
            $scope.isReview = false;
        else
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCopyRequest();
    }


    //Save into Draft
    $scope.GetFilingFee = function (id, selectedItem) {

        angular.forEach($scope.modal.CertifiedCopies, function (item) {
            if (parseInt(item.CopyRequest) >= parseInt(item.ApostilleCopies)) {
                if (item.FilingNumber === id && item.Amount == 0) {
                    var filingTypedata = { params: { businessID: item.BusinessID, BusinessTypeName: item.RCBusinessTypeName, businessTypeID: item.RCFBusinessTypeId, filingTypeID: item.RCFilingTypeId, filingType: item.RCFilingTypeName } };
                    // calculateAnnualFeeOnline method is available in constants.js
                    wacorpService.get(webservices.CopyRequest.calculateAnnualFeeOnline, filingTypedata, function (response) {

                        var fillingFee = $.grep(response.data, function (v) {
                            return v.Description === "FillingFee";
                        });
                        var certifiedFeeFee = $.grep(response.data, function (v) {
                            return v.Description === "CERTIFIED COPIES";
                        });
                        var apostilleFeeFee = $.grep(response.data, function (v) {
                            return v.Description === "APOSTILLE";
                        });
                        if (fillingFee.length > 0) {
                            item.Amount = fillingFee[0].FilingFee;
                        }
                        if (certifiedFeeFee.length > 0) {
                            item.CertifiedFee = certifiedFeeFee[0].FilingFee;
                        }
                        if (apostilleFeeFee.length > 0) {
                            var totalAf = 0;
                            for (var i = 0; i < apostilleFeeFee.length; i++) {
                                totalAf += apostilleFeeFee[i].FilingFee << 0;
                            }

                            item.ApostilleFee = totalAf;
                        }
                    }, function (response) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(response.data);
                    });
                }
            }
            else {
                item.ApostilleCopies = 0;
                // Folder Name: app Folder
                // Alert Name: ApostilleCopyRequest method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.CopyRequest.ApostilleCopyRequest);
            }

        });

        if (selectedItem != null && selectedItem != undefined && selectedItem.FilingTypeName == 'CERTIFICATE OF FACT' && selectedItem.CopyRequest > 0) {
            $scope.CertificateOfFactRequired = true;
        }
        else {
            if (selectedItem != null && selectedItem != undefined && selectedItem.FilingTypeName == 'CERTIFICATE OF FACT') {
                $scope.CertificateOfFactRequired = false;
                if (selectedItem != null && selectedItem != undefined) {
                    selectedItem.Comments = "";
                }
            }
        }
    }
    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {

        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        //$scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/CopyRequest';
        $scope.modal.CartStatus = 'Incomplete';
        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var selectedFilings = [];
        angular.forEach($scope.modal.CertifiedCopies, function (item) {
            //if (item.CopyRequest > 0)
            selectedFilings.push(item);
        });
        $scope.modelDraft.CertifiedCopies = selectedFilings;
        $scope.modelDraft.BusinessTransaction.CopyRequestEntityList = selectedFilings;
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });

        // CopyRequestSaveAsDraft method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.CopyRequestSaveAsDraft, $scope.modelDraft, function (response) {

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }
    $scope.getTransactionDocumentsList = function getTransactionDocumentsList(FilingNumber, Transactionid, FilingTypeName, DocumentTypeId, DocumentId) {
        var criteria = "";
        var url="";
        if ($scope.modal.CFTType != undefined && $scope.modal.CFTType != "") {
            criteria = { ID: Transactionid, FilingNumber: FilingNumber, CharityId: $scope.modal.CharitiesEntityInfo.CFTId, BusinessType: $scope.modal.CFTType, DocumentTypeID: DocumentTypeId, DocumentID: DocumentId }
            url = webservices.CopyRequest.getCFTTransactionDocumentsList; // getCFTTransactionDocumentsList method is available in constants.js
        }
        else {
            criteria = {
                ID: Transactionid, FilingNumber: FilingNumber, Type: FilingTypeName, DocumentTypeID: DocumentTypeId, DocumentID: DocumentId

            };
            url = webservices.CopyRequest.getTransactionDocumentsList; // getTransactionDocumentsList method is available in constants.js
        }

        wacorpService.post(url, criteria,
            function (response) {
                if (response.data != null) {
                    $scope.transactionDocumentsList = angular.copy(response.data);
                    $("#divSearchResult").modal('toggle');
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: noDataFound method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.noDataFound);
            },
            function (response) {
                // Folder Name: app Folder
                // Alert Name: Message method is available in alertMessages.js 
                wacorpService.alertDialog(response.data.Message);
            }
        );
    }
});
wacorpApp.controller('CopyRequestcftSearchController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, $window) {
    
    // variable initialization
    $scope.page = constant.ZERO;
    $scope.page1 = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.pagesCount1 = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.States = [];
    $scope.Counties = [];
    $scope.isButtonSerach = false;
    $scope.cftBusinesssearchcriteria = {};
    $scope.cftAdvFeinSearchcriteria = {};
    $scope.criteria = [];
    $scope.cftBusinessSearch = {};
    $rootScope.cftData = {};
    $rootScope.isAdvanceSearch = false;
    $scope.cftOrganizationSearchType = false;
    $scope.showHome = false;
    $scope.isShowAdvanceSearch = false;
    $scope.hideBasicSearch = false;
    $scope.hideSearchButton = false;
    $scope.search = loadCFList;
    $scope.selectedBusiness = null;
    $scope.selectedBusinessID = 0;

    $scope.SearchType == "searchCorporations";

    $scope.cftSearchcriteria = {
        Type: searchTypes.RegistrationNumber, EntityName: null, KeyWordSearch: null, PrincipalName: null, PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false,
        RegistrationNumber: null, FEINNo: null, UBINumber: null, PercentToProgramServices: null, SortBy: null, SortType: null,
        PrincipalAddress: {
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
            State: null, OtherState: null, Country: null, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        CFSearchList: []
    };

    $scope.clearCFTSearchcriteria = {
        Type: searchTypes.RegistrationNumber, EntityName: null, KeyWordSearch: null, PrincipalName: null, PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false,
        RegistrationNumber: null, FEINNo: null, UBINumber: null, PercentToProgramServices: null, SortBy: null, SortType: null,
        PrincipalAddress: {
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
            State: null, OtherState: null, Country: null, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        CFSearchList: []
    };
 
    $scope.getPercentType = function () {
        $scope.cftSearchcriteria.PercentToProgramServices = $(event.target || event.srcElement).find("option:selected").text();
    }
    $scope.getSelectedBusiness = function (business) {
        
        $scope.selectedBusiness = business;
        $scope.selectedBusinessID = business.CFTId;
    };
    $scope.cftAdvFeinSearchcriteria = {
        CFTId: "", ID: "", EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, isCftOrganizationSearchBack: false, IsSearch: false, EntityWebsite: null,
        RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, Businesstype: "", Type: "", SearchValue: "", SearchCriteria: "",
    };
    $scope.submitBusiness = function () {
        $rootScope.cftType = $scope.selectedBusiness.BusinessType
        $location.path('/CopyRequest/' + $scope.selectedBusinessID + '/' + $scope.selectedBusiness.BusinessType);
    };
    //scope initialization
    $scope.initCFTSearch = function () {
        $scope.cftOrganizationSearchType = true;
        if ($rootScope.isInitialSearch) {
            if ($rootScope.data) {
                $scope.cftSearchcriteria = $rootScope.data;
                $cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
            }
        }
        else if ($rootScope.isCftOrganizationSearchBack == true) {
            $scope.showAdvanceSearch();
            $scope.cftSearchcriteria = $rootScope.data;
            $cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
        }
        else {
            $scope.page = $scope.page || constant.ZERO;
            $scope.cftSearchcriteria.PageID = $scope.page == constant.ZERO ? constant.ONE : $scope.page + constant.ONE;
        }
        if ($rootScope.isInitialSearch)
            loadCFList(constant.ZERO, false);
        else if ($rootScope.isCftOrganizationSearchBack)
            loadCFList(constant.ZERO, true);

        $scope.messages = messages;
        if ($rootScope.repository.loggedUser != undefined && $rootScope.repository.loggedUser != null) {
            if ($rootScope.repository.loggedUser.userid != undefined && $rootScope.repository.loggedUser.userid != null && $rootScope.repository.loggedUser.userid > 0) {
                $scope.IsUserLogedIn = true;
            }
            else {
                $scope.IsUserLogedIn = false;
            }
        }
        else {
            $scope.IsUserLogedIn = false;
            $scope.showAdvanceSearch();
        }

    }


    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.cftSearchcriteria.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.cftSearchcriteria.UBINumber = pastedText;
            });
        }
    };

    $scope.setPastedFEIN = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.cftSearchcriteria.FEINNo = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.cftSearchcriteria.FEINNo = pastedText;
            });
        }
    };

    $scope.setPastedZip = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 5);
            $scope.cftSearchcriteria.FEINNo = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 5);
                $scope.cftSearchcriteria.FEINNo = pastedText;
            });
        }
    };

    $scope.setPastedRemoveSpaces = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\s/g, '');
            if (e.originalEvent.currentTarget.name == "OrganizationName")
                $scope.cftSearchcriteria.EntityName = pastedText;
            else if (e.originalEvent.currentTarget.name == "KeywordSearch")
                $scope.cftSearchcriteria.KeyWordSearch = pastedText;
            else if (e.originalEvent.currentTarget.name == "City")
                $scope.cftSearchcriteria.PrincipalAddress.City = pastedText;
            else if (e.originalEvent.currentTarget.name == "Officers")
                $scope.cftSearchcriteria.PrincipalName = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\s/g, '');
                if (e.originalEvent.currentTarget.name == "OrganizationName")
                    $scope.cftSearchcriteria.EntityName = pastedText;
                else if (e.originalEvent.currentTarget.name == "KeywordSearch")
                    $scope.cftSearchcriteria.KeyWordSearch = pastedText;
                else if (e.originalEvent.currentTarget.name == "City")
                    $scope.cftSearchcriteria.PrincipalAddress.City = pastedText;
                else if (e.originalEvent.currentTarget.name == "Officers")
                    $scope.cftSearchcriteria.PrincipalName = pastedText;
            });
        }
    };
    $scope.setPastedRegNumber = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
            $scope.cftSearchcriteria.RegistrationNumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                $scope.cftSearchcriteria.RegistrationNumber = pastedText;
            });
        }
    };

    $scope.setPercent = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            var digits = /^[0-9]+$/;
            if (digits.test(pastedText))
                $scope.cftSearchcriteria.PercentToProgramServices = pastedText;
            else {
                e.preventDefault();
                $scope.cftSearchcriteria.PercentToProgramServices = null;
            }

        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                var digits = /^[0-9]+$/;
                if (digits.test(pastedText))
                    $scope.cftSearchcriteria.PercentToProgramServices = pastedText;
                else {
                    e.preventDefault();
                    $scope.cftSearchcriteria.PercentToProgramServices = null;
                }
            });
        }
    };


    $scope.allowDecimals = function (e) {

        //var pastedText = "";
        //    pastedText = evt.originalEvent.clipboardData.getData('text/plain');
        var charCode = (e.which) ? e.which : e.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            e.preventDefault();
        }
        else { }
    };


    $scope.setUBILength = function (e) {
         if ($scope.cftSearchcriteria.UBINumber != undefined && $scope.cftSearchcriteria.UBINumber != "" && $scope.cftSearchcriteria.UBINumber!=null && $scope.cftSearchcriteria.UBINumber.length >= 9) {
            // Allow: backspace, delete, tab, escape, enter and .
            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                // Allow: Ctrl+A, Command+A
                (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                // Allow: home, end, left, right, down, up
                (e.keyCode >= 35 && e.keyCode <= 40)) {
                // let it happen, don't do anything
                return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
            e.preventDefault();
        }
    };

    // search Charity and Fundraiser list
    $scope.searchCF = function (searchform, flag) {
        //$scope.isShowErrorFlag = true;
        //if ($scope[searchform].$valid) {
        $scope.cftSearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadCFList(constant.ZERO, flag); // loadCFList method is available in this controller only
        //}
    };



    // get Charity and Fundraiser list data from server
    function loadCFList(page, flag, sortBy) {
        var data = new Array();
        $scope.cftSearchcriteria.PageID = page == 0 ? 1 : page + 1;
        if (sortBy != undefined) {
            if ($scope.cftSearchcriteria.SortBy == sortBy) {
                if ($scope.cftSearchcriteria.SortType == 'ASC') {
                    $scope.cftSearchcriteria.SortType = 'DESC';
                }
                else {
                    $scope.cftSearchcriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.cftSearchcriteria.SortBy = sortBy;
                $scope.cftSearchcriteria.SortType = 'ASC';
            }
        }
        data = angular.copy($scope.cftSearchcriteria);
        if (flag == undefined || flag == null)
            flag = $rootScope.flag;
        //$cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
        if (flag) {
            $rootScope.isAdvanceSearch = true;
            $rootScope.isInitialSearch = null;
        }
        else {
            $rootScope.isInitialSearch = true;
            $rootScope.isAdvanceSearch = null;
        }
        $rootScope.flag = flag;
        $scope.isButtonSerach = page == 0;
        // getCFPublicSearchDetails method is available in constants.js
        wacorpService.post(webservices.CopyRequest.getCFPublicSearchDetails, data, function (response) {
            $scope.cftSearchcriteria.CFSearchList = response.data;
            $cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
            if (response.data.length > constant.ZERO) {
                if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                    var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                    var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                    $scope.pagesCount = response.data.length < $scope.cftSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount : pagecount;
                    $scope.totalCount = totalcount;
                }
                $scope.page = page;
                $scope.BusinessListProgressBar = false;
                focus("tblCFSearch");
            }

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });

    }

    $scope.cancel = function () {
        $("#divAdvCharitiesSearchResult").modal('toggle');
    }

    // clear fields
    $scope.clearFun = function () {
        $scope.cftSearchcriteria.EntityName = null;
        $scope.cftSearchcriteria.FEINNo = null;
        $scope.cftSearchcriteria.UBINumber = null;
        $scope.cftSearchcriteria.RegistrationNumber = null;
        $scope.cftSearchcriteria.SortType = null;
        $scope.cftSearchcriteria.SortBy = null;

    };

    $scope.cleartext = function (value) {
        switch (value) {
            case "RegistrationNumber":
                $scope.cftSearchcriteria.EntityName = null;
                $scope.cftSearchcriteria.FEINNo = null;
                $scope.cftSearchcriteria.UBINumber = null;
                break;
            case "FEINNo":
                $scope.cftSearchcriteria.RegistrationNumber = null;
                $scope.cftSearchcriteria.EntityName = null;
                $scope.cftSearchcriteria.UBINumber = null;
                break;
            case "UBINumber":
                $scope.cftSearchcriteria.RegistrationNumber = null;
                $scope.cftSearchcriteria.EntityName = null;
                $scope.cftSearchcriteria.FEINNo = null;
                break;
            case "OrganizationName":
                $scope.cftSearchcriteria.RegistrationNumber = null;
                $scope.cftSearchcriteria.FEINNo = null;
                $scope.cftSearchcriteria.UBINumber = null;
                break;
            default:

        }
    };
});
wacorpApp.controller('charitiesRegistrationController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------- Charities Registration Functionality------------- */
    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    $scope.isShowBack = false;
    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $rootScope.BusinessTypeID = 7;//Charitable Organization business type

        var isOptional = localStorage.getItem("isOptional");
        $scope.isShowBack = isOptional;
        //get business information
        var data = {};
        if (isOptional == "true") {
            // here filingTypeID: 158 is CHARITABLE ORGANIZATION OPTIONAL REGISTRATION
            data = { params: { businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 158, transactionID: $rootScope.transactionID } };
        }
        else {
            // here filingTypeID: 159 is CHARITABLE ORGANIZATION REGISTRATION
            data = { params: { businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 159, transactionID: $rootScope.transactionID } };
        }

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                if (isOptional == "true") {
                    $location.path('/charitiesOptionalRegistration');
                }
                else {
                    $location.path('/charitiesRegistration');
                }
            }
            // CharitiesCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.CharitiesCriteria, data, function (response) {
                //angular.extend(response.data, $scope.modal);
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());

                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
                $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
                $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);
                $scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets || null;
                $scope.modal.RevenueGDfromSolicitations = $scope.modal.RevenueGDfromSolicitations || null;
                $scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.RevenueGDRevenueAllOtherSources || null;
                $scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts || null;
                $scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.ExpensesGDExpendituresProgramServices || null;
                $scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures || null;
                $scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets || null;
                $scope.modal.IsNewRegistration = true;
                $scope.modal.ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.ContributionServicesTypeId) ? [] : $scope.modal.ContributionServicesTypeId.split(',');
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');
                if (isOptional == "false")
                {
                    $scope.modal.IsOptionalRegistration = false;
                    $rootScope.OptionalData = null;
                }

                if ($rootScope.OptionalData != null && $rootScope.OptionalData != undefined) {
                    $scope.modal.IsIntegratedAuxiliary = $rootScope.OptionalData.IntegratedAuxiliary=="Yes"?true:false;
                    $scope.modal.IsPoliticalOrganization = $rootScope.OptionalData.PoliticalOrganization == "Yes" ? true : false;
                    $scope.modal.IsRaisingFundsForIndividual = $rootScope.OptionalData.RaisingFundsForIndividual == "Yes" ? true : false;
                    $scope.modal.IsRaisingLessThan50000 = $rootScope.OptionalData.RaisingLessThan50000 == "Yes" ? true : false;
                    $scope.modal.IsAnyOnePaid = $rootScope.OptionalData.AnyOnePaid == "Yes" ? true : false;
                    $scope.modal.IsInfoAccurate = $rootScope.OptionalData.InfoAccurate == "Yes" ? true : false;
                }
                else {
                    $scope.modal.IsIntegratedAuxiliary = $scope.modal.IsIntegratedAuxiliary;
                    $scope.modal.IsPoliticalOrganization = $scope.modal.IsPoliticalOrganization;
                    $scope.modal.IsRaisingFundsForIndividual = $scope.modal.IsRaisingFundsForIndividual;
                    $scope.modal.IsRaisingLessThan50000 = $scope.modal.IsRaisingLessThan50000;
                    $scope.modal.IsAnyOnePaid = $scope.modal.IsAnyOnePaid;
                    $scope.modal.IsInfoAccurate = $scope.modal.IsInfoAccurate;
                }
                $scope.modal.CharityAkaInfoEntity.CountiesServedId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CountiesServedId) ? [] : $scope.modal.CharityAkaInfoEntity.CountiesServedId.split(',');
                $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId) ? [] : $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.split(',');
                //$scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
                //$scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.County = $scope.modal.EntityStreetAddress.County != null ? $scope.modal.EntityStreetAddress.County : "";
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country != null ? $scope.modal.LegalInfo.LegalInfoAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';
                $scope.modal.AKASolicitNameId = '';
                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;
                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                if (!($scope.modal.FederalTaxExemptId == null || $scope.modal.FederalTaxExemptId == undefined))
                    $scope.modal.FederalTaxExemptId = $scope.modal.FederalTaxExemptId == 0 ? '' : $scope.modal.FederalTaxExemptId.toString();

                if (!($scope.modal.OSJurisdictionCountyId == null || $scope.modal.OSJurisdictionCountyId == undefined))
                    $scope.modal.OSJurisdictionCountyId = $scope.modal.OSJurisdictionCountyId == 0 ? '' : $scope.modal.OSJurisdictionCountyId.toString();

                if (!($scope.modal.OSJurisdictionStateId == null || $scope.modal.OSJurisdictionStateId == undefined))
                    $scope.modal.OSJurisdictionStateId = $scope.modal.OSJurisdictionStateId == 0 ? '' : $scope.modal.OSJurisdictionStateId.toString();

                if (!($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == undefined))
                    $scope.modal.JurisdictionCountry = $scope.modal.JurisdictionCountry == 0 ? '' : $scope.modal.JurisdictionCountry.toString();

                if (!($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == undefined))
                    $scope.modal.JurisdictionState = $scope.modal.JurisdictionState == 0 ? '' : $scope.modal.JurisdictionState.toString();

                $scope.modal.isShowReturnAddress = true;
            }, function (response) { });
        }
        else {
            //$scope.modal.FederalTaxExemptId = $scope.modal.FederalTaxExemptId.toString();
            $scope.modal = $rootScope.modal;
            if (isOptional=="false")
            {
                $scope.modal.IsOptionalRegistration = false;
            }
            if ($scope.modal.IsOptionalRegistration && $rootScope.OptionalData != null && $rootScope.OptionalData != undefined) {
                $scope.modal.IsIntegratedAuxiliary = $rootScope.OptionalData.IntegratedAuxiliary == "Yes" ? true : false;
                $scope.modal.IsPoliticalOrganization = $rootScope.OptionalData.PoliticalOrganization == "Yes" ? true : false;
                $scope.modal.IsRaisingFundsForIndividual = $rootScope.OptionalData.RaisingFundsForIndividual == "Yes" ? true : false;
                $scope.modal.IsRaisingLessThan50000 = $rootScope.OptionalData.RaisingLessThan50000 == "Yes" ? true : false;
                $scope.modal.IsAnyOnePaid = $rootScope.OptionalData.AnyOnePaid == "Yes" ? true : false;
                $scope.modal.IsInfoAccurate = $rootScope.OptionalData.InfoAccurate == "Yes" ? true : false;
            }
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());

            //Assigning 0's to Empty
            $scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets == 0 ? null : $scope.modal.BeginingGrossAssets;
            $scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets == 0 ? null : $scope.modal.EndingGrossAssets;
            $scope.modal.RevenueGDfromSolicitations = $scope.modal.RevenueGDfromSolicitations == 0 ? null : $scope.modal.RevenueGDfromSolicitations;
            $scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.RevenueGDRevenueAllOtherSources == 0 ? null : $scope.modal.RevenueGDRevenueAllOtherSources;
            $scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.ExpensesGDExpendituresProgramServices == 0 ? null : $scope.modal.ExpensesGDExpendituresProgramServices;
            $scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures == 0 ? null : $scope.modal.ExpensesGDValueofAllExpenditures;
            $scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts == 0 ? null : $scope.modal.TotalDollarValueofGrossReceipts;
            $scope.modal.PercentToProgramServices = $scope.modal.PercentToProgramServices == 0 ? null : $scope.modal.PercentToProgramServices;

            $scope.modal.isShowReturnAddress = true;
        }
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    $scope.Review = function (charitiesRegistrationForm) {
        //if (!$scope.modal.IsAnyOnePaid) {
        $scope.validateErrorMessage = true;

        //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {
        //var isFeinValid = $scope.modal.IsFEINNumberExistsorNot && ($scope.modal.UBINumber != null ? $scope.modal.IsUBINumberExistsorNot : true) && $scope.charitiesRegistrationForm.fein.$valid && $scope.modal.FEINNumber.length == 9;

        var isOrgNameValid = $scope.modal.EntityName != null && $scope.modal.EntityName != "" ? true : false;

        var isPurposeValid = $scope.modal.Purpose != null ? true : false;

        var isSolicitUpload = ($scope.modal.IsUploadAddress ? ($scope.modal.UploadListOfAddresses.length > 0 ? true : false) : true);

        //var isEntityNameValid = $scope.charitiesRegistrationForm.cftEntityName.$valid;

        var isTaxUploadValid = $scope.modal.IsShowFederalTax ? ($scope.modal.FederaltaxUpload.length > 0 ? true : false) : true;

        //var isEntityNameValid = $scope.modal.isBusinessNameAvailable ? true : false;

        $scope.EntityNameCheck = true;

        $scope.modal.NewEntityName = $scope.modal.EntityName;

        if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
            if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                $scope.modal.isBusinessNameChanged = true;
            }
            else {
                $scope.modal.isBusinessNameChanged = false;
            }
        }

        //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);
        var isEntityNameValid = ($scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : ($scope.modal.isBusinessNameChanged ? false : true)));

        if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
            $scope.EntityNameCheck = false;
        }
        else {
            $scope.EntityNameCheck = true;
        }

        var isEntityInfo = ($scope.charitiesRegistrationForm.entityInfo.$valid);

        var isExpensesValid = ($scope.modal.IsFIFullAccountingYear ? ($scope.modal.ExpensesGDValueofAllExpenditures < $scope.modal.ExpensesGDExpendituresProgramServices ? false : true) : true);

        //To not validate inner form from outer form removed control
        //if (!($scope.charitiesRegistrationForm.CharityOrganizationForm.akaNames == null || $scope.charitiesRegistrationForm.CharityOrganizationForm.akaNames == undefined))
        //    $scope.charitiesRegistrationForm.CharityOrganizationForm.$removeControl($scope.charitiesRegistrationForm.CharityOrganizationForm.akaNames);

        //var isCharityOrgFormValid = ($scope.charitiesRegistrationForm.CharityOrganizationForm.$valid);

        var isDateValid = ($scope.modal.IsFIFullAccountingYear ? (new Date($scope.modal.AccountingyearEndingDate) > new Date($scope.modal.AccountingyearBeginningDate) ? true : false) : true);

        $scope.checkAccYearVaild = false;
        if ($scope.modal.IsFIFullAccountingYear) {
            if (typeof ($scope.modal.AccountingyearEndingDate) != typeof (undefined) && $scope.modal.AccountingyearEndingDate != null && $scope.modal.AccountingyearEndingDate != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.checkAccYearVaild = wacorpService.checkAccYearEndDateForReg($scope.modal.AccountingyearEndingDate, true);
            }
        }
        else {
            if (typeof ($scope.modal.FirstAccountingyearEndDate) != typeof (undefined) && $scope.modal.FirstAccountingyearEndDate != null && $scope.modal.FirstAccountingyearEndDate != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.checkAccYearVaild = wacorpService.checkAccYearEndDateForReg($scope.modal.FirstAccountingyearEndDate, false);
            }
        }

        var isCharitiesFinancialInfo = ($scope.charitiesRegistrationForm.CharityFinancialInfoForm.$valid);

        var isOfficerHighpay = $scope.modal.OfficersHighPay.IsPayOfficers ? ($scope.modal.OfficersHighPayList.length > 0 ? true : false) : true;
        //var isOfficerHighpay =   $scope.modal.OfficersHighPay.IsPayOfficers ? ($scope.modal.OfficersHighPay.IsPayOfficers && $scope.modal.OfficersHighPayList != null && $scope.modal.OfficersHighPayList.length > 0) : true;

        var isCftOfficesListValid = ($scope.modal.CFTOfficersList.length > 0);

        var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

        var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalActionsUploads.length > 0 ? true : false) : true);

        var isLegalInfo = $scope.modal.isUpdated ? ($scope.charitiesRegistrationForm.fundraiserLegalInfo.$valid) : true;

        var isFundraiserListValid = true;
        if ($scope.modal.IsCommercialFundraisersContributionsInWA)
            isFundraiserListValid = $scope.modal.FundraisersList.length > 0;


        var Fein = $scope.modal.FEINNumber;
        var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

        var Ubi = $scope.modal.UBINumber;
        var isValidUbi = $scope.modal.IsEntityRegisteredInWA && $scope.modal.JurisdictionState == "271" ?
            (Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9 ? true : false) : (Ubi == null || Ubi == '' || Ubi.length == 9 ? true : false);


        var isSignatureAttestationValidate = ($scope.charitiesRegistrationForm.SignatureForm.$valid);

        //var isCorrespondenceAddressValid = $scope.charitiesRegistrationForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.charitiesRegistrationForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.charitiesRegistrationForm.cftCorrespondenceAddressForm.$valid;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

        var isFormValidate = isOrgNameValid && isTaxUploadValid && isPurposeValid && isSolicitUpload && isEntityNameValid && isEntityInfo && !$scope.checkAccYearVaild
        && isExpensesValid && isOfficerHighpay && isCharitiesFinancialInfo && isCftOfficesListValid && isLegalActionsListValid && isLegalActionsUploadValid && isDateValid
        && isFundraiserListValid && isSignatureAttestationValidate && isValidFein && isValidUbi && isLegalInfo && isAdditionalUploadValid && isCorrespondenceAddressValid;

        $scope.fillRegData(); // fillRegData method is available in this controller only.

        if ($scope.modal.IsOptionalRegistration) {
            var IsQualified = ($scope.modal.IsIntegratedAuxiliary || $scope.modal.IsPoliticalOrganization
                    || $scope.modal.IsRaisingFundsForIndividual || $scope.modal.IsRaisingLessThan50000 || $scope.modal.IsAnyOnePaid);
            if (isFormValidate && IsQualified && $scope.modal.IsInfoAccurate) {
                $scope.validateErrorMessage = false;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                var isOptionalReg = wacorpService.validateOptionalQualifiers($scope.modal.IsIntegratedAuxiliary, $scope.modal.IsPoliticalOrganization, $scope.modal.IsRaisingFundsForIndividual, $scope.modal.IsRaisingLessThan50000, $scope.modal.IsAnyOnePaid);
                if (isOptionalReg) {
                    $scope.isReview = true;
                    $location.path('/charitiesOptionalRegistrationReview');
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: qualifier method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifier);
                    $rootScope.modal = null;
                    //$location.path("/charitiesRegistration");
                }
            }
            else {
                // Folder Name: app Folder
                // Alert Name: InvalidFilingMsg method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
            }
        }
        else {
            if (isFormValidate) {
                $scope.validateErrorMessage = false;
                $scope.isReview = true;
                $location.path('/charitiesRegistrationReview');
            }
            else
                // Folder Name: app Folder
                // Alert Name: InvalidFilingMsg method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
        //}
        //else {
        //    wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifier1);
        //    $rootScope.modal = null;
        //    $scope.navCharityRegistration();
        //}
        //}
        //else {
        //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
        //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
        //        return false;
        //    }
        //}
    };

    $scope.fillRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.EntityName = $scope.modal.EntityName || null;
        $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
        $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
        $scope.modal.OSJurisdictionId = $scope.modal.OSJurisdictionStateId != "" ? $scope.modal.OSJurisdictionStateId : $scope.modal.OSJurisdictionCountyId;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }

        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }

        if ($scope.modal.CharityAkaInfoEntity.CountiesServedId != null && $scope.modal.CharityAkaInfoEntity.CountiesServedId.length > 0) {
            $scope.modal.CharityAkaInfoEntity.CountiesServedId = $scope.modal.CharityAkaInfoEntity.CountiesServedId.join(",");
        }
        if ($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId != null && $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.length > 0) {
            $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.join(",");
        }

        if ($scope.modal.OfficersHighPayList != null && $scope.modal.OfficersHighPayList.length == 3)
            $scope.modal.OfficersHighPay.IsCountMax = true;

        if ($scope.modal.CharityAkaInfoEntityList != null && $scope.modal.CharityAkaInfoEntityList.length > 0) {
            angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                if (akaInfo.CountiesServedId != null && akaInfo.CountiesServedId.length > 0)
                    akaInfo.CountiesServedId = akaInfo.CountiesServedId.join(",");
                if (akaInfo.CategoryOfServiceId != null && akaInfo.CategoryOfServiceId.length > 0)
                    akaInfo.CategoryOfServiceId = akaInfo.CategoryOfServiceId.join(",");
            });
        }
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
        $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
        $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

        $scope.modal.EntityStreetAddress.IsAddressSame = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        //if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
        //    $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $rootScope.modal = $scope.modal;

    }

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillRegData(); // fillRegData method is available in this controller only.
        if ($scope.modal.IsOptionalRegistration) {
            $scope.modal.OnlineNavigationUrl = "/charitiesOptionalRegistration";
        }
        else {
            $scope.modal.OnlineNavigationUrl = "/charitiesRegistration";
        }
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.RegBack = function () {
        $scope.fillRegData(); // fillRegData method is available in this controller only.
        var optioanlData = {
            IntegratedAuxiliary: $scope.modal.IsIntegratedAuxiliary?"Yes":"No",
            PoliticalOrganization: $scope.modal.IsPoliticalOrganization?"Yes":"No",
            RaisingFundsForIndividual: $scope.modal.IsRaisingFundsForIndividual ? "Yes" : "No",
            RaisingLessThan50000: $scope.modal.IsRaisingLessThan50000?"Yes":"No",
            AnyOnePaid: $scope.modal.IsAnyOnePaid ? "Yes" : "No",
            InfoAccurate: $scope.modal.IsInfoAccurate ? "Yes" : "No",
        };
        $rootScope.OptionalData = optioanlData;
        //localStorage.setItem('isOptionalReg',true);
        $rootScope.isOptionalReg = true;
        localStorage.setItem("IsBack", true);
        $location.path("/charitiesOptionalQualifier");

    };
});

wacorpApp.controller('charitiesRegistrationReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Charities Registration Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        $scope.modal = $rootScope.modal;
    };
    
    $scope.CharitiesAddToCart = function () {
        //$scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        //$scope.modal.OSJurisdictionId = $scope.modal.OSJurisdictionStateId != "" ? $scope.modal.OSJurisdictionStateId : $scope.modal.OSJurisdictionCountyId;
        if ($scope.modal.ContributionServicesTypeId!=null && $scope.modal.ContributionServicesTypeId.length > 0)
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");

        if ($scope.modal.FinancialInfoStateId!=null && $scope.modal.FinancialInfoStateId.length > 0)
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesAddToCart method is available in constants.js
         wacorpService.post(webservices.CFT.CharitiesAddToCart, $scope.modal, function (response) {
             $rootScope.BusinessType = null;
             //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
             $rootScope.modal = null;
             $rootScope.OptionalData = null;
             $rootScope.isOptionalReg = false;
             resetLocalStorage(); // resetLocalStorage method is available in this controller only.
             $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
         }, function (response) {
             // Service Folder: services
             // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        if ($scope.modal.IsOptionalRegistration) {
            $location.path('/charitiesOptionalRegistration');
        }
        else {
            $location.path('/charitiesRegistration');
        }
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    function resetLocalStorage() {
        //localStorage.removeItem('isOptionalReg');
        localStorage.removeItem("IsBack");
        localStorage.removeItem('isOptional');
    }
});

wacorpApp.controller('organizationController', function ($scope, $http, $q, $timeout, $routeParams, $location, $rootScope, $window, $cookieStore, lookupService, wacorpService, ScopesData) {
    // variable initialization
    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.cftSearchcriteria = {};
    $scope.cftBusinessSearchcriteria = {};
    $scope.isButtonSerach = false;
    $scope.cftBusinessSearch = [];
    $scope.criteria = [];
    $scope.Reasons = [];
    $scope.isAdvanceSearch = false;
    $scope.cftOrganizationSearchType = false;
    $scope.isCftOrganizationSearchBack = false;
    $scope.modal = $rootScope.Modal;
    $scope.transactionDocumentsList = [];
    $scope.cftSearchcriteria = {
        EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false, EntityWebsite: null,
        RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, BusinessType: "", Type: "", ID: "", SearchValue: "", SearchCriteria: "", CFTId: "", Businesstype:null
    };

    var criteria = {
        CFTId: null,
        Businesstype: null,
    };
    //scope initialization
    $scope.initCFOrgBusinessSearch = function () {
        if ($rootScope.isAdvanceSearch == false) {
            $cookieStore.remove('cftAdvanceSearchcriteria');
            $scope.cftOrganizationSearchType = true;
            $rootScope.isBasicSearch = false;
        }
        var sessionObj = JSON.parse($window.sessionStorage.getItem('orgData'));

        if (sessionObj && sessionObj.viewMode) {
            $scope.feinBack = sessionObj.flag;
            if (sessionObj.isBasicSearch) {
                $rootScope.data = sessionObj.org;
                $scope.criteria = $rootScope.data;
                $rootScope.isBasicSearch = true;
            }
            else if (!$scope.feinBack && $scope.feinBack != undefined) {
                criteria = {
                    CFTId: $cookieStore.get('cftBusinessSearchcriteriaId'),
                    Businesstype: $cookieStore.get('cftBusinessSearchcriteriaType'),
                };
                $rootScope.isAdvanceSearch = false;
                $rootScope.data = criteria;
                $scope.criteria = sessionObj.org;
            }
            else if (sessionObj.type == "Optional") {
                $rootScope.data = sessionObj.org;
                $scope.criteria = $rootScope.data;
                $rootScope.isOptionalCharityEntitySearch = true;
            }
            else {
                if (sessionObj.isAdvanced) {
                    $rootScope.isAdvanceSearch = true;
                    $rootScope.data = sessionObj.org;
                    $scope.criteria = sessionObj.org;
                }
                else {
                    if (sessionObj.org.Businesstype == "Fundraiser") {
                        $rootScope.isFundraiserEntitySearch = true;
                    }
                    else {
                        $rootScope.isCharityEntitySearch = true;
                    }
                    $rootScope.data = sessionObj.org;
                    $scope.criteria = $rootScope.data;
                }

            }

        } else {
            $scope.criteria = $rootScope.data;
        }

        $window.sessionStorage.removeItem('orgData');
        $scope.cftBusinessSearch.CFTId = $cookieStore.get('cftBusinessSearchcriteriaId');
        $scope.cftBusinessSearch.Businesstype = $cookieStore.get('cftBusinessSearchcriteriaType');
        execCurrentPath(); // execCurrentPath method is available in this controller only.
    }

    function execCurrentPath() {
        if ($location.path() == "/organization") {
            loadCFList(constant.ZERO); // loadCFList method is available in this controller only.
        }
        if ($location.path() == "/CFTSearch/cftSearchOrganizationFilings") {
            loadCFList(constant.ZERO); // loadCFList method is available in this controller only.
            $scope.cftSearchBusinessFilings(); // cftSearchBusinessFilings method is available in this controller only.
        }
        if ($location.path() == "/CFTSearch/cftSearchOrganizationNameHistory") {
            loadCFList(constant.ZERO); // loadCFList method is available in this controller only.
            $scope.getCftBusinessNameHistoryList(); // getCftBusinessNameHistoryList method is available in this controller only.
        }
    }

    // search Charity and Fundraiser list
    $scope.searchCF = function (searchform) {
        $scope.cftSearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadCFList(searchform); // loadCFList method is available in this controller only.
    };
    // get Charity and Fundraiser list data from server
    function loadCFList(page) {

        var data = { params: { Type: $rootScope.data.Businesstype, CharityID: $rootScope.data.CFTId } };
        // getcharityOrganization method is available in constants.js
        wacorpService.get(webservices.CFT.getcharityOrganization, data, function (response) {
            $scope.modal = response.data;
            //$scope.show = $scope.modal.BusinessTransaction.BusinessFilingType == 'CHARITABLE ORGANIZATION OPTIONAL REGISTRATION' ? true : false;
            //$scope.show = !angular.isUndefinedOrNull ($scope.modal.BusinessTransaction.BusinessFilingType)?($scope.modal.BusinessTransaction.BusinessFilingType.toUpperCase() == 'CHARITABLE ORGANIZATION OPTIONAL REGISTRATION' ? true : false):false;
            $scope.isClosure = $scope.modal.Status == 'Closed' || $scope.modal.Status == 'Involuntarily Closed' ? true : false;
            //$scope.isShowData = $scope.show == false && $scope.isClosure == false ? true : false;
            $scope.isShowData = $scope.show == false ? true : false;
            $scope.modal.CFTType = $rootScope.data.Businesstype;
            if ($scope.modal.CFTType == "Trust") {
                if ($scope.modal.TrustClosureReason && $scope.modal.TrustClosureReason.length > 0)
                    $scope.Reasons = $scope.modal.TrustClosureReason.split(',');
            }
            else {
                if ($scope.modal.CharitiesClosureReason && $scope.modal.CharitiesClosureReason.length > 0)
                    $scope.Reasons = $scope.modal.CharitiesClosureReason.split(',');
            }
            $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
            $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
            $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);
            $scope.modal.BondWaiversBondExpirationDate = wacorpService.dateFormatService($scope.modal.BondWaiversBondExpirationDate);
            $scope.modal.LegalInfo.LastName = $scope.modal.LegalInfo.LastName == null ? "" : $scope.modal.LegalInfo.LastName;
            $scope.modal.LegalInfo.FirstName = $scope.modal.LegalInfo.FirstName == null ? "" : $scope.modal.LegalInfo.FirstName;
            $scope.modal.LegalInfo.EntityRepresentativeFirstName = $scope.modal.LegalInfo.EntityRepresentativeFirstName == null ? "" : $scope.modal.LegalInfo.EntityRepresentativeFirstName;
            $scope.modal.LegalInfo.EntityRepresentativeLastName = $scope.modal.LegalInfo.EntityRepresentativeLastName == null ? "" : $scope.modal.LegalInfo.EntityRepresentativeLastName;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    // display CFT  business filings
    $scope.cftSearchBusinessFilings = function () {
        var cftBusinesstype = $rootScope.data.Businesstype;
        $scope.cftSearchcriteria.ID = $rootScope.data.CFTId;
        $scope.cftSearchcriteria.BusinessType = $rootScope.data.Businesstype;
        var data = angular.copy($scope.cftSearchcriteria);
        if (cftBusinesstype != "Name Reservation")
            // getCftSearchOrganizationFillings method is available in constants.js
            wacorpService.post(webservices.CFT.getCftSearchOrganizationFillings, data, function (response) {
                if (response.data != null) {
                    $scope.cftBusinessFilings = response.data;
                    $scope.cftBusinessFilings.FilingDateTime = wacorpService.dateFormatService($scope.cftBusinessFilings.FilingDateTime);
                }
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
    };

    // display CFT business names history list
    $scope.getCftBusinessNameHistoryList = function () {
        $scope.cftSearchcriteria.ID = $rootScope.data.CFTId;
        $scope.cftSearchcriteria.BusinessType = $rootScope.data.Businesstype;
        var data = angular.copy($scope.cftSearchcriteria);
        // getCftSearchOrganizationNameHistoryList method is available in constants.js
        wacorpService.post(webservices.CFT.getCftSearchOrganizationNameHistoryList, data, function success(response) {
            if (response.data.length > 0) {
                $scope.cftBusinessNameHistoryList = response.data;
            }
        }, function failed(response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data)
        });
    }

    //navigate to business information
    $scope.showBusineInfo = function (id, businessType) {
        $scope.cftBusinessSearch.CFTId = id;
        $scope.cftBusinessSearch.Businesstype = businessType;
        $rootScope.data = $scope.cftBusinessSearch.length > 0 ? $scope.cftBusinessSearch : $rootScope.data;
        $cookieStore.put('cftBusinessSearchcriteriaId', $scope.cftBusinessSearch.CFTId);
        $cookieStore.put('cftBusinessSearchcriteriaType', $scope.cftBusinessSearch.Businesstype);
        // Folder Name: controller
        // File Name: rootController.js (you can search with file name in solution explorer)
        $scope.navCharityFoundationOrganization();
    }

    $scope.cftNavOrganizationSearch = function () {
        if ($rootScope.isAdvanceSearch == true) {
            $cookieStore.get('cftAdvanceSearchcriteria');
            $rootScope.isCftOrganizationSearchBack = true;
            $rootScope.isBasicSearch = false;
            $rootScope.isBasicSearchBack = false;
            $rootScope.isFundraiserEntitySearch = null;            
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCFTSearch();
            //$location.path("/cftSearch");
        }
        if ($rootScope.isInitialSearch == true) {
            $cookieStore.get('cftAdvanceSearchcriteria');
            $rootScope.isCftOrganizationSearchBack = true;
            $rootScope.isBasicSearch = false;
            $rootScope.isBasicSearchBack = false;
            $rootScope.isFundraiserEntitySearch = null;
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCFTSearch();
        }
        if ($rootScope.isAdvanceSearch == false) {
            $rootScope.isCftOrganizationSearchBack = true;
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCFTOrgBusinessDetails();
        }
        if ($rootScope.isCharityEntitySearch == true) {
            if ($rootScope.isCharityEntitySearch)
                $rootScope.isCftOrganizationSearchBack = true;
            else
                $rootScope.isCftFeinOrganizationSearchBack = true;
            if ($rootScope.businessFilingType == "Renewal")
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navCharityRenewal();
            else
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navCharityAmendment();

            $rootScope.isFundraiserEntitySearch = null;
        }
        if ($rootScope.isFundraiserEntitySearch == true) {
            if ($rootScope.isFundraiserEntitySearch)
                $rootScope.isCftOrganizationSearchBack = true;
            else
                $rootScope.isCftFeinOrganizationSearchBack = true;

            if ($rootScope.businessFilingType == "Renewal") {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navFundraiserRenewal();
            }
            else if ($rootScope.businessFilingType == "Closure") {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navFundraiserClose();
            }
            else {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navFundraiserAmendment();
            }
        }
        if ($rootScope.isBasicSearch) {
            $cookieStore.get('cftBasicSearchcriteria', $scope.criteria);
            $rootScope.isBasicSearchBack = true;
            // $scope.navCFTBusinessSearch();
            if ($rootScope.businessFilingType == "Renewal") {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navCharityRenewal();
            }
            else if ($rootScope.businessFilingType == "Closure") {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navCharityClose();
            }
            //else {
            //    $scope.navCFTBusinessSearch();
            //}
        } else {
            if ($rootScope.businessFilingType == "Renewal") {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navCharityRenewal();
            }
            else if ($rootScope.businessFilingType == "Closure") {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navCharityClose();
            }
            //else {
            //    $scope.navCFTBusinessSearch();
            //}
            $rootScope.isFundraiserEntitySearch = null;
        }


        if ($rootScope.isOptionalCharityEntitySearch) {
            $rootScope.isOptionalCftFeinOrganizationSearchBack = true;
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCharityOptionalUpdate();
        }
    }

    $scope.cftNavOrganizationReturnToSearch = function () {
        //Ticket -- 3167
        $rootScope.isCFTBackButtonPressed = true;
        $rootScope.isSearchNavClicked = false;
        if ($rootScope.isAdvanceSearch == true) {
            $rootScope.isCftOrganizationSearchBack = true;
            $rootScope.isBasicSearch = false;
            $rootScope.isBasicSearchBack = false;
            //$scope.navCFTSearch();
            $rootScope.isFundraiserEntitySearch = null;
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navNewCFTSearch();
        }

        if ($rootScope.isInitialSearch == true) {
            $cookieStore.get('cftAdvanceSearchcriteria');
            var isOptional = localStorage.getItem("isOptional");
            $rootScope.isCftOrganizationSearchBack = true;
            $rootScope.isBasicSearch = false;
            $rootScope.isBasicSearchBack = false;
            $rootScope.isFundraiserEntitySearch = null;
            if (isOptional)
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navCFTSearch();
            else
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navCFTSearch();
        }

        if ($rootScope.isAdvanceSearch == false) {
            $rootScope.isCftOrganizationSearchBack = true;
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCFTOrgBusinessDetails();
        }

        if ($rootScope.isCharityEntitySearch == true) {
            if ($rootScope.isCharityEntitySearch)
                $rootScope.isCftOrganizationSearchBack = true;
            else
                $rootScope.isCftFeinOrganizationSearchBack = true;

            var isOptional = localStorage.getItem("isOptional");
            if (isOptional == "true" || $rootScope.businessFilingType == "OptionalRenewal" || $rootScope.businessFilingType == "OptionalAmendment" || $rootScope.businessFilingType == "OptionalClosure") {
                if ($rootScope.businessFilingType == "OptionalRenewal")
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityOptionalRenewal();
                else if ($rootScope.businessFilingType == "OptionalAmendment")
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityOptionalAmendment();
                else
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityOptionalClosure();
            }
            else {
                if ($rootScope.businessFilingType == "Renewal")
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityRenewal();
                else if ($rootScope.businessFilingType == "Amendment")
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityAmendment();
                else
                    // Folder Name: controller
                    // File Name: rootController.js (you can search with file name in solution explorer)
                    $scope.navCharityClose();
            }
            $rootScope.isFundraiserEntitySearch = null;
        }
        if ($rootScope.isFundraiserEntitySearch == true) {
            if ($rootScope.isFundraiserEntitySearch)
            {
                $rootScope.isCftOrganizationSearchBack = true;
                $rootScope.isInitialSearch = null;
            }
            else
                $rootScope.isCftFeinOrganizationSearchBack = true;

            //$scope.navFundraiserAmendment();
            if ($rootScope.businessFilingType == "Renewal") {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navFundraiserRenewal();
            }
            else if ($rootScope.businessFilingType == "Closure") {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navFundraiserClose();
            }
            else {
                // Folder Name: controller
                // File Name: rootController.js (you can search with file name in solution explorer)
                $scope.navFundraiserAmendment();
            }
        }
        if ($rootScope.isBasicSearch) {
            $cookieStore.get('cftBasicSearchcriteria', $scope.criteria);
            $rootScope.isBasicSearchBack = true;
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCFTBusinessSearch();
        }
        if ($rootScope.isOptionalCharityEntitySearch) {
            $rootScope.isOptionalCftFeinOrganizationSearchBack = true;
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCharityOptionalUpdate();
        }
    }

    //to get docuemnts associated for the repective filing
    $scope.getTransactionDocumentsList = function (FilingNumber, Transactionid, Id) {
        var criteria = { ID: Transactionid, FilingNumber: FilingNumber, CharityId: Id, BusinessType: $rootScope.data.Businesstype }
        // getCFTTransactionDocumentsList method is available in constants.js
        wacorpService.post(webservices.CFT.getCFTTransactionDocumentsList, criteria, function success(response) {
            //if (response.data.length > 0) {
            $scope.transactionDocumentsList = response.data;
            $('#divSearchResult').show();
            $('#divSearchResult').modal('toggle')
            //}
        }, function failed(response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data)
        });

    };

    $scope.cancel = function () {
        $("#divSearchResult").modal('toggle');
    }
    $scope.$watch('cftSearchcriteria', function () {
        if ($scope.cftBusinessSearch == undefined)
            return;
        if ($scope.cftBusinessSearch == constant.ZERO) {
            $scope.totalCount = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.page = constant.ZERO;
        }
    }, true);

    //$scope.propertyName = 'FilingDate';
    //$scope.reverse = true;

    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };

    angular.isUndefinedOrNull = function (val) {
        return angular.isUndefined(val) || val === null
    }

    $scope.businessFilingSearch = function (cftId, filingType) {
        $cookieStore.put('cftMergerId', cftId);
        $cookieStore.put('cftMergerType', filingType);
        $("#divMergedCFTInfo").modal('toggle');
        $rootScope.$emit("CallMergerMethod", {});
    }

    $scope.closeMergerInfo = function () {
        $('#divMergedCFTInfo').modal('toggle');
    };

    $('.modal-dialog').draggable({
        handle: ".modal-header"
    });

});
wacorpApp.controller('mergedorganizationController', function ($scope, $http, $q, $timeout, $routeParams, $location, $rootScope, $window, $cookieStore, lookupService, wacorpService, ScopesData) {
    // variable initialization
    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.cftMergerSearchcriteria = {};
    $scope.cftBusinessSearchcriteria = {};
    $scope.isButtonSerach = false;
    $scope.cftBusinessSearch = [];
    $scope.criteria = [];
    $scope.Reasons = [];
    $scope.isAdvanceSearch = false;
    $scope.cftOrganizationSearchType = false;
    $scope.isCftOrganizationSearchBack = false;
    $scope.modal = $rootScope.Modal;
    $scope.transactionDocumentsList = [];
    $scope.cftMergerSearchcriteria = {
        EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false, EntityWebsite: null,
        RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, BusinessType: "", Type: "", ID: "", SearchValue: "", SearchCriteria: "",
    };

    var criteria = {
        CFTId: null,
        Businesstype: null,
    };

    var onMethod = $rootScope.$on("CallMergerMethod", function () {
        $scope.initMergedOrgBusinessSearch(); // initMergedOrgBusinessSearch method is available in this controller only.
    });

    $scope.$on('$destroy', function () {
        onMethod(); // onMethod method is available in this controller only.
    });

    //scope initialization
    $scope.initMergedOrgBusinessSearch = function () {
        var mergerId = $cookieStore.get('cftMergerId');
        var mergerType = $cookieStore.get('cftMergerType');
        if (mergerId != undefined && mergerType != undefined) {
            $scope.cftMergerSearchcriteria.CFTId = $cookieStore.get('cftMergerId');
            $scope.cftMergerSearchcriteria.Businesstype = $cookieStore.get('cftMergerType');
            execCurrentPath(); // execCurrentPath method is available in this controller only.
        }
    }

    function execCurrentPath() {
        loadCFList(constant.ZERO); // loadCFList method is available in this controller only.
    }

    // search Charity and Fundraiser list
    $scope.searchCF = function (searchform) {
        $scope.cftMergerSearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadCFList(searchform); // loadCFList method is available in this controller only.
    };
    // get Charity and Fundraiser list data from server
    function loadCFList(page) {

        var data = { params: { Type: $scope.cftMergerSearchcriteria.Businesstype, CharityID: $scope.cftMergerSearchcriteria.CFTId } };
        wacorpService.get(webservices.CFT.getcharityOrganization, data, function (response) {
            $scope.modal = response.data;
            $scope.isClosure = $scope.modal.Status == 'Closed' || $scope.modal.Status == 'Involuntarily Closed' ? true : false;
            $scope.isShowData = $scope.show == false ? true : false;
            $scope.modal.CFTType = $scope.cftMergerSearchcriteria.Businesstype;
            if ($scope.modal.CFTType == "Trust") {
                if ($scope.modal.TrustClosureReason && $scope.modal.TrustClosureReason.length > 0)
                    $scope.Reasons = $scope.modal.TrustClosureReason.split(',');
            }
            else {
                if ($scope.modal.CharitiesClosureReason && $scope.modal.CharitiesClosureReason.length > 0)
                    $scope.Reasons = $scope.modal.CharitiesClosureReason.split(',');
            }
            $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
            $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
            $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);
            $scope.modal.BondWaiversBondExpirationDate = wacorpService.dateFormatService($scope.modal.BondWaiversBondExpirationDate);
            $scope.modal.LegalInfo.LastName = $scope.modal.LegalInfo.LastName == null ? "" : $scope.modal.LegalInfo.LastName;
            $scope.modal.LegalInfo.FirstName = $scope.modal.LegalInfo.FirstName == null ? "" : $scope.modal.LegalInfo.FirstName;
            $scope.modal.LegalInfo.EntityRepresentativeFirstName = $scope.modal.LegalInfo.EntityRepresentativeFirstName == null ? "" : $scope.modal.LegalInfo.EntityRepresentativeFirstName;
            $scope.modal.LegalInfo.EntityRepresentativeLastName = $scope.modal.LegalInfo.EntityRepresentativeLastName == null ? "" : $scope.modal.LegalInfo.EntityRepresentativeLastName;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    // display CFT  business filings
    $scope.cftSearchBusinessFilings = function () {
        $scope.cftMergerSearchcriteria.ID = $scope.cftMergerSearchcriteria.CFTId;
        $scope.cftMergerSearchcriteria.BusinessType = $scope.cftMergerSearchcriteria.Businesstype;
        var data = angular.copy($scope.cftMergerSearchcriteria);
        // getCftSearchOrganizationFillings method is available in constants.js
        wacorpService.post(webservices.CFT.getCftSearchOrganizationFillings, data, function (response) {
            if (response.data != null) {
                $scope.cftBusinessFilings = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.cftBusinessFilings.FilingDateTime = wacorpService.dateFormatService($scope.cftBusinessFilings.FilingDateTime);
                $('#divMergedFilingHistory').modal('toggle');
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.closeFilingHistory = function () {
        $('#divMergedFilingHistory').modal('toggle');
    };

    // display CFT business names history list
    $scope.getCftBusinessNameHistoryList = function () {
        $scope.cftMergerSearchcriteria.ID = $scope.cftMergerSearchcriteria.CFTId;
        $scope.cftMergerSearchcriteria.BusinessType = $scope.cftMergerSearchcriteria.Businesstype;
        var data = angular.copy($scope.cftMergerSearchcriteria);
        // getCftSearchOrganizationNameHistoryList method is available in constants.js
        wacorpService.post(webservices.CFT.getCftSearchOrganizationNameHistoryList, data, function success(response) {
            if (response.data.length > 0) {
                $scope.cftBusinessNameHistoryList = response.data;
            }
            $('#divMergedNameHistory').modal('toggle');
        }, function failed(response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data)
        });
    };

    $scope.closeNameHistory = function () {
        $('#divMergedNameHistory').modal('toggle');
    };

    //navigate to business information
    $scope.showBusineInfo = function (id, businessType) {
        $scope.cftBusinessSearch.CFTId = id;
        $scope.cftBusinessSearch.Businesstype = businessType;
        $rootScope.data = $scope.cftBusinessSearch.length > 0 ? $scope.cftBusinessSearch : $rootScope.data;
        $cookieStore.put('cftBusinessSearchcriteriaId', $scope.cftBusinessSearch.CFTId);
        $cookieStore.put('cftBusinessSearchcriteriaType', $scope.cftBusinessSearch.Businesstype);
        // Folder Name: controller
        // File Name: rootController.js (you can search with file name in solution explorer)
        $scope.navCharityFoundationOrganization();
    }



    //to get docuemnts associated for the repective filing
    $scope.getTransactionDocumentsList = function (FilingNumber, Transactionid, Id) {
        var criteria = { ID: Transactionid, FilingNumber: FilingNumber, CharityId: Id, BusinessType: $rootScope.data.Businesstype }
        // getCFTTransactionDocumentsList method is available in constants.js
        wacorpService.post(webservices.CFT.getCFTTransactionDocumentsList, criteria, function success(response) {
            //if (response.data.length > 0) {
            $scope.transactionDocumentsList = response.data;
            $('#divDocumentsResult').modal('toggle')
            //}
        }, function failed(response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data)
        });

    };

    $scope.closeDocumentsModal = function () {
        $("#divDocumentsResult").modal('toggle');
    }
    $scope.$watch('cftMergerSearchcriteria', function () {
        if ($scope.cftBusinessSearch == undefined)
            return;
        if ($scope.cftBusinessSearch == constant.ZERO) {
            $scope.totalCount = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.page = constant.ZERO;
        }
    }, true);

    //$scope.propertyName = 'FilingDate';
    //$scope.reverse = true;

    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };

    angular.isUndefinedOrNull = function (val) {
        return angular.isUndefined(val) || val === null
    }

});
wacorpApp.controller('charitiesSearchController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;

    /* --------Business Search Functionality------------- */

    $rootScope.charitySearchPath = $routeParams.charitySearchType;
    $scope.selectedEntity = null;
    $scope.submitCharityEntity = getNavigation;

    function getNavigation() {
        $rootScope.CharityID = $scope.selectedEntity.CFTId;
        if ($rootScope.charitySearchPath == 'Renewal') {
            $location.path('/charitiesRenewal/' + $scope.selectedEntity.CFTId);

            //if (!$scope.selectedEntity.IsOptionalRegistration)
            //    $location.path('/charitiesRenewal/' + $scope.selectedEntity.CFTId);
            //else
            //    wacorpService.alertDialog("Optional Renewal cannot file charitable organization renewal");
        }
        if ($rootScope.charitySearchPath == 'Amendment') {
            $location.path('/charitiesAmendment/' + $scope.selectedEntity.CFTId);

            //if (!$scope.selectedEntity.IsOptionalRegistration)
            //    $location.path('/charitiesAmendment/' + $scope.selectedEntity.CFTId);
            //else
            //    wacorpService.alertDialog("Optional Amendment cannot file charitable organization amendment");
        }
        if ($rootScope.charitySearchPath == 'Closure') {
            if (!$scope.selectedEntity.IsOptionalRegistration)
                 $location.path('/charitiesClosure/' +$scope.selectedEntity.CFTId);
        else
            wacorpService.alertDialog("Cannot file an optional closure for charitable organization");
        }
        if ($rootScope.charitySearchPath == 'OptionalRenewal') {
            $location.path('/charitiesOptionalRenewal/' + $scope.selectedEntity.CFTId);
        }
        if ($rootScope.charitySearchPath == 'OptionalAmendment') {
            $location.path('/charitiesOptionalAmendment/' + $scope.selectedEntity.CFTId);
        }
        if ($rootScope.charitySearchPath == 'OptionalClosure') {
            if ($scope.selectedEntity.IsOptionalRegistration)
                $location.path('/charitiesOptionalClosure/' + $scope.selectedEntity.CFTId);
            else
                wacorpService.alertDialog("You are not registered as Optional Registration");
        }
        if ($rootScope.charitySearchPath == 'FundraiserServiceContract') {
            $location.path('/submitFundraisingServiceContract/' + $scope.selectedEntity.CFTId);

            //if ($scope.selectedEntity.IsOptionalRegistration) {
            //    wacorpService.alertDialog("This record belongs to Optional Registration filing, please choose charities records only to continue");
            //}
            //else {
            //    $location.path('/submitFundraisingServiceContract/' + $scope.selectedEntity.CFTId);
            //}
        }
        if ($rootScope.charitySearchPath == 'FundraiserServiceContractAmendment') {
            $location.path('/submitFundraisingServiceContractAmendment/' + $scope.selectedEntity.CFTId);
        }
        //if ($rootScope.charitySearchPath == 'OptionalRegistrationUpdate') {
        //    $location.path('/charitiesOptionalRegistrationUpdate/' + $scope.selectedEntity.CFTId);
        //}
    }

});



wacorpApp.controller('charitiesRenewalController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------- Charities Renewal Functionality------------- */

    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    var originalEntityName = "";

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.getCharitiesDetails();
        $("div.error-messages").addClass('ng-hide');
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }


    //Get Charities Details from Registration Number
    $scope.getCharitiesDetails = function () {
        // here BusinessTypeID = 7 is charity business type
        $rootScope.BusinessTypeID = 7;

        var isOptional = localStorage.getItem("isOptional");

        if ($routeParams.CharityID != undefined) {
            $rootScope.CharityID = $routeParams.CharityID;
        }
        var data = null;

        if (isOptional == "true") {
            if ($rootScope.transactionID > 0) 
                // here filingTypeID: 162 is CHARITABLE ORGANIZATION OPTIONAL RENEWAL
                data = { params: { CharityID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 162, transactionID: $rootScope.transactionID } };
            else
                data = { params: { CharityID: $routeParams.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 162, transactionID: $rootScope.transactionID } };
        }
        else {
            if ($rootScope.transactionID > 0)
                // here filingTypeID: 160 is CHARITABLE ORGANIZATION RENEWAL
                data = { params: { CharityID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 160, transactionID: $rootScope.transactionID } };
            else
                data = { params: { CharityID: $rootScope.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 160, transactionID: $rootScope.transactionID } };
        }

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.CharityID == undefined || $rootScope.CharityID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/charitiesSearch');
            }
            // getCharitiesRenewalDetails method is available in constants.js
            wacorpService.get(webservices.CFT.getCharitiesRenewalDetails, data, function (response) {
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                originalEntityName = $scope.modal.EntityName;
                $scope.modal.UBIOtherDescp = $scope.modal.UBIOtherDescp || null;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);

                $scope.modal.OldIsFederalTax = $scope.modal.IsFederalTax;
                $scope.modal.OldIsShowFederalTax = $scope.modal.IsShowFederalTax;
                if (isOptional == "false") {
                    $scope.modal.IsOptionalRegistration = false;
                    $rootScope.OptionalData = null;
                } else if (isOptional == "true") {
                    $scope.modal.IsOptionalRegistration = true;
                }

                if ($rootScope.OptionalData != null && $rootScope.OptionalData != undefined) {
                    $scope.modal.IsIntegratedAuxiliary = $rootScope.OptionalData.IntegratedAuxiliary == "Yes" ? true : false;
                    $scope.modal.IsPoliticalOrganization = $rootScope.OptionalData.PoliticalOrganization == "Yes" ? true : false;
                    $scope.modal.IsRaisingFundsForIndividual = $rootScope.OptionalData.RaisingFundsForIndividual == "Yes" ? true : false;
                    $scope.modal.IsRaisingLessThan50000 = $rootScope.OptionalData.RaisingLessThan50000 == "Yes" ? true : false;
                    $scope.modal.IsAnyOnePaid = $rootScope.OptionalData.AnyOnePaid == "Yes" ? true : false;
                    $scope.modal.IsInfoAccurate = $rootScope.OptionalData.InfoAccurate == "Yes" ? true : false;
                }
                else {
                    $scope.modal.IsIntegratedAuxiliary = $scope.modal.IsIntegratedAuxiliary;
                    $scope.modal.IsPoliticalOrganization = $scope.modal.IsPoliticalOrganization;
                    $scope.modal.IsRaisingFundsForIndividual = $scope.modal.IsRaisingFundsForIndividual;
                    $scope.modal.IsRaisingLessThan50000 = $scope.modal.IsRaisingLessThan50000;
                    $scope.modal.IsAnyOnePaid = $scope.modal.IsAnyOnePaid;
                    $scope.modal.IsInfoAccurate = $scope.modal.IsInfoAccurate;
                }
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
                $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);
                $scope.FirstAccountingyearEndDate = new Date();
                $scope.FirstAccountingyearEndDate = $scope.modal.FirstAccountingyearEndDate;
                var accEndDate;


                if ($scope.modal.IsActiveFilingExist) {
                    //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js 
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);
                if ($scope.modal.IsFIFullAccountingYear)
                    $scope.modal.oldFiscalYear = $scope.modal.AccountingyearBeginningDate != '01/01/0001' || $scope.modal.AccountingyearBeginningDate != null ? $scope.modal.AccountingyearBeginningDate : null;
                else
                    $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingyearEndDate != '01/01/0001' || $scope.modal.FirstAccountingyearEndDate != null ? $scope.modal.FirstAccountingyearEndDate : null;

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                //$scope.modal.FEINNumber = $scope.modal.FEINNumber || null;
                //$scope.modal.IsOrgNameExists = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "" && $scope.modal.EntityName != null && $scope.modal.EntityName != "" ? true : false;
                $scope.modal.UBINumber = $scope.modal.UBINumber || null;
                $scope.modal.AKANamesList = $scope.modal.AKANamesList || null;
                if ($scope.modal.FederaltaxUpload.length > 0)
                    $scope.modal.FederaltaxUpload.length = 0;
                //$scope.modal.IsShowFederalTax = $scope.modal.FederaltaxUpload.length > 0 ? true : false;
                $scope.modal.FinancialId = $scope.modal.FinancialId || null;
                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.IsFIFullAccountingYear) {
                        if ($scope.modal.AccountingyearEndingDate != "01/01/0001") {
                            accEndDate = new Date($scope.modal.AccountingyearEndingDate);
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            accEndDate = wacorpService.dateFormatService(accEndDate.setDate(accEndDate.getDate() + 1));
                            $scope.modal.AccountingyearBeginningDate = accEndDate;
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.claculateEndDate(accEndDate));
                            $scope.modal.IsRenewalMinDates = false;
                        }
                        else
                            $scope.modal.IsRenewalMinDates = true;

                    }
                    else {
                        if ($scope.modal.FirstAccountingyearEndDate != null && $scope.modal.FirstAccountingyearEndDate != '01/01/0001') {

                            var _enddate = new Date($scope.modal.FirstAccountingyearEndDate);
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.calculateAccountingYearBgnDate(_enddate));
                            $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.calculateEndDate($scope.modal.AccountingyearBeginningDate));

                            //accEndDate = new Date($scope.modal.FirstAccountingyearEndDate);
                            //$scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.claculateEndDate(accEndDate));
                            //var beginDate = new Date($scope.FirstAccountingyearEndDate);
                            //beginDate = wacorpService.dateFormatService(beginDate.setDate(beginDate.getDate() + 1));
                            //$scope.modal.AccountingyearBeginningDate = beginDate;

                            $scope.modal.IsFIFullAccountingYear = true;
                            $scope.modal.BeginingGrossAssets = $scope.modal.EndingGrossAssets != null ? $scope.modal.EndingGrossAssets : null;
                            $scope.modal.IsRenewalMinDates = false;
                        }
                        else {
                            $scope.modal.IsRenewalMinDates = true;
                            //$scope.modal.AccountingyearBeginningDate = beginDate;
                            $scope.modal.IsFIFullAccountingYear = true;
                        }
                    }
                    if ($scope.modal.AccountingyearBeginningDate != "01/01/0001") //added on 9/13/2017
                    {
                        $scope.modal.BeginingGrossAssets = $scope.modal.EndingGrossAssets != null ? $scope.modal.EndingGrossAssets : null;
                        $scope.modal.EndingGrossAssets = null;
                        $scope.modal.RevenueGDfromSolicitations = null;
                        $scope.modal.RevenueGDRevenueAllOtherSources = null;
                        $scope.modal.ExpensesGDExpendituresProgramServices = null;
                        $scope.modal.ExpensesGDValueofAllExpenditures = null;
                        $scope.modal.TotalDollarValueofGrossReceipts = null;
                        $scope.modal.PercentToProgramServices = null;
                    }
                }

                //$scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets || null;
                //$scope.modal.RevenueGDfromSolicitations = $scope.modal.RevenueGDfromSolicitations || null;
                //$scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.RevenueGDRevenueAllOtherSources || null;
                //$scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts || null;

                //$scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.ExpensesGDExpendituresProgramServices || null;
                //$scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures || null;
                //$scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets || null;


                $scope.modal.ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.ContributionServicesTypeId) ? [] : $scope.modal.ContributionServicesTypeId.split(',');
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');

                $scope.modal.CharityAkaInfoEntity.CountiesServedId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CountiesServedId) ? [] : $scope.modal.CharityAkaInfoEntity.CountiesServedId.split(',');
                $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId) ? [] : $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.split(',');
                $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress != null ? $scope.modal.EntityStreetAddress : null;
                $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress != null ? $scope.modal.EntityMailingAddress : null;
                $scope.modal.EntityStreetAddress.IsSameAsEntityMailingAddress = $scope.modal.IsSameAsEntityMailingAddress;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country;

                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : "I";
                $scope.modal.LegalInfo.IsAnyLegalActions = $scope.modal.LegalInfo.IsAnyLegalActions || false;
                $scope.modal.LegalInfoEntityList = $scope.modal.LegalInfoEntityList != null ? $scope.modal.LegalInfoEntityList : null;

                //$scope.modal.EntityMailingAddress.State = codes.WA; //$scope.modal.EntityMailingAddress.Country = codes.USA;
                //$scope.modal.EntityStreetAddress.State = codes.WA; //$scope.modal.EntityStreetAddress.Country = codes.USA;
                //$scope.modal.LegalInfo.LegalInfoAddress.State = codes.WA; //$scope.modal.LegalInfo.LegalInfoAddress.Country = codes.USA;
                //$scope.modal.LegalInfo.LegalInfoTypeID = 'I';
                $scope.modal.AKASolicitNameId = '';
                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;

                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if (!($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == undefined))
                    $scope.modal.JurisdictionCountry = $scope.modal.JurisdictionCountry == 0 ? '' : $scope.modal.JurisdictionCountry.toString();

                if (!($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == undefined))
                    $scope.modal.JurisdictionState = $scope.modal.JurisdictionState == 0 ? '' : $scope.modal.JurisdictionState.toString();

                if (!($scope.modal.FederalTaxExemptId == null || $scope.modal.FederalTaxExemptId == undefined))
                    $scope.modal.FederalTaxExemptId = $scope.modal.FederalTaxExemptId == 0 ? '' : $scope.modal.FederalTaxExemptId.toString();

                if (!($scope.modal.OSJurisdictionCountyId == null || $scope.modal.OSJurisdictionCountyId == undefined))
                    $scope.modal.OSJurisdictionCountyId = $scope.modal.OSJurisdictionCountyId == 0 ? '' : $scope.modal.OSJurisdictionCountyId.toString();

                if (!($scope.modal.OSJurisdictionStateId == null || $scope.modal.OSJurisdictionStateId == undefined))
                    $scope.modal.OSJurisdictionStateId = $scope.modal.OSJurisdictionStateId == 0 ? '' : $scope.modal.OSJurisdictionStateId.toString();

                //if ($scope.modal.OfficersHighPayList != null && $scope.modal.OfficersHighPayList.length >= 3)
                //    $scope.modal.OfficersHighPay.IsCountMax = true;
                //else
                //    $scope.modal.OfficersHighPay.IsCountMax = false;

                if ($scope.modal.OfficersHighPayList.length > 0) {
                    angular.forEach($scope.modal.OfficersHighPayList, function (cftHihPay) {
                        cftHihPay.SequenceNo = cftHihPay.ID;
                    });
                }

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.CFTOfficersList.length > 0) {
                    angular.forEach($scope.modal.CFTOfficersList, function (cftOffice) {
                        cftOffice.SequenceNo = cftOffice.OfficerID;
                    });
                    }
                }
                
                if ($scope.modal.LegalInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.LegalInfoEntityList, function (cftLegalInfo) {
                        cftLegalInfo.SequenceNo = cftLegalInfo.LegalInfoId;
                    });
                }

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaEntity) {
                        akaEntity.SequenceNo = akaEntity.AKASolicitNameId;
                    });
                }
                if ($scope.modal.FundraisersList.length > 0) {
                    angular.forEach($scope.modal.FundraisersList, function (fundraiser) {
                        fundraiser.SequenceNo = fundraiser.CFTID;
                    });
                }
                if ($scope.modal.AKANamesList.length > 0) {
                    angular.forEach($scope.modal.AKANamesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }
                 
                $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.
                $scope.ValidateRenewalDate(); // ValidateRenewalDate method is available in this controller only.
                $scope.modal.isShowReturnAddress = true;

            }, function (response) {
            });
        }
        else {
            $scope.modal = $rootScope.modal;
            if (isOptional == "false")
                $scope.modal.IsOptionalRegistration = false;

            if ($scope.modal.IsOptionalRegistration && $rootScope.OptionalData != null && $rootScope.OptionalData != undefined) {
                $scope.modal.IsIntegratedAuxiliary = $rootScope.OptionalData.IntegratedAuxiliary == "Yes" ? true : false;
                $scope.modal.IsPoliticalOrganization = $rootScope.OptionalData.PoliticalOrganization == "Yes" ? true : false;
                $scope.modal.IsRaisingFundsForIndividual = $rootScope.OptionalData.RaisingFundsForIndividual == "Yes" ? true : false;
                $scope.modal.IsRaisingLessThan50000 = $rootScope.OptionalData.RaisingLessThan50000 == "Yes" ? true : false;
                $scope.modal.IsAnyOnePaid = $rootScope.OptionalData.AnyOnePaid == "Yes" ? true : false;
                $scope.modal.IsInfoAccurate = $rootScope.OptionalData.InfoAccurate == "Yes" ? true : false;
            }
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.

            //Assigning 0's to Empty
            $scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets == 0 ? null : $scope.modal.EndingGrossAssets;
            $scope.modal.RevenueGDfromSolicitations = $scope.modal.RevenueGDfromSolicitations == 0 ? null : $scope.modal.RevenueGDfromSolicitations;
            $scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.RevenueGDRevenueAllOtherSources == 0 ? null : $scope.modal.RevenueGDRevenueAllOtherSources;
            $scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.ExpensesGDExpendituresProgramServices == 0 ? null : $scope.modal.ExpensesGDExpendituresProgramServices;
            $scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures == 0 ? null : $scope.modal.ExpensesGDValueofAllExpenditures;
            $scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts == 0 ? null : $scope.modal.TotalDollarValueofGrossReceipts;
            $scope.modal.PercentToProgramServices = $scope.modal.PercentToProgramServices == 0 ? null : $scope.modal.PercentToProgramServices;
            $scope.modal.isShowReturnAddress = true;
        }
    };


    $scope.checkHighpayCount = function () {
        var count = 0;
        angular.forEach($scope.modal.OfficersHighPayList, function (highpayItem) {
            if (highpayItem.Status != "D") {
                count++;
            }
        });

        if (count >= 3) {
            $scope.modal.OfficersHighPay.IsCountMax = true;
        }
        else {
            $scope.modal.OfficersHighPay.IsCountMax = false;
        }
        return count <= 0;
    };

    $scope.ValidateRenewalDate = function () {
        var result = $scope.modal.ErrorMsg == null || $scope.modal.ErrorMsg == "" ? true : false;
        if (!result) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.modal.ErrorMsg);
            return false;
        }
        return true;
    };

    $scope.checkFederalCount = function () {
        var count = 0;
        angular.forEach($scope.modal.FederaltaxUpload, function (value) {
            if (value.Status != 'D')
                count++;
        });
        if (count == 0 || count == undefined)
            return $scope.modal.FederaltaxUpload.length = 0;
        else
            return $scope.modal.FederaltaxUpload.length = count;
    };

    $scope.Review = function (charitiesRenewalForm) {
        // ValidateRenewalDate method is available in this controller only.
        if ($scope.ValidateRenewalDate()) {
            //if (!$scope.modal.IsAnyOnePaid) {
            $scope.validateErrorMessage = true;

            var endDate = $scope.modal.AccountingyearEndingDate;
            if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                if (isEndDateMore) {
                    // Folder Name: app Folder
                    // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                    return false;
                }
            }

            //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {
            //var isFeinValid = ($scope.modal.UBINumber != "" ? $scope.modal.IsUBINumberExistsorNot : true) && $scope.charitiesRenewalForm.fein.$valid;

            //var isErrorMsg = $scope.ValidateRenewalDate()?true:false;

            var isOrgNameValid = $scope.modal.EntityName != null ? true : false;

            var isPurposeValid = $scope.modal.Purpose != null ? true : false;

            var isTaxUploadValid = $scope.modal.IsShowFederalTax ? ($scope.checkFederalCount() > 0 ? true : false) : true;

            //var isEntityNameValid = $scope.modal.isBusinessNameAvailable ? true : false;

            //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);

            $scope.EntityNameCheck = true;

            $scope.modal.NewEntityName = $scope.modal.EntityName;

            if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
                if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                    $scope.modal.isBusinessNameChanged = true;
                }
                else {
                    $scope.modal.isBusinessNameChanged = false;
                }
            }

            //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);
            //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase(originalEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));
            //var isEntityNameValid = ($scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true: ($scope.modal.isBusinessNameChanged ? false: true)));
            var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

            if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
                $scope.EntityNameCheck = false;
            }
            else {
                $scope.EntityNameCheck = true;
            }

            var isEntityInfo = ($scope.charitiesRenewalForm.entityInfo.$valid);

            var isExpensesValid = ($scope.modal.IsFIFullAccountingYear ? ($scope.modal.ExpensesGDValueofAllExpenditures < $scope.modal.ExpensesGDExpendituresProgramServices ? false : true) : true);

            //To not validate inner form from outer form removed control
            //if (!($scope.charitiesRenewalForm.CharityOrganizationForm.akaNames == null || $scope.charitiesRenewalForm.CharityOrganizationForm.akaNames == undefined))
            //    $scope.charitiesRenewalForm.CharityOrganizationForm.$removeControl($scope.charitiesRenewalForm.CharityOrganizationForm.akaNames);

            //var isCharityOrgFormValid = ($scope.charitiesRenewalForm.CharityOrganizationForm.$valid);

            var isCharitiesFinancialInfo = ($scope.charitiesRenewalForm.CharityFinancialInfoForm.$valid);

            var isOfficerHighpay = !$scope.modal.OfficersHighPay.IsPayOfficers || ($scope.modal.OfficersHighPay.IsPayOfficers && !$scope.checkHighpayCount());

            var isCftOfficesListValid = ($scope.checkOfficersCount() > 0);

            var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

            var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalActionsUploads.length > 0 ? true : false) : true);

            var isLegalInfo = ($scope.charitiesRenewalForm.fundraiserLegalInfo.$valid);

            var isFundraiserListValid = true;
            if ($scope.modal.IsCommercialFundraisersContributionsInWA) {
                isFundraiserListValid = $scope.checkFundraisersCount(); // checkFundraisersCount method is available in this controller only.
                if (isFundraiserListValid) {
                    $scope.modal.isFundraiserRequired = false;
                }
                else {
                    $scope.modal.isFundraiserRequired = true;
                }
            }

            //var isGreenCrossEnrolltoCFD = true;
            //if ($scope.modal.IsGreenCross)
            //    isGreenCrossEnrolltoCFD = $scope.modal.IsAkaProgramsinCFD ? $scope.charitiesRenewalForm.enrollToCFDForm.greenCrossCfdDetails.$valid : true;

            var Fein = $scope.modal.FEINNumber;
            var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

            var Ubi = $scope.modal.UBINumber;
            // here JurisdictionState = 271 is Washington
            var isValidUbi = $scope.modal.IsEntityRegisteredInWA && $scope.modal.JurisdictionState == "271" ?
                (Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9 ? true : false) : (Ubi == null || Ubi == '' || Ubi.length == 9 ? true : false);

            var isSignatureAttestationValidate = ($scope.charitiesRenewalForm.SignatureForm.$valid);
            //var isCorrespondenceAddressValid = $scope.charitiesRenewalForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.charitiesRenewalForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
            var isCorrespondenceAddressValid = $scope.charitiesRenewalForm.cftCorrespondenceAddressForm.$valid;

            //var isFormValidate = isEntityNameValid && isEntityInfo && isCharityOrgFormValid && isCharitiesFinancialInfo && isCftOfficesListValid && isLegalInfo &&
            //        isFundraiserListValid && isGreenCrossEnrolltoCFD && isSignatureAttestationValidate; // by 1504 - 23/06/2017

            //Upload Additional Documents
            var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

            var isFormValidate = isOrgNameValid && isPurposeValid && isTaxUploadValid && isEntityNameValid && isEntityInfo && isExpensesValid && isCharitiesFinancialInfo && isOfficerHighpay && isCftOfficesListValid &&
                            isLegalActionsListValid && isLegalActionsUploadValid && isLegalInfo && isCorrespondenceAddressValid && isFundraiserListValid && isSignatureAttestationValidate && isValidFein && isValidUbi && isAdditionalUploadValid;

            $scope.fillRenewalData(); // fillRenewalData method is available in this controller only.

            if ($scope.modal.IsOptionalRegistration) {
                var IsQualified = ($scope.modal.IsIntegratedAuxiliary || $scope.modal.IsPoliticalOrganization
                        || $scope.modal.IsRaisingFundsForIndividual || $scope.modal.IsRaisingLessThan50000 || $scope.modal.IsAnyOnePaid);
                if (isFormValidate && IsQualified && $scope.modal.IsInfoAccurate) {
                    $scope.validateErrorMessage = false;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
                    $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
                    $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);
                    var isOptionalReg = wacorpService.validateOptionalQualifiers($scope.modal.IsIntegratedAuxiliary, $scope.modal.IsPoliticalOrganization, $scope.modal.IsRaisingFundsForIndividual, $scope.modal.IsRaisingLessThan50000, $scope.modal.IsAnyOnePaid);
                    if (isOptionalReg) {
                        $scope.isReview = true;
                        $location.path('/charitiesOptionalRenewalReview');
                    }
                    else {
                        // Folder Name: app Folder
                        // Alert Name: qualifier method is available in alertMessages.js
                        wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifier);
                        $rootScope.modal = null;
                        //$location.path("/charitiesRegistration");
                    }
                }
                else {
                    // Folder Name: app Folder
                    // Alert Name: InvalidFilingMsg method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
                }
            }
            else {
                if (isFormValidate) {
                    $scope.validateErrorMessage = false;
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
                    $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
                    $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);
                    $scope.isReview = true;
                    $location.path('/charitiesRenewalReview');
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: InvalidFilingMsg method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
            }
            //}
            //else {
            //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
            //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
            //        return false;
            //    }
            //}
            //}
            //else {
            //    wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifierRenewal);
            //    $rootScope.modal = null;
            //    $scope.navCharityRegistration();
            //}
        }

    };

    $scope.fillRenewalData = function () {

        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.EntityName = $scope.modal.EntityName || null;
        $scope.modal.FinancialId = $scope.modal.FinancialId || null;
        if ($scope.modal.IsFIFullAccountingYear)
            $scope.modal.oldFiscalYear = $scope.modal.AccountingyearBeginningDate != '01/01/0001' || $scope.modal.AccountingyearBeginningDate != null ? $scope.modal.AccountingyearBeginningDate : null;
        else
            $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingyearEndDate != '01/01/0001' || $scope.modal.FirstAccountingyearEndDate != null ? $scope.modal.FirstAccountingyearEndDate : null;

        $scope.modal.OSJurisdictionId = $scope.modal.OSJurisdictionStateId != "" ? $scope.modal.OSJurisdictionStateId : $scope.modal.OSJurisdictionCountyId;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }

        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }

        if ($scope.modal.CharityAkaInfoEntity.CountiesServedId != null && $scope.modal.CharityAkaInfoEntity.CountiesServedId.length > 0) {
            $scope.modal.CharityAkaInfoEntity.CountiesServedId = $scope.modal.CharityAkaInfoEntity.CountiesServedId.join(",");
        }
        if ($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId != null && $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.length > 0) {
            $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.join(",");
        }

        if ($scope.modal.OfficersHighPayList != null && $scope.modal.OfficersHighPayList.length == 3)
            $scope.modal.OfficersHighPay.IsCountMax = true;

        if ($scope.modal.CharityAkaInfoEntityList != null && $scope.modal.CharityAkaInfoEntityList.length > 0) {
            angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                if (akaInfo.CountiesServedId != null && akaInfo.CountiesServedId.length > 0)
                    akaInfo.CountiesServedId = akaInfo.CountiesServedId.join(",");
                if (akaInfo.CategoryOfServiceId != null && akaInfo.CategoryOfServiceId.length > 0)
                    akaInfo.CategoryOfServiceId = akaInfo.CategoryOfServiceId.join(",");
            });
        }
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;

        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
        $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
        $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

        $scope.modal.EntityStreetAddress.IsAddressSame = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName;
        $scope.modal.IsCommercialFundraisersContributionsInWA = $scope.modal.IsCommercialFundraisersContributionsInWA;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        //if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
        //    $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $rootScope.modal = $scope.modal;
    };

    $scope.RenewalSaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillRenewalData();
        if ($scope.modal.IsOptionalRegistration) {
            $scope.modal.OnlineNavigationUrl = "/charitiesOptionalRenewal";
        }
        else {
            $scope.modal.OnlineNavigationUrl = "/charitiesRenewal";
        }
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.checkOfficersCount = function () {
        var count = 0;
        angular.forEach($scope.modal.CFTOfficersList, function (value) {
            if (value.OfficerStatus != 'D')
                count++;
        });

        if (count == 0 || count == undefined)
            return $scope.modal.CFTOfficersList.length = 0;
        else
            return $scope.modal.CFTOfficersList.length;
    };

    $scope.checkFundraisersCount = function () {
        var delCount = 0;
        var listCount = 0;
        //listCount = $scope.modal.FundraisersList.length;
        //delCount = $scope.modal.FundraisersList.length;
        angular.forEach($scope.modal.FundraisersList, function (value) {
            if (value.Status != 'D')
                delCount++;
        });

        if (delCount > 0)
            return true;
        else
            return false;
    };

    $scope.claculateEndDate = function (value) {
        if (value != null && value != undefined) {
            var endDate = new Date(value);
            endDate.setYear(endDate.getFullYear() + 1);
            var firstDay = new Date(endDate.getFullYear(), endDate.getMonth(), 1);
            var lastDay = new Date(endDate.getFullYear(), endDate.getMonth(), 0);
            var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
            return lastDayWithSlashes;
        }
    }

    $scope.calculateEndDate = function (value) {
        if (value != null && value != undefined) {
            var endDate = new Date(value);
            endDate.setYear(endDate.getFullYear() + 1);
            var firstDay = new Date(endDate.getFullYear(), endDate.getMonth(), 1);
            var lastDay = new Date(endDate.getFullYear(), endDate.getMonth(), 0);
            var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
            return lastDayWithSlashes;
        }
    }

    //TFS 1159 Old Code
    $scope.calculateAccountingYearBgnDate = function (value) {
        if (value != null && value != undefined) {
            var accEndDate = new Date(value)
            accEndDate = new Date(accEndDate.setMonth(accEndDate.getMonth() - 11))
            accEndDate = new Date(accEndDate.getFullYear(), accEndDate.getMonth(), 1)
            return accEndDate;
        }
    }
    //TFS 1159 Old Code

    //TFS 1159 Updated Code
    //$scope.calculateAccountingYearBgnDate = function (value) {
    //    if (value != null && value != undefined) {
    //        var accEndDate = new Date(value);
    //        //TFS 1159 Updated Logic
    //        //Note: months are 0-11
    //        //if (accEndDate.getMonth() < 11) {  //month 0-10 (not december)
    //        //    var getStartMonth = accEndDate.getMonth() + 1;  //get next month
    //        //    var getStartYear = accEndDate.getFullYear() - 1;  //get previous year
    //        //} else {  //month 11 = 1/1/YYYY to 12/31/YYYY
    //        //    var getStartMonth = 0; //get month 0 (January)
    //        //    var getStartYear = accEndDate.getFullYear();  //no year change
    //        //}
            
            
    //        //accEndDate = new Date(getStartYear, getStartMonth);
    //        //return accEndDate;
    //        
    //    }
    //}
    //TFS 1159 Updated Logic


    $scope.RenewalBack = function () {

        $scope.fillRenewalData(); // fillRenewalData method is available in this controller only.
        var optioanlData = {
            IntegratedAuxiliary: $scope.modal.IsIntegratedAuxiliary ? "Yes" : "No",
            PoliticalOrganization: $scope.modal.IsPoliticalOrganization ? "Yes" : "No",
            RaisingFundsForIndividual: $scope.modal.IsRaisingFundsForIndividual ? "Yes" : "No",
            RaisingLessThan50000: $scope.modal.IsRaisingLessThan50000 ? "Yes" : "No",
            AnyOnePaid: $scope.modal.IsAnyOnePaid ? "Yes" : "No",
            InfoAccurate: $scope.modal.IsInfoAccurate ? "Yes" : "No",
        };
        $rootScope.OptionalData = optioanlData;
        //localStorage.setItem('isRenewal',true);
        $rootScope.isRenewal = true;
        localStorage.setItem("IsBack", true);
        $location.path("/charitiesOptionalQualifier");

    };
});

wacorpApp.controller('charitiesRenewalReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Charities Registration Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        $scope.modal = $rootScope.modal;
    };

    $scope.CharitiesRenewalAddToCart = function () {
        if ($scope.modal.ContributionServicesTypeId!=null && $scope.modal.ContributionServicesTypeId.length > 0)
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");

        if ($scope.modal.FinancialInfoStateId!=null && $scope.modal.FinancialInfoStateId.length > 0)
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        //CharitiesAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
                $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
                $rootScope.modal = null;
                $rootScope.OptionalData = null;
                $rootScope.isRenewal = false;
                resetLocalStorage(); // resetLocalStorage method is available in this controller only.
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        if ($scope.modal.IsOptionalRegistration) {
            $location.path('/charitiesOptionalRenewal');
        }
        else {
            $location.path('/charitiesRenewal');
        }
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }
    function resetLocalStorage() {
        //localStorage.removeItem('isRenewal');
        localStorage.removeItem("IsBack");
        localStorage.removeItem('isOptional');
    }
});

wacorpApp.controller('charitiesAmendmentController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------- Charities Amendmenet Functionality------------- */

    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    var originalEntityName = "";
    var isShortFiscalYearChecked = false;

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.getCharitiesDetails(); // getCharitiesDetails method is available in this controller only.
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    var getShortYearStartDate = function () {
        if ($scope.modal.CurrentEndDateForAmendment != null && typeof ($scope.modal.CurrentEndDateForAmendment) != typeof (undefined)) {
            $scope.modal.shortFiscalYearEntity.FiscalStartDate = "";
            var startDate = wacorpService.getShortYearStartDate($scope.modal.CurrentEndDateForAmendment);
            $scope.modal.shortFiscalYearEntity.FiscalStartDate = wacorpService.dateFormatService(startDate);
            return $scope.modal.shortFiscalYearEntity.FiscalStartDate;
        }
    };

    var getShortYearEndDate = function () {
        if ($scope.modal.AccountingyearBeginningDate != null && typeof ($scope.modal.AccountingyearBeginningDate) != typeof (undefined)) {
            $scope.modal.shortFiscalYearEntity.FiscalEndDate = "";
            var endDate = wacorpService.getShortYearEndDate($scope.modal.AccountingyearBeginningDate);
            $scope.modal.shortFiscalYearEntity.FiscalEndDate = wacorpService.dateFormatService(endDate);
            return $scope.modal.shortFiscalYearEntity.FiscalEndDate;
        }
    };

    //Get Charities Details from Registration Number
    $scope.getCharitiesDetails = function () {
        // Here BusinessTypeID = 7 is Charity Business Type.
        $rootScope.BusinessTypeID = 7;

        var isOptional = localStorage.getItem("isOptional");

        var data = null;

        if (isOptional == "true") {
            if ($rootScope.transactionID > 0)
                // Here filingTypeID: 3676 is CHARITABLE ORGANIZATION OPTIONAL AMENDMENT
                data = { params: { CharityID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3676, transactionID: $rootScope.transactionID } };
            else
                data = { params: { CharityID: $routeParams.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3676, transactionID: $rootScope.transactionID } };
        }
        else {
            if ($rootScope.transactionID > 0)
                // Here filingTypeID : 157 is CHARITABLE ORGANIZATION AMENDMENT.
                data = { params: { CharityID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 157, transactionID: $rootScope.transactionID } };
            else
                data = { params: { CharityID: $routeParams.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 157, transactionID: $rootScope.transactionID } };
        }

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/CharitiesSearch');
            }
            // getCharitiesAmendmentDetails method is availble in constants.js
            wacorpService.get(webservices.CFT.getCharitiesAmendmentDetails, data, function (response) {
                $scope.modal = response.data;
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                originalEntityName = $scope.modal.EntityName;
                $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
                $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
                $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);
                $scope.modal.UBIOtherDescp = $scope.modal.UBIOtherDescp || null;
                if (isOptional == "false")
                {
                    $scope.modal.IsOptionalRegistration = false;
                    $rootScope.OptionalData = null;
                }
                else if (isOptional == "true")
                {
                    $scope.modal.IsOptionalRegistration = true;
                }

                if ($rootScope.OptionalData != null && $rootScope.OptionalData != undefined) {
                    $scope.modal.IsIntegratedAuxiliary = $rootScope.OptionalData.IntegratedAuxiliary == "Yes" ? true : false;
                    $scope.modal.IsPoliticalOrganization = $rootScope.OptionalData.PoliticalOrganization == "Yes" ? true : false;
                    $scope.modal.IsRaisingFundsForIndividual = $rootScope.OptionalData.RaisingFundsForIndividual == "Yes" ? true : false;
                    $scope.modal.IsRaisingLessThan50000 = $rootScope.OptionalData.RaisingLessThan50000 == "Yes" ? true : false;
                    $scope.modal.IsAnyOnePaid = $rootScope.OptionalData.AnyOnePaid == "Yes" ? true : false;
                    $scope.modal.IsInfoAccurate = $rootScope.OptionalData.InfoAccurate == "Yes" ? true : false;
                }
                else {
                    $scope.modal.IsIntegratedAuxiliary = $scope.modal.IsIntegratedAuxiliary;
                    $scope.modal.IsPoliticalOrganization = $scope.modal.IsPoliticalOrganization;
                    $scope.modal.IsRaisingFundsForIndividual = $scope.modal.IsRaisingFundsForIndividual;
                    $scope.modal.IsRaisingLessThan50000 = $scope.modal.IsRaisingLessThan50000;
                    $scope.modal.IsAnyOnePaid = $scope.modal.IsAnyOnePaid;
                    $scope.modal.IsInfoAccurate = $scope.modal.IsInfoAccurate;
                }
                $scope.modal.IsIntegratedAuxiliary = $scope.modal.IsIntegratedAuxiliary;
                $scope.modal.IsPoliticalOrganization = $scope.modal.IsPoliticalOrganization;
                $scope.modal.IsRaisingFundsForIndividual = $scope.modal.IsRaisingFundsForIndividual;
                $scope.modal.IsRaisingLessThan50000 = $scope.modal.IsRaisingLessThan50000;
                $scope.modal.IsAnyOnePaid = $scope.modal.IsAnyOnePaid;
                $scope.modal.IsInfoAccurate = $scope.modal.IsInfoAccurate;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                if ($scope.modal.IsActiveFilingExist) {
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.IsFIFullAccountingYear)
                        $scope.modal.oldFiscalYear = $scope.modal.AccountingyearBeginningDate != '01/01/0001' || $scope.modal.AccountingyearBeginningDate != null ? $scope.modal.AccountingyearBeginningDate : null;
                    else
                        $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingyearEndDate != '01/01/0001' || $scope.modal.FirstAccountingyearEndDate != null ? $scope.modal.FirstAccountingyearEndDate : null;
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }

                //$scope.modal.IsOrgNameExists = $scope.modal.EntityName != null && $scope.modal.FEINNumber != "" && $scope.modal.FEINNumber != null || $scope.modal.UBINumber != null && $scope.modal.UBINumber != "" && $scope.modal.EntityName != "" ? true : false;
                //$scope.modal.FEINNumber = $scope.modal.FEINNumber || null;
                $scope.modal.UBINumber = $scope.modal.UBINumber || null;
                $scope.modal.AKANamesList = $scope.modal.AKANamesList || null;
                if ($scope.modal.FederaltaxUpload.length > 0)
                    $scope.modal.FederaltaxUpload.length = 0;
                //$scope.modal.IsShowFederalTax = $scope.modal.FederaltaxUpload.length > 0 ? true : false;
                $scope.modal.OldIsFederalTax = $scope.modal.IsFederalTax;
                $scope.modal.OldIsShowFederalTax = $scope.modal.IsShowFederalTax = false;

                //$scope.modal.FinancialId = $scope.modal.FinancialId || null;
                //$scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets;
                //$scope.modal.RevenueGDfromSolicitations = $scope.modal.RevenueGDfromSolicitations;
                //$scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.RevenueGDRevenueAllOtherSources;
                //$scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts;

                //$scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.ExpensesGDExpendituresProgramServices;
                //$scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures;
                //$scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets;
                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.IsFIFullAccountingYear) {
                        $scope.modal.CurrentStartDateForAmendment = ($scope.modal.AccountingyearBeginningDate != '01/01/0001' || $scope.modal.AccountingyearBeginningDate != null) ? $scope.modal.AccountingyearBeginningDate : null;
                        $scope.modal.CurrentEndDateForAmendment = ($scope.modal.AccountingyearEndingDate != '01/01/0001' || $scope.modal.AccountingyearEndingDate != null) ? $scope.modal.AccountingyearEndingDate : null;
                        $scope.modal.shortFiscalYearEntity.PreviousFiscalStartDate = $scope.modal.AccountingyearBeginningDate;
                        $scope.modal.shortFiscalYearEntity.PreviousFiscalEndDate = $scope.modal.AccountingyearEndingDate;
                    }
                    else {
                        $scope.modal.CurrentEndDateForAmendment = ($scope.modal.FirstAccountingyearEndDate != '01/01/0001' || $scope.modal.FirstAccountingyearEndDate != null) ? $scope.modal.FirstAccountingyearEndDate : null;
                        $scope.modal.shortFiscalYearEntity.PreviousFiscalEndDate = $scope.modal.FirstAccountingyearEndDate;
                    }
                }

                //Empty the Previous Financials
                if (!$rootScope.IsShoppingCart) {
                    $scope.modal.IsFIFullAccountingYear = false;
                    $scope.modal.isUpdated = false;
                    $scope.modal.AccountingyearBeginningDate = null;
                    $scope.modal.AccountingyearEndingDate = null;
                    //$scope.modal.FirstAccountingyearEndDate = null;
                    $scope.modal.BeginingGrossAssets = null;
                    $scope.modal.RevenueGDfromSolicitations = null;
                    $scope.modal.RevenueGDRevenueAllOtherSources = null;
                    $scope.modal.TotalDollarValueofGrossReceipts = null;

                    $scope.modal.ExpensesGDExpendituresProgramServices = null;
                    $scope.modal.ExpensesGDValueofAllExpenditures = null;
                    $scope.modal.EndingGrossAssets = null;

                    //Short Fiscal Info
                    $scope.modal.shortFiscalYearEntity.BeginingGrossAssetsForShortFY = null;
                    $scope.modal.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY = null;
                    $scope.modal.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY = null;
                    $scope.modal.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY = null;
                    $scope.modal.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY = null;
                    $scope.modal.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY = null;
                    $scope.modal.shortFiscalYearEntity.EndingGrossAssetsForShortFY = null;
                }



                $scope.modal.ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.ContributionServicesTypeId) ? [] : $scope.modal.ContributionServicesTypeId.split(',');
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');

                $scope.modal.CharityAkaInfoEntity.CountiesServedId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CountiesServedId) ? [] : $scope.modal.CharityAkaInfoEntity.CountiesServedId.split(',');
                $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId) ? [] : $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.split(',');
                $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress != null ? $scope.modal.EntityStreetAddress : null;
                $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress != null ? $scope.modal.EntityMailingAddress : null;
                $scope.modal.EntityStreetAddress.IsSameAsEntityMailingAddress = $scope.modal.IsSameAsEntityMailingAddress;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country != null ? $scope.modal.LegalInfo.LegalInfoAddress.Country : codes.USA;

                $scope.modal.CFTCorrespondenceAddress.Attention = $scope.modal.CFTCorrespondenceAddress.Attention != null ? $scope.modal.CFTCorrespondenceAddress.Attention : null;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;


                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : "I";
                $scope.modal.LegalInfo.IsAnyLegalActions = $scope.modal.LegalInfo.IsAnyLegalActions || false;
                $scope.modal.LegalInfoEntityList = $scope.modal.LegalInfoEntityList != null ? $scope.modal.LegalInfoEntityList : null;
                $scope.modal.shortFiscalYearEntity = wacorpService.shortFisicalYearDataFormat($scope.modal.shortFiscalYearEntity);
                //$scope.modal.EntityMailingAddress.State = codes.WA; //$scope.modal.EntityMailingAddress.Country = codes.USA;
                //$scope.modal.EntityStreetAddress.State = codes.WA; //$scope.modal.EntityStreetAddress.Country = codes.USA;
                //$scope.modal.LegalInfo.LegalInfoAddress.State = codes.WA; //$scope.modal.LegalInfo.LegalInfoAddress.Country = codes.USA;
                //$scope.modal.LegalInfo.LegalInfoTypeID = 'I';
                $scope.modal.AKASolicitNameId = '';
                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;

                //if ($scope.modal.CFTFinancialHistoryList != null && typeof ($scope.modal.CFTFinancialHistoryList) != typeof (undefined)) {
                //    if ($scope.modal.CFTFinancialHistoryList.length > 0) {
                //        $scope.modal.IsShowAccDates = true;
                //    }
                //}

                if ($scope.modal.CFTFinancialHistoryList.length > 0) {
                    angular.forEach($scope.modal.CFTFinancialHistoryList, function (charity) {
                        charity.SequenceNo = charity.FinancialId;
                    });
                }

                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if (!($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == undefined))
                    $scope.modal.JurisdictionCountry = $scope.modal.JurisdictionCountry == 0 ? '' : $scope.modal.JurisdictionCountry.toString();

                if (!($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == undefined))
                    $scope.modal.JurisdictionState = $scope.modal.JurisdictionState == 0 ? '' : $scope.modal.JurisdictionState.toString();

                if (!($scope.modal.FederalTaxExemptId == null || $scope.modal.FederalTaxExemptId == undefined))
                    $scope.modal.FederalTaxExemptId = $scope.modal.FederalTaxExemptId == 0 ? '' : $scope.modal.FederalTaxExemptId.toString();

                if (!($scope.modal.OSJurisdictionCountyId == null || $scope.modal.OSJurisdictionCountyId == undefined))
                    $scope.modal.OSJurisdictionCountyId = $scope.modal.OSJurisdictionCountyId == 0 ? '' : $scope.modal.OSJurisdictionCountyId.toString();

                if (!($scope.modal.OSJurisdictionStateId == null || $scope.modal.OSJurisdictionStateId == undefined))
                    $scope.modal.OSJurisdictionStateId = $scope.modal.OSJurisdictionStateId == 0 ? '' : $scope.modal.OSJurisdictionStateId.toString();

                if ($scope.modal.OfficersHighPayList.length > 0) {
                    angular.forEach($scope.modal.OfficersHighPayList, function (cftHihPay) {
                        cftHihPay.SequenceNo = cftHihPay.ID;
                    });
                }
                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.CFTOfficersList.length > 0) {
                        angular.forEach($scope.modal.CFTOfficersList, function (cftOffice) {
                            cftOffice.SequenceNo = cftOffice.OfficerID;
                        });
                    }
                }

                if ($scope.modal.LegalInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.LegalInfoEntityList, function (cftLegalInfo) {
                        cftLegalInfo.SequenceNo = cftLegalInfo.LegalInfoId;
                    });
                }

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaEntity) {
                        akaEntity.SequenceNo = akaEntity.AKASolicitNameId;
                    });
                }
                if ($scope.modal.FundraisersList.length > 0) {
                    var i = 0;
                    angular.forEach($scope.modal.FundraisersList, function (fundraiser) {
                        fundraiser.SequenceNo = i + 1;
                    });
                }
                if ($scope.modal.AKANamesList.length > 0) {
                    angular.forEach($scope.modal.AKANamesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }

                $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.

                $scope.modal.isShowReturnAddress = true;
            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            if (isOptional == "false") {
                $scope.modal.IsOptionalRegistration = false;
            }
            if ($scope.modal.IsOptionalRegistration && $rootScope.OptionalData != null && $rootScope.OptionalData != undefined) {
                $scope.modal.IsIntegratedAuxiliary = $rootScope.OptionalData.IntegratedAuxiliary == "Yes" ? true : false;
                $scope.modal.IsPoliticalOrganization = $rootScope.OptionalData.PoliticalOrganization == "Yes" ? true : false;
                $scope.modal.IsRaisingFundsForIndividual = $rootScope.OptionalData.RaisingFundsForIndividual == "Yes" ? true : false;
                $scope.modal.IsRaisingLessThan50000 = $rootScope.OptionalData.RaisingLessThan50000 == "Yes" ? true : false;
                $scope.modal.IsAnyOnePaid = $rootScope.OptionalData.AnyOnePaid == "Yes" ? true : false;
                $scope.modal.IsInfoAccurate = $rootScope.OptionalData.InfoAccurate == "Yes" ? true : false;
            }
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.

            //Assigning 0's to Empty
            $scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets == 0 ? null : $scope.modal.BeginingGrossAssets;
            $scope.modal.RevenueGDfromSolicitations = $scope.modal.RevenueGDfromSolicitations == 0 ? null : $scope.modal.RevenueGDfromSolicitations;
            $scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.RevenueGDRevenueAllOtherSources == 0 ? null : $scope.modal.RevenueGDRevenueAllOtherSources;
            $scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts == 0 ? null : $scope.modal.TotalDollarValueofGrossReceipts;
            $scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.ExpensesGDExpendituresProgramServices == 0 ? null : $scope.modal.ExpensesGDExpendituresProgramServices;
            $scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures == 0 ? null : $scope.modal.ExpensesGDValueofAllExpenditures;
            $scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets == 0 ? null : $scope.modal.EndingGrossAssets;
            //Short Fiscal Info
            $scope.modal.shortFiscalYearEntity.BeginingGrossAssetsForShortFY = $scope.modal.shortFiscalYearEntity.BeginingGrossAssetsForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.BeginingGrossAssetsForShortFY;
            $scope.modal.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY = $scope.modal.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.RevenueGDfromSolicitationsForShortFY;
            $scope.modal.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY = $scope.modal.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.RevenueGDRevenueAllOtherSourcesForShortFY;
            $scope.modal.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY = $scope.modal.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.TotalDollarValueofGrossReceiptsForShortFY;
            $scope.modal.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY = $scope.modal.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY;
            $scope.modal.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY = $scope.modal.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY;
            $scope.modal.shortFiscalYearEntity.EndingGrossAssetsForShortFY = $scope.modal.shortFiscalYearEntity.EndingGrossAssetsForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.EndingGrossAssetsForShortFY;
            $scope.modal.isShowReturnAddress = true;
        }
    };

    $scope.checkHighpayCount = function () {
        var count = 0;
        angular.forEach($scope.modal.OfficersHighPayList, function (highpayItem) {
            if (highpayItem.Status != "D") {
                count++;
            }
        });

        if (count >= 3) {
            $scope.modal.OfficersHighPay.IsCountMax = true;
        }
        else {
            $scope.modal.OfficersHighPay.IsCountMax = false;
        }
        return count <= 0;
    };

    $scope.checkFederalCount = function () {
        var count = 0;
        angular.forEach($scope.modal.FederaltaxUpload, function (value) {
            if (value.Status != 'D')
                count++;
        });
        if (count == 0 || count == undefined)
            return $scope.modal.FederaltaxUpload.length = 0;
        else
            return $scope.modal.FederaltaxUpload.length = count;
    };

    $scope.Review = function (charitiesAmendmentForm) {

        //if (!$scope.modal.IsAnyOnePaid) {
        $scope.validateErrorMessage = true;

        if (typeof ($scope.modal.CFTFinancialHistoryList) != typeof (undefined) && $scope.modal.CFTFinancialHistoryList.length == 0) {
            var endDate = $scope.modal.AccountingyearEndingDate;
            if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                if (isEndDateMore) {
                    // Folder Name: app Folder
                    // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                    return false;
                }
            }
        }


        var endFiscalDate = $scope.modal.shortFiscalYearEntity.FiscalEndDate;
        if (typeof (endFiscalDate) != typeof (undefined) && endFiscalDate != null && endFiscalDate != "" && $scope.modal.CFTFinancialHistoryList.length > 0) {
            var isEndDateMore = wacorpService.isEndDateMoreThanToday(endFiscalDate);
            if (isEndDateMore) {
                // Folder Name: app Folder
                // Alert Name: shortYearEndDateNotGreaterThanTodayDate method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.CharitiesFinancial.shortYearEndDateNotGreaterThanTodayDate);
                return false;
            }
        }

        //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {

        //var isFeinValid = ($scope.modal.UBINumber != "" ? $scope.modal.IsUBINumberExistsorNot : true) && $scope.charitiesRenewalForm.fein.$valid;


        var isOrgNameValid = $scope.modal.EntityName != null ? true : false;

        var isPurposeValid = $scope.modal.Purpose != null ? true : false;

        var isTaxUploadValid = $scope.modal.IsShowFederalTax ? ($scope.checkFederalCount() > 0 ? true : false) : true;

        //var isEntityNameValid = $scope.modal.isBusinessNameAvailable ? true : false;

        $scope.EntityNameCheck = true;

        $scope.modal.NewEntityName = $scope.modal.EntityName;

        if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
            if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                $scope.modal.isBusinessNameChanged = true;
            }
            else {
                $scope.modal.isBusinessNameChanged = false;
            }
        }

        //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);
        //var isEntityNameValid = ($scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : ($scope.modal.isBusinessNameChanged ? false : true)));
        var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

        if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
            $scope.EntityNameCheck = false;
        }
        else {
            $scope.EntityNameCheck = true;
        }

        //Checking Accounting Year Less Than Current End Date
        //$scope.modal.AccStartDateMoreThanOneYear = false;
        //if ($scope.modal.IsFIFullAccountingYear) {
        //    $scope.modal.AccYearStartDateForAmendment = $scope.modal.AccountingyearBeginningDate;
        //    $scope.modal.AccStartDateMoreThanOneYear = wacorpService.checkForAccYearMaxThenOneYear($scope.modal.AccYearStartDateForAmendment, $scope.modal.CurrentEndDateForAmendment);
        //}

        ////Checking Accounting Year Less Than Current End Date
        //$scope.modal.AccEndDateLessThanCurrentYear = false;
        //if ($scope.modal.IsFIFullAccountingYear) {
        //    $scope.modal.AccEndDateLessThanCurrentYear = wacorpService.checkDateValidity($scope.modal.AccountingYearBeginningDate, $scope.modal.CurrentStartDateForAmendment);
        //}

        //isShortFiscalValid = true;

        //Checking For Short Fiscal Year
        //   $scope.modal.IsShortFiscalYear = false;
        //if ($scope.modal.IsFIFullAccountingYear) {
        //    $scope.modal.AccYearStartDateForAmendment = $scope.modal.AccountingyearBeginningDate;
        //  //  $scope.modal.IsShortFiscalYear = wacorpService.checkForShortFiscalYear($scope.modal.AccYearStartDateForAmendment, $scope.modal.CurrentStartDateForAmendment, $scope.modal.CurrentEndDateForAmendment);
        //    if ($scope.modal.IsShortFiscalYear) {
        //        isShortFiscalValid = false;
        //        $scope.modal.AccStartDateMoreThanOneYear = false;
        //        $scope.modal.AccEndDateLessThanCurrentYear = false;
        //        //$scope.modal.shortFiscalYearEntity.AllContributionsReceivedForShortFY = null;
        //        //$scope.modal.shortFiscalYearEntity.AveragePercentToCharityForShortFY = null;
        //        //$scope.modal.shortFiscalYearEntity.AmountOfFundsForShortFY = null;
        //    }
        //    else
        //        isShortFiscalValid = true;
        //}

        //var isShortFYExpensesValid = true;
        //if ($scope.modal.IsShortFiscalYear && $scope.modal.IsFIFullAccountingYear) {
        //    var stDate = wacorpService.dateFormatService($scope.modal.shortFiscalYearEntity.FiscalStartDate);
        //    var endDate = wacorpService.dateFormatService($scope.modal.shortFiscalYearEntity.FiscalEndDate);
        //    if (stDate != null && endDate != null) {
        //        isShortFYExpensesValid = ($scope.modal.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY < $scope.modal.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY ? false : true);
        //        if (!isShortFYExpensesValid) {
        //            isShortFiscalValid = false;
        //            $scope.modal.AccStartDateMoreThanOneYear = false;
        //            $scope.modal.AccEndDateLessThanCurrentYear = false;
        //        }
        //        else
        //            isShortFiscalValid = true;
        //    }
        //}

        $scope.modal.AccEndDateLessThanCurrentYear = ($scope.modal.IsFIFullAccountingYear) ? $scope.modal.AccEndDateLessThanCurrentYear : false;

        if ($scope.modal.IsShortFiscalYear) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            var preAccEndDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
            var currAccStartDate = wacorpService.dateFormatService($scope.modal.CurrentStartDateForAmendment);
            if (preAccEndDate != null && currAccStartDate != null && currAccStartDate != undefined && preAccEndDate != undefined) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                var val = wacorpService.checkDateValidity($scope.modal.CurrentEndDateForAmendment, $scope.modal.AccountingyearBeginningDate, $scope.modal.IsShortFiscalYear);
                $scope.modal.IsShortFiscalYear = false;
                $scope.modal.AccEndDateLessThanCurrentYear = false;
                $scope.modal.AccStartDateMoreThanOneYear = false;
                if (val == 'SFY') {
                    $scope.modal.IsShortFiscalYear = true;
                    isShortFiscalYearChecked = true;
                } else if (val == 'SDgPnD') {
                    $scope.modal.AccEndDateLessThanCurrentYear = true;
                } else if (val == 'Y1Plus') {

                    $scope.modal.AccStartDateMoreThanOneYear = true;
                } else {
                    $scope.modal.IsShortFiscalYear = false;
                    $scope.modal.AccEndDateLessThanCurrentYear = false;
                    $scope.modal.AccStartDateMoreThanOneYear = false;
                }
            }
            else {
                $scope.modal.AccEndDateLessThanCurrentYear = false;
                $scope.modal.AccStartDateMoreThanOneYear = false;
            }
        }

        if ($scope.modal.IsShortFiscalYear) {
            getShortYearStartDate(); // getShortYearStartDate method is available in this controller only.
            getShortYearEndDate(); // getShortYearEndDate method is available in this controller only.
        }

        //var shortFiscalInfoValid = $scope.modal.IsShortFiscalYear ? (isShortFiscalYearChecked ? true : false) : true;

        var isEntityInfo = ($scope.charitiesAmendmentForm.entityInfo.$valid);

        var isExpensesValid = true;
        if (typeof ($scope.modal.CFTFinancialHistoryList) != typeof (undefined) && $scope.modal.CFTFinancialHistoryList.length == 0) {
            isExpensesValid = ($scope.modal.IsFIFullAccountingYear ? ($scope.modal.ExpensesGDValueofAllExpenditures != null && $scope.modal.ExpensesGDExpendituresProgramServices != null ? ($scope.modal.ExpensesGDValueofAllExpenditures < $scope.modal.ExpensesGDExpendituresProgramServices ? false : true) : true) : true);
        }

        var isShortFiscalExpensesValid = true;
        if (typeof ($scope.modal.CFTFinancialHistoryList) != typeof (undefined) && $scope.modal.CFTFinancialHistoryList.length > 0) {
            isShortFiscalExpensesValid = ($scope.modal.IsShortFiscalYear ? ($scope.modal.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY != null && $scope.modal.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY != null ? ($scope.modal.shortFiscalYearEntity.ExpensesGDValueofAllExpendituresForShortFY < $scope.modal.shortFiscalYearEntity.ExpensesGDExpendituresProgramServicesForShortFY ? false : true) : true): true);
        }
        //To not validate inner form from outer form removed control
        //if (!($scope.charitiesRenewalForm.CharityOrganizationForm.akaNames == null || $scope.charitiesRenewalForm.CharityOrganizationForm.akaNames == undefined))
        //    $scope.charitiesRenewalForm.CharityOrganizationForm.$removeControl($scope.charitiesRenewalForm.CharityOrganizationForm.akaNames);

        //var isCharityOrgFormValid = ($scope.charitiesRenewalForm.CharityOrganizationForm.$valid);
        var isDatesValid = true;//($scope.modal.IsFIFullAccountingYear ? ((new Date($scope.modal.AccountingyearEndingDate) > new Date($scope.modal.AccountingyearBeginningDate)) ? true : false) : true);

        var isCharitiesFinancialInfo = ($scope.charitiesAmendmentForm.CharityFinancialInfoForm.$valid) && (isDatesValid);

        var isOfficerHighpay = !$scope.modal.OfficersHighPay.IsPayOfficers || ($scope.modal.OfficersHighPay.IsPayOfficers && !$scope.checkHighpayCount());

        var isCftOfficesListValid = ($scope.checkOfficersCount() > 0);

        var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

        var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalActionsUploads.length > 0 ? true : false) : true);

        var isLegalInfo = $scope.modal.isUpdated ? ($scope.charitiesAmendmentForm.fundraiserLegalInfo.$valid) : true;

        var isFundraiserListValid = true;
        if ($scope.modal.IsCommercialFundraisersContributionsInWA) {
            isFundraiserListValid = $scope.checkFundraisersCount(); // checkFundraisersCount method is available in this controller only.
            if (isFundraiserListValid) {
                $scope.modal.isFundraiserRequired = false;
            }
            else {
                $scope.modal.isFundraiserRequired = true;
            }
        }

        //var isShortFiscalSectionVaild = $scope.modal.IsShortFiscalYear?():true;

        //var isGreenCrossEnrolltoCFD = true;
        //if ($scope.modal.IsGreenCross)
        //    isGreenCrossEnrolltoCFD = $scope.modal.IsAkaProgramsinCFD ? $scope.charitiesRenewalForm.enrollToCFDForm.greenCrossCfdDetails.$valid : true;

        var Fein = $scope.modal.FEINNumber;
        var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

        var Ubi = $scope.modal.UBINumber;
        var isValidUbi = $scope.modal.IsEntityRegisteredInWA && $scope.modal.JurisdictionState == "271" ?
            (Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9 ? true : false) : (Ubi == null || Ubi == '' || Ubi.length == 9 ? true : false);;

        var isSignatureAttestationValidate = ($scope.charitiesAmendmentForm.SignatureForm.$valid);
        //var isCorrespondenceAddressValid = $scope.charitiesAmendmentForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.charitiesAmendmentForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.charitiesAmendmentForm.cftCorrespondenceAddressForm.$valid;

        //var isFormValidate = isEntityNameValid && isEntityInfo && isCharityOrgFormValid && isCharitiesFinancialInfo && isCftOfficesListValid && isLegalInfo &&
        //        isFundraiserListValid && isGreenCrossEnrolltoCFD && isSignatureAttestationValidate; // by 1504 - 23/06/2017

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

        $scope.checkAccYearVaild = false;
        if (!$scope.modal.IsFIFullAccountingYear) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            var FAYEDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);
            if (typeof (FAYEDate) != typeof (undefined) && FAYEDate != null && FAYEDate != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.checkAccYearVaild = wacorpService.checkAccYearEndDateForReg($scope.modal.FirstAccountingyearEndDate, false);
            }
        }


        var isFormValidate = isOrgNameValid && isPurposeValid && isTaxUploadValid && isEntityNameValid && isEntityInfo && isExpensesValid && isShortFiscalExpensesValid &&
                                isCharitiesFinancialInfo && isOfficerHighpay && isCftOfficesListValid && isLegalActionsListValid && isLegalInfo && !$scope.checkAccYearVaild &&
                                    isCorrespondenceAddressValid && isLegalActionsUploadValid && isFundraiserListValid && isSignatureAttestationValidate &&
                                        isValidFein && isValidUbi && isAdditionalUploadValid && !$scope.modal.AccStartDateMoreThanOneYear && !$scope.modal.AccEndDateLessThanCurrentYear;

        $scope.fillAmendmentData(); // fillAmendmentData method is availble in this controller only.

        //if ($scope.modal.IsOptionalRegistration) {
        //    var IsQualified = ($scope.modal.IsIntegratedAuxiliary || $scope.modal.IsPoliticalOrganization
        //            || $scope.modal.IsRaisingFundsForIndividual || $scope.modal.IsRaisingLessThan50000 || $scope.modal.IsAnyOnePaid);
        //    if (isFormValidate && IsQualified && $scope.modal.IsInfoAccurate) {
        //        $scope.validateErrorMessage = false;
        //        $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
        //        $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
        //        $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);
        //        var isOptionalReg = wacorpService.validateOptionalQualifiers($scope.modal.IsIntegratedAuxiliary, $scope.modal.IsPoliticalOrganization, $scope.modal.IsRaisingFundsForIndividual, $scope.modal.IsRaisingLessThan50000, $scope.modal.IsAnyOnePaid);
        //        if (isOptionalReg) {
        //            $scope.isReview = true;
        //            $location.path('/charitiesOptionalAmendmentReview');
        //        }
        //        else {
        //            wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifier);
        //            $rootScope.modal = null;
        //            //$location.path("/charitiesRegistration");
        //        }
        //    }
        //    else {
        //        wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        //    }
        //}
        //else {
        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
            $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
            $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

            $scope.isReview = true;
            $location.path('/charitiesAmendmentReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        //}
        //}
        //else {
        //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
        //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
        //        return false;
        //    }
        //}
        //}
        //else {
        //    wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifierAmendment);
        //    $rootScope.modal = null;
        //    $scope.navCharityRegistration();
        //}
    };

    $scope.checkOfficersCount = function () {
        var count = 0;
        angular.forEach($scope.modal.CFTOfficersList, function (value) {
            if (value.OfficerStatus != 'D')
                count++;
        });

        if (count == 0 || count == undefined)
            return $scope.modal.CFTOfficersList.length = 0;
        else
            return $scope.modal.CFTOfficersList.length;
    };

    $scope.checkFundraisersCount = function () {
        var delCount = 0;
        var listCount = 0;
        //listCount = $scope.modal.FundraisersList.length;
        //delCount = $scope.modal.FundraisersList.length;
        angular.forEach($scope.modal.FundraisersList, function (value) {
            if (value.Status != 'D')
                delCount++;
        });

        if (delCount > 0)
            return true;
        else
            return false;
    };

    $scope.fillAmendmentData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.EntityName = $scope.modal.EntityName || null;
        $scope.modal.FinancialId = $scope.modal.FinancialId || null;
        if ($scope.modal.IsFIFullAccountingYear)
            $scope.modal.oldFiscalYear = $scope.modal.AccountingyearBeginningDate != '01/01/0001' || $scope.modal.AccountingyearBeginningDate != null ? $scope.modal.AccountingyearBeginningDate : null;
        else
            $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingyearEndDate != '01/01/0001' || $scope.modal.FirstAccountingyearEndDate != null ? $scope.modal.FirstAccountingyearEndDate : null;

        $scope.modal.OSJurisdictionId = $scope.modal.OSJurisdictionStateId != "" ? $scope.modal.OSJurisdictionStateId : $scope.modal.OSJurisdictionCountyId;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }

        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }

        if ($scope.modal.CharityAkaInfoEntity.CountiesServedId != null && $scope.modal.CharityAkaInfoEntity.CountiesServedId.length > 0) {
            $scope.modal.CharityAkaInfoEntity.CountiesServedId = $scope.modal.CharityAkaInfoEntity.CountiesServedId.join(",");
        }
        if ($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId != null && $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.length > 0) {
            $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.join(",");
        }

        if ($scope.modal.OfficersHighPayList != null && $scope.modal.OfficersHighPayList.length == 3)
            $scope.modal.OfficersHighPay.IsCountMax = true;

        if ($scope.modal.CharityAkaInfoEntityList != null && $scope.modal.CharityAkaInfoEntityList.length > 0) {
            angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                if (akaInfo.CountiesServedId != null && akaInfo.CountiesServedId.length > 0)
                    akaInfo.CountiesServedId = akaInfo.CountiesServedId.join(",");
                if (akaInfo.CategoryOfServiceId != null && akaInfo.CategoryOfServiceId.length > 0)
                    akaInfo.CategoryOfServiceId = akaInfo.CategoryOfServiceId.join(",");
            });
        }
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
        $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
        $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);
        $scope.modal.EntityStreetAddress.IsAddressSame = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName;
        $scope.modal.IsCommercialFundraisersContributionsInWA = $scope.modal.IsCommercialFundraisersContributionsInWA;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        //if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
        //    $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $rootScope.modal = $scope.modal;
    };

    $scope.AmendSaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillAmendmentData(); // fillAmendmentData method is available in this controller only.
        if ($scope.modal.IsOptionalRegistration) {
            $scope.modal.OnlineNavigationUrl = "/charitiesOptionalAmendment";
        }
        else {
            $scope.modal.OnlineNavigationUrl = "/charitiesAmendment";
        }
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
        $rootScope.OptionalData = null;
    }

    $scope.AmendBack = function () {
        $scope.fillAmendmentData(); // fillAmendmentData method is available in this controller only.
        var optioanlData = {
            IntegratedAuxiliary: $scope.modal.IsIntegratedAuxiliary ? "Yes" : "No",
            PoliticalOrganization: $scope.modal.IsPoliticalOrganization ? "Yes" : "No",
            RaisingFundsForIndividual: $scope.modal.IsRaisingFundsForIndividual ? "Yes" : "No",
            RaisingLessThan50000: $scope.modal.IsRaisingLessThan50000 ? "Yes" : "No",
            AnyOnePaid: $scope.modal.IsAnyOnePaid ? "Yes" : "No",
            InfoAccurate: $scope.modal.IsInfoAccurate ? "Yes" : "No",
        };
        $rootScope.OptionalData = optioanlData;
        $rootScope.isOptionalAmendment = true;
        localStorage.setItem("IsBack",true);
        $location.path("/charitiesOptionalQualifier");

    };
});

wacorpApp.controller('charitiesAmendmentReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Charities Registration Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        $scope.modal = $rootScope.modal;
    };

    $scope.CharitiesAmendmentAddToCart = function () {

        if ($scope.modal.ContributionServicesTypeId!=null && $scope.modal.ContributionServicesTypeId.length > 0)
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");

        if ($scope.modal.FinancialInfoStateId!=null && $scope.modal.FinancialInfoStateId.length > 0)
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
                $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
                $rootScope.modal = null;
                $rootScope.OptionalData = null;
                $rootScope.isOptionalAmendment = false;
                resetLocalStorage(); // resetLocalStorage method is available in this controller only.
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        if ($scope.modal.IsOptionalRegistration) {
            $location.path('/charitiesOptionalAmendment');
        }
        else {
            $location.path('/charitiesAmendment');
        }
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }
    //to reset local storage values
    function resetLocalStorage() {
        localStorage.removeItem("IsBack");
        localStorage.removeItem('isOptional');
    }

});

wacorpApp.controller('charitiesClosureController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isReview = false;
    $scope.addedReasons = [];
    $scope.ValidateFinancialEndDateMessage = false;
    $scope.IsFirstAcctyear = null;
    $scope.beginningdate = null;
    $scope.endingdate = null;

    $scope.Init = function () {
        $scope.messages = messages;
        $scope.getCharitiesDetails(); // getCharitiesDetails method is available in this controller only.
    }

    $scope.getCharitiesDetails = function () {
        // Here BusinessTypeID = 7 is Charity Business Type.
        $rootScope.BusinessTypeID = 7;

        var isOptional = localStorage.getItem("isOptional");

        if ($routeParams.CharityID != undefined) {
            $rootScope.CharityID = $routeParams.CharityID;
        }
        var data = null;

        if (isOptional == "true") {
            if ($rootScope.transactionID > 0)
                // Here filingTypeID: 3677 is CHARITABLE ORGANIZATION OPTIONAL CLOSURE
                data = { params: { CharityID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3677, transactionID: $rootScope.transactionID } };
            else
                data = { params: { CharityID: $routeParams.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3677, transactionID: $rootScope.transactionID } };
        }
        else {
            if ($rootScope.transactionID > 0)
                // Here filingTypeID: 163 is CLOSE CHARITABLE ORGANIZATION
                data = { params: { CharityID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 163, transactionID: $rootScope.transactionID } };
            else
                data = { params: { CharityID: $rootScope.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 163, transactionID: $rootScope.transactionID } };
        }
        //data = { params: { CharityID: $routeParams.CharityID, TransactionID: $rootScope.transactionID } };
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            wacorpService.get(webservices.CFT.CharityClosureCriteria, data, function (response) {
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());

                $scope.modal.BusinessTransaction.DateTimeReceived = wacorpService.dateFormatService(new Date());
                $scope.modal.BusinessTransaction.FilingDate = wacorpService.dateFormatService(new Date());
                $scope.modal.RenewalDate = wacorpService.dateFormatService($scope.modal.RenewalDate);

                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                $scope.modal.CharitiesClosureReasonList = ['Organization Does not raise funds in WA', 'Organization No Longer Exists', 'Organization not needed to register', 'Other'];
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.EffectiveClosureDate = wacorpService.dateFormatService($scope.modal.EffectiveClosureDate);
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
                $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
                $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);
                $scope.beginningdate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
                $scope.endingdate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
                $scope.IsFirstAcctyear = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);
                if (isOptional == "false")
                    $scope.modal.IsOptionalRegistration = false;
                $scope.modal.IsIntegratedAuxiliary = $scope.modal.IsIntegratedAuxiliary;
                $scope.modal.IsPoliticalOrganization = $scope.modal.IsPoliticalOrganization;
                $scope.modal.IsRaisingFundsForIndividual = $scope.modal.IsRaisingFundsForIndividual;
                $scope.modal.IsRaisingLessThan50000 = $scope.modal.IsRaisingLessThan50000;
                $scope.modal.IsAnyOnePaid = $scope.modal.IsAnyOnePaid;
                $scope.modal.IsInfoAccurate = $scope.modal.IsInfoAccurate;
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);
                //$scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }
                if (!$rootScope.IsShoppingCart || $rootScope.IsShoppingCart == undefined) {
                    $scope.modal.BeginingGrossAssets = $scope.modal.EndingGrossAssets;
                    $scope.modal.RevenueGDfromSolicitations = null;
                    $scope.modal.RevenueGDRevenueAllOtherSources = null;
                    $scope.modal.TotalDollarValueofGrossReceipts = null;
                    $scope.modal.ExpensesGDExpendituresProgramServices = null;
                    $scope.modal.ExpensesGDValueofAllExpenditures = null;
                    $scope.modal.EndingGrossAssets = null;
                    $scope.modal.PercentToProgramServices = null;
                }

                //Assigning 0's to Empty
                $scope.modal.BeginingGrossAssets = $scope.modal.IsBeginingGrossAssetsEmpty ? null : $scope.modal.BeginingGrossAssets;
                $scope.modal.EndingGrossAssets = $scope.modal.IsEndingGrossAssetsEmpty ? null : $scope.modal.EndingGrossAssets;
                $scope.modal.RevenueGDfromSolicitations = $scope.modal.IsRevenueGDfromSolicitationsEmpty ? null : $scope.modal.RevenueGDfromSolicitations;
                $scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.IsRevenueGDRevenueAllOtherSourcesEmpty ? null : $scope.modal.RevenueGDRevenueAllOtherSources;
                $scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.IsExpensesGDExpendituresProgramServicesEmpty ? null : $scope.modal.ExpensesGDExpendituresProgramServices;
                $scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.IsExpensesGDValueofAllExpendituresEmpty ? null : $scope.modal.ExpensesGDValueofAllExpenditures;
                $scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.IsTotalDollarValueofGrossReceiptsEmpty ? null : $scope.modal.TotalDollarValueofGrossReceipts;
                $scope.modal.PercentToProgramServices = $scope.modal.IsPercentToProgramServicesEmpty ? null : $scope.modal.PercentToProgramServices;

                $scope.modal.ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.ContributionServicesTypeId) ? [] : $scope.modal.ContributionServicesTypeId.split(',');
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');
                //$scope.modal.CharityAkaInfoEntity.CountiesServedId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CountiesServedId) ? [] : $scope.modal.CharityAkaInfoEntity.CountiesServedId.split(',');
                //$scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId) ? [] : $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.split(',');
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State;
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID;
                $scope.modal.isHavingEntityOnUBISearch = angular.isNullorEmpty($scope.modal.UBINumber) ? false : true;

                if (!$rootScope.IsShoppingCart || $rootScope.IsShoppingCart == undefined) {
                    $scope.modal.CFTCorrespondenceAddress.Country = codes.USA;
                    $scope.modal.CFTCorrespondenceAddress.State = codes.WA;
                }
                else if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                if ($scope.modal.OfficersHighPayList.length > 0) {
                    angular.forEach($scope.modal.OfficersHighPayList, function (cftHihPay) {
                        cftHihPay.SequenceNo = cftHihPay.ID;
                    });
                }

                if ($scope.modal.CharitiesClosureReason != null && $scope.modal.CharitiesClosureReason != "" && $scope.modal.CharitiesClosureReason != undefined)
                    $scope.addedReasons = $scope.modal.CharitiesClosureReason.split(',');
                else
                    $scope.addedReasons = [];


                $scope.modal.isShowReturnAddress = true;
            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.addedReasons = $scope.modal.addedReasons;
            if ($scope.modal.CharitiesClosureReason != null && $scope.modal.CharitiesClosureReason != "" && $scope.modal.CharitiesClosureReason != undefined)
                $scope.addedReasons = $scope.modal.CharitiesClosureReason.split(',');
            else
                $scope.addedReasons = [];
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.BusinessTransaction.DateTimeReceived = wacorpService.dateFormatService($scope.modal.BusinessTransaction.DateTimeReceived);
            $scope.modal.BusinessTransaction.FilingDate = wacorpService.dateFormatService($scope.modal.BusinessTransaction.FilingDate);
            $scope.modal.RenewalDate = wacorpService.dateFormatService($scope.modal.RenewalDate);

            $scope.beginningdate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
            $scope.endingdate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
            $scope.IsFirstAcctyear = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);

            //Assigning 0's to Empty
            $scope.modal.BeginingGrossAssets = $scope.modal.IsBeginingGrossAssetsEmpty ? null : $scope.modal.BeginingGrossAssets;
            $scope.modal.EndingGrossAssets = $scope.modal.IsEndingGrossAssetsEmpty ? null : $scope.modal.EndingGrossAssets;
            $scope.modal.RevenueGDfromSolicitations = $scope.modal.IsRevenueGDfromSolicitationsEmpty ? null : $scope.modal.RevenueGDfromSolicitations;
            $scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.IsRevenueGDRevenueAllOtherSourcesEmpty ? null : $scope.modal.RevenueGDRevenueAllOtherSources;
            $scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.IsExpensesGDExpendituresProgramServicesEmpty ? null : $scope.modal.ExpensesGDExpendituresProgramServices;
            $scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.IsExpensesGDValueofAllExpendituresEmpty ? null : $scope.modal.ExpensesGDValueofAllExpenditures;
            $scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.IsTotalDollarValueofGrossReceiptsEmpty ? null : $scope.modal.TotalDollarValueofGrossReceipts;
            $scope.modal.PercentToProgramServices = $scope.modal.IsPercentToProgramServicesEmpty ? null : $scope.modal.PercentToProgramServices;
            $scope.modal.isShowReturnAddress = true;

        }
    };

    $scope.Review = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;

        //var endDate = $scope.modal.AccountingyearEndingDate;
        //if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
        //    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
        //    if (isEndDateMore) {
        //        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
        //        return false;
        //    }
        //}

        $scope.validateErrorMessage = true;
        var isCharitiesFinancialInfo = $scope.modal.IsDateEditable ? true : ($scope.charitiesClosureForm.CharityFinancialInfoForm.$valid);
        var isEffectiveDateExists = ($scope.charitiesClosureForm.EffectiveDate.$valid);
        var isExpensesValid = ($scope.modal.IsFIFullAccountingYear ? ($scope.modal.ExpensesGDValueofAllExpenditures < $scope.modal.ExpensesGDExpendituresProgramServices ? false : true) : true);

        var isSignatureAttestationValidate = ($scope.charitiesClosureForm.SignatureForm.$valid);
        //var isCorrespondenceAddressValid = $scope.charitiesClosureForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.charitiesClosureForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.charitiesClosureForm.cftCorrespondenceAddressForm.$valid;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

        $scope.modal.IsBeginingGrossAssetsEmpty = ($scope.modal.BeginingGrossAssets == null || isNaN($scope.modal.BeginingGrossAssets)) ? true : false;
        $scope.modal.IsEndingGrossAssetsEmpty = ($scope.modal.EndingGrossAssets == null || isNaN($scope.modal.EndingGrossAssets)) ? true : false;
        $scope.modal.IsRevenueGDfromSolicitationsEmpty = ($scope.modal.RevenueGDfromSolicitations == null || isNaN($scope.modal.RevenueGDfromSolicitations)) ? true : false;
        $scope.modal.IsRevenueGDRevenueAllOtherSourcesEmpty = ($scope.modal.RevenueGDRevenueAllOtherSources == null || isNaN($scope.modal.RevenueGDRevenueAllOtherSources)) ? true : false;
        $scope.modal.IsExpensesGDExpendituresProgramServicesEmpty = ($scope.modal.ExpensesGDExpendituresProgramServices == null || isNaN($scope.modal.ExpensesGDExpendituresProgramServices)) ? true : false;
        $scope.modal.IsExpensesGDValueofAllExpendituresEmpty = ($scope.modal.ExpensesGDValueofAllExpenditures == null || isNaN($scope.modal.ExpensesGDValueofAllExpenditures)) ? true : false;
        $scope.modal.IsTotalDollarValueofGrossReceiptsEmpty = ($scope.modal.TotalDollarValueofGrossReceipts == null || isNaN($scope.modal.TotalDollarValueofGrossReceipts)) ? true : false;
        $scope.modal.IsPercentToProgramServicesEmpty = ($scope.modal.PercentToProgramServices == null || isNaN($scope.modal.PercentToProgramServices)) ? true : false;

        $scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets == null ? null : $scope.modal.BeginingGrossAssets;
        $scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets == null ? null : $scope.modal.EndingGrossAssets;
        $scope.modal.RevenueGDfromSolicitations = $scope.modal.RevenueGDfromSolicitations == null ? null : $scope.modal.RevenueGDfromSolicitations;
        $scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.RevenueGDRevenueAllOtherSources == null ? null : $scope.modal.RevenueGDRevenueAllOtherSources;
        $scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.ExpensesGDExpendituresProgramServices == null ? null : $scope.modal.ExpensesGDExpendituresProgramServices;
        $scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures == null ? null : $scope.modal.ExpensesGDValueofAllExpenditures;
        $scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts == null ? null : $scope.modal.TotalDollarValueofGrossReceipts;
        $scope.modal.PercentToProgramServices = $scope.modal.PercentToProgramServices == null ? null : $scope.modal.PercentToProgramServices;




        //var isOfficerHighpay = !$scope.modal.OfficersHighPay.IsPayOfficers || ($scope.modal.OfficersHighPay.IsPayOfficers && !$scope.checkHighpayCount());
        $scope.modal.CharitiesClosureReason = $scope.addedReasons.join(',');

        if ($scope.modal.OfficersHighPayList != null && $scope.modal.OfficersHighPayList.length == 3)
            $scope.modal.OfficersHighPay.IsCountMax = true;


        //Filing Correspondence
        $scope.modal.CFTAttention = $scope.modal.CFTAttention;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        //ONLINE UPLOAD DOCUMENTS
        $scope.modal.CFTUploadDocumentsList = angular.isNullorEmpty($scope.modal.CFTUploadDocumentsList) ? [] : $scope.modal.CFTUploadDocumentsList;

        //Attestation
        $scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;

        $scope.modal.addedReasons = $scope.addedReasons;
        $rootScope.modal = $scope.modal;
        var isFormValidate = isEffectiveDateExists && $scope.addedReasons.length > 0 && isCharitiesFinancialInfo && isExpensesValid && isSignatureAttestationValidate && isCorrespondenceAddressValid && isAdditionalUploadValid;
        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            if ($scope.modal.IsOptionalRegistration) {
                $location.path('/charitiesOptionalClosureReview');
            }
            else {
                $location.path('/charitiesClosureReview');
            }
        } else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // Toggle selection for a given fruit by name
    $scope.toggleSelection = function toggleSelection(reason) {
        var idx = $scope.addedReasons.indexOf(reason);
        if (idx > -1) {
            $scope.addedReasons.splice(idx, 1);
        }
        else {
            $scope.addedReasons.push(reason);
        }
    };

    $scope.SaveClose = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.isBusinessNameAvailable = false;
        $scope.modal.CharitiesClosureReason = $scope.addedReasons.join(',');

        if ($scope.modal.OfficersHighPayList != null && $scope.modal.OfficersHighPayList.length == 3)
            $scope.modal.OfficersHighPay.IsCountMax = true;


        //Filing Correspondence
        $scope.modal.CFTAttention = $scope.modal.CFTAttention;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        //ONLINE UPLOAD DOCUMENTS
        $scope.modal.CFTUploadDocumentsList = angular.isNullorEmpty($scope.modal.CFTUploadDocumentsList) ? [] : $scope.modal.CFTUploadDocumentsList;

        //Attestation
        $scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;

        $scope.modal.IsBeginingGrossAssetsEmpty = ($scope.modal.BeginingGrossAssets == null || isNaN($scope.modal.BeginingGrossAssets)) ? true: false;
        $scope.modal.IsEndingGrossAssetsEmpty = ($scope.modal.EndingGrossAssets == null || isNaN($scope.modal.EndingGrossAssets)) ? true : false;
        $scope.modal.IsRevenueGDfromSolicitationsEmpty = ($scope.modal.RevenueGDfromSolicitations == null || isNaN($scope.modal.RevenueGDfromSolicitations)) ? true : false;
        $scope.modal.IsRevenueGDRevenueAllOtherSourcesEmpty = ($scope.modal.RevenueGDRevenueAllOtherSources == null || isNaN($scope.modal.RevenueGDRevenueAllOtherSources)) ? true : false;
        $scope.modal.IsExpensesGDExpendituresProgramServicesEmpty = ($scope.modal.ExpensesGDExpendituresProgramServices == null || isNaN($scope.modal.ExpensesGDExpendituresProgramServices)) ? true : false;
        $scope.modal.IsExpensesGDValueofAllExpendituresEmpty = ($scope.modal.ExpensesGDValueofAllExpenditures == null || isNaN($scope.modal.ExpensesGDValueofAllExpenditures)) ? true : false;
        $scope.modal.IsTotalDollarValueofGrossReceiptsEmpty = ($scope.modal.TotalDollarValueofGrossReceipts == null || isNaN($scope.modal.TotalDollarValueofGrossReceipts)) ? true : false;
        $scope.modal.IsPercentToProgramServicesEmpty = ($scope.modal.PercentToProgramServices == null || isNaN($scope.modal.PercentToProgramServices)) ? true : false;

        $scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets == null ? null : $scope.modal.BeginingGrossAssets;
        $scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets == null ? null : $scope.modal.EndingGrossAssets;
        $scope.modal.RevenueGDfromSolicitations = $scope.modal.RevenueGDfromSolicitations == null ? null : $scope.modal.RevenueGDfromSolicitations;
        $scope.modal.RevenueGDRevenueAllOtherSources = $scope.modal.RevenueGDRevenueAllOtherSources == null ? null : $scope.modal.RevenueGDRevenueAllOtherSources;
        $scope.modal.ExpensesGDExpendituresProgramServices = $scope.modal.ExpensesGDExpendituresProgramServices == null ? null : $scope.modal.ExpensesGDExpendituresProgramServices;
        $scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures == null ? null : $scope.modal.ExpensesGDValueofAllExpenditures;
        $scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts == null ? null : $scope.modal.TotalDollarValueofGrossReceipts;
        $scope.modal.PercentToProgramServices = $scope.modal.PercentToProgramServices == null ? null : $scope.modal.PercentToProgramServices;

        $scope.modal.addedReasons = $scope.addedReasons;
        $rootScope.modal = $scope.modal;
        if ($scope.modal.IsOptionalRegistration) {
            $scope.modal.OnlineNavigationUrl = "/charitiesOptionalClosure";
        }
        else {
            $scope.modal.OnlineNavigationUrl = "/charitiesClosure";
        }
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

});
wacorpApp.controller('charitiesClosureReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    $scope.Init = function () {
        $scope.modal = $rootScope.modal;
    }

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        if ($scope.modal.IsOptionalRegistration) {
            $location.path('/charitiesOptionalClosure');
        }
        else {
            $location.path('/charitiesClosure');
        }
    }

    $scope.AddToCart = function () {
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0)
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");

        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0)
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");

        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
            $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });

    };
});
wacorpApp.controller('submitFundraisingServiceContractController', function ($scope, $filter, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------- Charities Amendmenet Functionality------------- */

    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    var originalEntityName = "";
    var isShortFiscalYearChecked = false;

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.getCharitiesDetails(); // getCharitiesDetails method is available in this controller only.
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    //Get Charities Details from Registration Number
    $scope.getCharitiesDetails = function () {
        $rootScope.BusinessTypeID = 7; // charity business type
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 341 is FUNDRAISING SERVICE CONTRACT REGISTRATION
            data = { params: { CharityID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 341, transactionID: $rootScope.transactionID } };
        else
            data = { params: { CharityID: $routeParams.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 341, transactionID: $rootScope.transactionID } };

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/CharitiesSearch');
            }
            // getCharitiesSubmitFundraisingCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.getCharitiesSubmitFundraisingCriteria, data, function (response) {
                $scope.modal = response.data;
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }
                $scope.modal.UBINumber = $scope.modal.UBINumber || null;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                if ($scope.modal.IsActiveFilingExist) {
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                if ($scope.modal.FundraiserSubContractorList.length > 0) {
                    $scope.modal.FundraiserSubContractorList[0].ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.FundraiserSubContractorList[0].ContributionServicesTypeId) ? [] : $scope.modal.FundraiserSubContractorList[0].ContributionServicesTypeId.split(',');
                }
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.ContractTermBeginDate = wacorpService.dateFormatService($scope.modal.ContractTermBeginDate);
                $scope.modal.ContractTermEndDate = wacorpService.dateFormatService($scope.modal.ContractTermEndDate);
                $scope.modal.DateServiceBeginDate = wacorpService.dateFormatService($scope.modal.DateServiceBeginDate);
                $scope.modal.DateServiceEndDate = wacorpService.dateFormatService($scope.modal.DateServiceEndDate);

                $scope.modal.CFTCorrespondenceAddress.Attention = $scope.modal.CFTCorrespondenceAddress.Attention != null ? $scope.modal.CFTCorrespondenceAddress.Attention : null;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
                $scope.modal.isShowReturnAddress = true;
                if ($scope.modal.FundraisersList.length > 0) {
                    angular.forEach($scope.modal.FundraisersList, function (fundraiser) {
                        fundraiser.SequenceNo = fundraiser.FundRaiserID;
                    });
                }

            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.isShowReturnAddress = true;
        }
    };

    var validateContractDate = function () {
        if ($scope.modal.ContractTermBeginDate != null && $scope.modal.ContractTermEndDate != null && $scope.modal.ContractTermBeginDate != undefined && $scope.modal.ContractTermEndDate != undefined && $scope.modal.ContractTermBeginDate != "" && $scope.modal.ContractTermEndDate != "") {
            if (new Date($scope.modal.ContractTermEndDate) < new Date($scope.modal.ContractTermBeginDate)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    };

    var validateServiceDate = function () {
        if ($scope.modal.DateServiceBeginDate != null && $scope.modal.DateServiceEndDate != null && $scope.modal.DateServiceBeginDate != undefined && $scope.modal.DateServiceEndDate != undefined && $scope.modal.DateServiceBeginDate != "" && $scope.modal.DateServiceEndDate != "") {
            if (new Date($scope.modal.DateServiceEndDate) < new Date($scope.modal.DateServiceBeginDate)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    };

    $scope.Review = function (fundraisingServiceContractRegForm) {

        $scope.validateErrorMessage = true;

        var isFundraiserListValid = true;
        if ($scope.modal.IsCommercialFundraisersContributionsInWA)
            isFundraiserListValid = $scope.modal.FundraisersList.length > 0;
        
        var isSubContractorValid = $scope.modal.FundraiserSubContractorList.length > 0;

        var isContractTermDatesValid = ($scope.fundraisingServiceContractRegForm.fundraiserServiceContract.$valid);

        var contractEndDateValid = validateContractDate(); // validateContractDate method is available in this controller only.

        var serviceEndDateValid = validateServiceDate(); // validateServiceDate method is available in this controller only.

        var isSignatureAttestationValidate = ($scope.fundraisingServiceContractRegForm.SignatureForm.$valid);
        //var isCorrespondenceAddressValid = $scope.fundraisingServiceContractRegForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.fundraisingServiceContractRegForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.fundraisingServiceContractRegForm.cftCorrespondenceAddressForm.$valid;

        var isCharitiesContractValid = ($scope.modal.CharitiesContractUploadDocument == null || $scope.modal.CharitiesContractUploadDocument.length == 0) ? false : true;
        var isContractBetweenCharityAndFundValid = ($scope.modal.CharitiesFundraiserContractUpload == null || $scope.modal.CharitiesFundraiserContractUpload.length == 0) ? false : true;

        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

        var isFormValidate = isFundraiserListValid && isSubContractorValid && isContractTermDatesValid && isSignatureAttestationValidate && isCorrespondenceAddressValid
                                && isAdditionalUploadValid && isCharitiesContractValid && isContractBetweenCharityAndFundValid
                                && !contractEndDateValid && !serviceEndDateValid;


        if (isFormValidate) {
            $scope.fillAmendmentData(); // fillAmendmentData method is available in this controller only.
            $scope.validateErrorMessage = false;
            $scope.isReview = true;
            $location.path('/submitFundraisingServiceContractReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);

    };


    $scope.fillAmendmentData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        if ($scope.modal.FundraiserSubContractorList.length > 0) {
            if ($scope.modal.FundraiserSubContractorList[0].ContributionServicesTypeId != null && $scope.modal.FundraiserSubContractorList[0].ContributionServicesTypeId.length > 0 && typeof ($scope.modal.FundraiserSubContractorList[0].ContributionServicesTypeId) != "string") {
                $scope.modal.FundraiserSubContractorList[0].ContributionServicesTypeId = $scope.modal.FundraiserSubContractorList[0].ContributionServicesTypeId.join(",");
            }
        }
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $rootScope.modal = $scope.modal;
    };

    $scope.AmendSaveClose = function () {
        $scope.fillAmendmentData(); // fillAmendmentData method is available in this controller only.
        $scope.modal.OnlineNavigationUrl = "/submitFundraisingServiceContract";
        //$scope.modal.IsRegisteredAgentConsent = true; $scope.modal.Agent.IsRegisteredAgentConsent = true; //TFS 1143
        // CharitiesSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }
});

wacorpApp.controller('submitFundraisingServiceContractReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Charities Registration Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        $scope.modal = $rootScope.modal;
    };

    $scope.CharitiesAmendmentAddToCart = function () {
        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        //$scope.modal.IsRegisteredAgentConsent = true; $scope.modal.Agent.IsRegisteredAgentConsent = true; //TFS 1143
        // CharitiesAddToCart is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
            $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
            $rootScope.modal = null;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/submitFundraisingServiceContract');
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

});

wacorpApp.controller('submitFundraisingServiceContractAmendmentController', function ($scope, $filter, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------- Charities Amendmenet Functionality------------- */

    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    var originalEntityName = "";
    var isShortFiscalYearChecked = false;
    var FSCCount = 0;

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.getCharitiesDetails(); // getCharitiesDetails method is available in this controller only.
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    var validateFSCList = function () {
        FSCCount = GetLatestFSCCount();
        //if ($scope.modal.FundraiserServiceContractList == null || $scope.modal.FundraiserServiceContractList.length == 0 || FSCCount == 0) {
        if ($scope.modal.IsFSCDoNotAmend) {
            //wacorpService.alertDialog("Please file a fundraising service contract registration, since this charity has no service contract.");
            wacorpService.alertDialog("The Organization does not have a current contract on record to amend, please file as a new Fundraising Service Contract Registration. If you have any questions please call 360-725-0378.");
            return false;
        }
        return true;
    };

    var GetLatestFSCCount = function () {
        var cnt = 0;
        angular.forEach($scope.modal.FundraiserServiceContractList, function (fscData) {
            if (fscData.Status == principalStatus.DELETE) {
                cnt++;
            }
        });
        if (cnt == $scope.modal.FundraiserServiceContractList.length) {
            return 0;
        }
        else {
            return 1;
        }
    };

    //Get Charities Details from Registration Number
    $scope.getCharitiesDetails = function () {
        $rootScope.BusinessTypeID = 7; // charity business type
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 1112 is FUNDRAISING SERVICE CONTRACT AMENDMENT
            data = { params: { CharityID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 1112, transactionID: $rootScope.transactionID } };
        else
            data = { params: { CharityID: $routeParams.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 1112, transactionID: $rootScope.transactionID } };

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/CharitiesSearch');
            }
            // getCharitiesSubmitFundraisingAmendmentCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.getCharitiesSubmitFundraisingAmendmentCriteria, data, function (response) {
                $scope.modal = response.data;
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }
                $scope.modal.UBINumber = $scope.modal.UBINumber || null;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                if ($scope.modal.IsActiveFilingExist) {
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                $scope.modal.CFTCorrespondenceAddress.Attention = $scope.modal.CFTCorrespondenceAddress.Attention != null ? $scope.modal.CFTCorrespondenceAddress.Attention : null;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;

                //Soft Alert for not allowing FSC Amendment if, Charity does not have any FSC List
                validateFSCList();

                $scope.modal.isShowReturnAddress = true;
            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.isShowReturnAddress = true;
        }
    };

    $scope.Review = function (fundraisingServiceContractAmendmentForm) {
        
        //Hard Stop for not allowing FSC Amendment if, Charity does not have any FSC List
        if (validateFSCList()) {

            $scope.validateErrorMessage = true;

            var isSignatureAttestationValidate = ($scope.fundraisingServiceContractAmendmentForm.SignatureForm.$valid);
            //var isCorrespondenceAddressValid = $scope.fundraisingServiceContractRegForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.fundraisingServiceContractRegForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
            var isCorrespondenceAddressValid = $scope.fundraisingServiceContractAmendmentForm.cftCorrespondenceAddressForm.$valid;

            var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

            var isFormValidate = isSignatureAttestationValidate && isCorrespondenceAddressValid
                                    && isAdditionalUploadValid;


            if (isFormValidate) {
                $scope.fillAmendmentData(); // fillAmendmentData method is available in this controller only.
                $scope.validateErrorMessage = false;
                $scope.isReview = true;
                $location.path('/submitFundraisingServiceContractAmendmentReview');
            }
            else
                // Folder Name: app Folder
                // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };
    

    $scope.fillAmendmentData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $rootScope.modal = $scope.modal;
    };

    $scope.AmendSaveClose = function () {
        $scope.fillAmendmentData(); // fillAmendmentData method is available in this controller only.
        $scope.modal.OnlineNavigationUrl = "/submitFundraisingServiceContractAmendment/" + $scope.modal.CFTId;

        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);

        // CharitiesSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesSaveandClose, $scope.modelDraft, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    //Delete Fundraising Service Contract
    $scope.deleteFundraisingContract = function (contractData) {
        // Folder Name: app Folder
        // Alert Name: ConfirmMessage method is available in alertMessages.js 
        wacorpService.confirmDialog($scope.messages.Confirm.ConfirmMessage, function () {
            contractData.Status = principalStatus.DELETE;
        });
    };

    //Edit Fundrainsing Service Contract
    $scope.editFundraisingContract = function (contractData) {
        //localStorage.setItem('FSCAmendData', {});
        localStorage.setItem('FSCAmendData', JSON.stringify(contractData));
        //localStorage.setItem('FSCList', []);
        localStorage.setItem('FSCList', JSON.stringify($scope.modal.FundraiserServiceContractList));
        $rootScope.$emit("CallFSCDataMethod", {});
        $("#divEditFSC").modal('toggle');
    };

    $scope.closeFSCInfo = function () {
        var fscList = localStorage.getItem('FSCList');
        $scope.modal.FundraiserServiceContractList = JSON.parse(fscList);
        $('#divEditFSC').modal('toggle');
    };

    var onCloseToggle = $rootScope.$on("CallCloseToggleMethod", function () {
        $scope.closeFSCInfo(); 
    });

    $scope.$on('$destroy', function () {
        onCloseToggle(); 
    });

    //$('.modal-dialog').draggable({
    //    handle: ".modal-header"
    //});

});

wacorpApp.controller('submitFundraisingServiceContractAmendmentReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Charities Registration Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        $scope.modal = $rootScope.modal;
    };

    $scope.CharitiesAmendmentAddToCart = function () {
        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        //$scope.modal.IsRegisteredAgentConsent = true; $scope.modal.Agent.IsRegisteredAgentConsent = true; //TFS 1143
        // CharitiesAddToCart is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
            $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
            $rootScope.modal = null;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/submitFundraisingServiceContractAmendment/' + $scope.modal.CFTId);
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

});

wacorpApp.controller('EditCharityFundraiserServiceContractController', function ($scope, $filter, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------- Charities Amendmenet Functionality------------- */

    // scope variables
    $scope.editFSCModal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    var fscList = [];
    var CurrentFSCAmendData = {};

    // page load
    $scope.Init = function () {
        CurrentFSCAmendData = JSON.parse(localStorage.getItem('FSCAmendData'));
        fscList = JSON.parse(localStorage.getItem('FSCList'));
        $scope.messages = messages;
        getCurrentFSCDetails(CurrentFSCAmendData); // getCharitiesDetails method is available in this controller only.
    };

    var onMethod = $rootScope.$on("CallFSCDataMethod", function () {
        $scope.Init(); // initMergedOrgBusinessSearch method is available in this controller only.
    });

    $scope.$on('$destroy', function () {
        onMethod(); // onMethod method is available in this controller only.
    });

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    var updateCurrentFSCList = function (CurrentFSCAmendData, currentFSCIndex,isHideToggle) {
        fscList[currentFSCIndex].IsInitialData = true;
        fscList[currentFSCIndex].FundraiserSubContractorList = CurrentFSCAmendData.FundraiserSubContractorList;
        fscList[currentFSCIndex].FundraisersList = CurrentFSCAmendData.FundraisersList;
        fscList[currentFSCIndex].CharitiesContractUploadDocument = CurrentFSCAmendData.CharitiesContractUploadDocument;
        fscList[currentFSCIndex].CharitiesFundraiserContractUpload = CurrentFSCAmendData.CharitiesFundraiserContractUpload;
        fscList[currentFSCIndex].ContractTermBeginDate = CurrentFSCAmendData.ContractTermBeginDate;
        fscList[currentFSCIndex].ContractTermEndDate = CurrentFSCAmendData.ContractTermEndDate;
        fscList[currentFSCIndex].DateServiceBeginDate = CurrentFSCAmendData.DateServiceBeginDate;
        fscList[currentFSCIndex].DateServiceEndDate = CurrentFSCAmendData.DateServiceEndDate;
        fscList[currentFSCIndex].IsContractPerpetual = CurrentFSCAmendData.IsContractPerpetual;
        fscList[currentFSCIndex].IsContractCancelled = CurrentFSCAmendData.IsContractCancelled;
        fscList[currentFSCIndex].ContractCancelledDate = CurrentFSCAmendData.ContractCancelledDate;
        fscList[currentFSCIndex].IsCommercialFundraisersContributionsInWA = CurrentFSCAmendData.IsCommercialFundraisersContributionsInWA;
        if (isHideToggle) {
            fscList[currentFSCIndex].Status = "M";
            localStorage.setItem('FSCList', null);
            localStorage.setItem('FSCList', JSON.stringify(fscList));
            $rootScope.$emit("CallCloseToggleMethod", {});
        }
        else {
            localStorage.setItem('FSCList', null);
            localStorage.setItem('FSCList', JSON.stringify(fscList));
        }
    };

    var assignCurrentFSCObj = function (item) {
        CurrentFSCAmendData.FundraiserSubContractorList = item.FundraiserSubContractorList;
        CurrentFSCAmendData.FundraisersList = item.FundraisersList;
        CurrentFSCAmendData.CharitiesContractUploadDocument = item.CharitiesContractUploadDocument;
        CurrentFSCAmendData.CharitiesFundraiserContractUpload = item.CharitiesFundraiserContractUpload;
        CurrentFSCAmendData.ContractTermBeginDate = item.ContractTermBeginDate;
        CurrentFSCAmendData.ContractTermEndDate = item.ContractTermEndDate;
        CurrentFSCAmendData.DateServiceBeginDate = item.DateServiceBeginDate;
        CurrentFSCAmendData.DateServiceEndDate = item.DateServiceEndDate;
        CurrentFSCAmendData.IsContractPerpetual = item.IsContractPerpetual;
        CurrentFSCAmendData.IsContractCancelled = item.IsContractCancelled;
        CurrentFSCAmendData.ContractCancelledDate = item.ContractCancelledDate;
        CurrentFSCAmendData.IsCommercialFundraisersContributionsInWA = item.IsCommercialFundraisersContributionsInWA;
        CurrentFSCAmendData.IsInitialData = item.IsInitialData;

        if (CurrentFSCAmendData.FundraiserSubContractorList.length > 0) {
            var cnt = 0;
            angular.forEach(CurrentFSCAmendData.FundraiserSubContractorList, function (fscData) {
                fscData.SequenceNo = ++cnt;
            });
        }

        if (CurrentFSCAmendData.FundraisersList.length > 0) {
            var cnt = 0;
            angular.forEach(CurrentFSCAmendData.FundraisersList, function (fundData) {
                fundData.SequenceNo = ++cnt;
                if (fundData.FEINNumber!=null && fundData.FEINNumber!=undefined)
                {
                    fundData.CFTType = "F";
                }
            });
        }
    };

    //Get Current FSC Details from Registration Number
    var getCurrentFSCDetails = function (item) {
        var data = null;
        var url = "";

        if (item.IsFSCTrue && !item.IsInitialData) {
            // here filingTypeID: 1112 is FUNDRAISING SERVICE CONTRACT AMENDMENT
            data = { params: { FSCId: item.FSCId } };
            url = webservices.CFT.getFundraisingServiceContractEntity;
            //Need to implement Edit CurrentFSC Details in on Monday
            wacorpService.get(url, data, function (response) {
                $scope.editFSCModal = response.data;
                $scope.editFSCModal.BusinessFiling.FilingTypeName = "FUNDRAISING SERVICE CONTRACT AMENDMENT";
                $scope.editFSCModal.ContractTermBeginDate = wacorpService.dateFormatService($scope.editFSCModal.ContractTermBeginDate);
                $scope.editFSCModal.ContractTermEndDate = wacorpService.dateFormatService($scope.editFSCModal.ContractTermEndDate);
                $scope.editFSCModal.DateServiceBeginDate = wacorpService.dateFormatService($scope.editFSCModal.DateServiceBeginDate);
                $scope.editFSCModal.DateServiceEndDate = wacorpService.dateFormatService($scope.editFSCModal.DateServiceEndDate);
                $scope.editFSCModal.ContractCancelledDate = wacorpService.dateFormatService($scope.editFSCModal.ContractCancelledDate);
                $scope.editFSCModal.FSCId = item.FSCId;

                var currentFSCIndex = -1;
                //var currentFSCIndex = fscList.findIndex(x=>x.FSCId == item.FSCId);
                for (var i = 0; i < fscList.length; i++) {
                    if (fscList[i].FSCId == item.FSCId) {
                        currentFSCIndex = i;
                    }
                }

                //assignCurrentFSCObj($scope.editFSCModal);
                updateCurrentFSCList($scope.editFSCModal, currentFSCIndex,false);
            }, function (response) { });
        }
        else if (!item.IsFSCTrue && !item.IsInitialData) {
            data = { params: { FSCId: item.FSCId } };
            url = webservices.CFT.getNonContractServiceEntity;
            wacorpService.get(url, data, function (response) {
                $scope.editFSCModal = response.data;
                $scope.editFSCModal.BusinessFiling.FilingTypeName = "FUNDRAISING SERVICE CONTRACT AMENDMENT";
                $scope.editFSCModal.ContractTermBeginDate = wacorpService.dateFormatService($scope.editFSCModal.ContractTermBeginDate);
                $scope.editFSCModal.ContractTermEndDate = wacorpService.dateFormatService($scope.editFSCModal.ContractTermEndDate);
                $scope.editFSCModal.DateServiceBeginDate = wacorpService.dateFormatService($scope.editFSCModal.DateServiceBeginDate);
                $scope.editFSCModal.DateServiceEndDate = wacorpService.dateFormatService($scope.editFSCModal.DateServiceEndDate);
                $scope.editFSCModal.ContractCancelledDate = wacorpService.dateFormatService($scope.editFSCModal.ContractCancelledDate);
                $scope.editFSCModal.FSCId = item.FSCId;

                //var currentFSCIndex = fscList.findIndex(x=>x.FSCId == item.FSCId);
                var currentFSCIndex = -1;
                for (var i = 0; i < fscList.length; i++) {
                    if (fscList[i].FSCId == item.FSCId) {
                        currentFSCIndex = i;
                    }
                }

                //assignCurrentFSCObj($scope.editFSCModal);
                updateCurrentFSCList($scope.editFSCModal, currentFSCIndex,false);
            }, function (response) { });
        }
        else {
            //var currentFSCIndex = fscList.findIndex(x=>x.FSCId == item.FSCId);
            var currentFSCIndex = -1;
            for (var i = 0; i < fscList.length; i++) {
                if (fscList[i].FSCId == item.FSCId) {
                    currentFSCIndex = i;
                }
            }

            CurrentFSCAmendData.ContractTermBeginDate = wacorpService.dateFormatService(CurrentFSCAmendData.ContractTermBeginDate);
            CurrentFSCAmendData.ContractTermEndDate = wacorpService.dateFormatService(CurrentFSCAmendData.ContractTermEndDate);
            CurrentFSCAmendData.DateServiceBeginDate = wacorpService.dateFormatService(CurrentFSCAmendData.DateServiceBeginDate);
            CurrentFSCAmendData.DateServiceEndDate = wacorpService.dateFormatService(CurrentFSCAmendData.DateServiceEndDate);
            CurrentFSCAmendData.ContractCancelledDate = wacorpService.dateFormatService(CurrentFSCAmendData.ContractCancelledDate);
            $scope.editFSCModal = CurrentFSCAmendData;
            $scope.editFSCModal.FSCId = item.FSCId;
            $scope.editFSCModal.BusinessFiling.FilingTypeName = "FUNDRAISING SERVICE CONTRACT AMENDMENT";
            updateCurrentFSCList($scope.editFSCModal, currentFSCIndex,false);
        }        
    };

    var validateContractDate = function () {
        if ($scope.editFSCModal.ContractTermBeginDate != null && $scope.editFSCModal.ContractTermEndDate != null && $scope.editFSCModal.ContractTermBeginDate != undefined && $scope.editFSCModal.ContractTermEndDate != undefined && $scope.editFSCModal.ContractTermBeginDate != "" && $scope.editFSCModal.ContractTermEndDate != "") {
            if (new Date($scope.editFSCModal.ContractTermEndDate) < new Date($scope.editFSCModal.ContractTermBeginDate)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    };

    var validateServiceDate = function () {
        if ($scope.editFSCModal.DateServiceBeginDate != null && $scope.editFSCModal.DateServiceEndDate != null && $scope.editFSCModal.DateServiceBeginDate != undefined && $scope.editFSCModal.DateServiceEndDate != undefined && $scope.editFSCModal.DateServiceBeginDate != "" && $scope.editFSCModal.DateServiceEndDate != "") {
            if (new Date($scope.editFSCModal.DateServiceEndDate) < new Date($scope.editFSCModal.DateServiceBeginDate)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    };

    $scope.Submit = function () {
        $scope.validateErrorMessage = true;

        var isFundraiserListValid = true;
        if ($scope.editFSCModal.IsCommercialFundraisersContributionsInWA)
            isFundraiserListValid = $scope.editFSCModal.FundraisersList.length > 0;

        var isContractTermDatesValid = ($scope.EditFundraisingServiceContractForm.fundraiserServiceContract.$valid);

        var contractEndDateValid = validateContractDate(); // validateContractDate method is available in this controller only.

        var serviceEndDateValid = validateServiceDate(); // validateServiceDate method is available in this controller only.

        var isCharitiesContractValid = ($scope.editFSCModal.CharitiesContractUploadDocument == null || $scope.editFSCModal.CharitiesContractUploadDocument.length == 0) ? false : true;
        var isContractBetweenCharityAndFundValid = ($scope.editFSCModal.CharitiesFundraiserContractUpload == null || $scope.editFSCModal.CharitiesFundraiserContractUpload.length == 0) ? false : true;

        var isContractCancelledValid = $scope.EditFundraisingServiceContractForm.cancellationdate.$valid;



        var isFormValidate = isFundraiserListValid && isContractTermDatesValid 
                                && isCharitiesContractValid && isContractBetweenCharityAndFundValid && isContractCancelledValid
                                && !contractEndDateValid && !serviceEndDateValid;


        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            var currentFSCIndex = -1;
            for (var i = 0; i < fscList.length; i++) {
                if (fscList[i].FSCId == $scope.editFSCModal.FSCId) {
                    currentFSCIndex = i;
                }
            }
            //var currentFSCIndex = fscList.findIndex(x=>x.FSCId == $scope.editFSCModal.FSCId);
            updateCurrentFSCList($scope.editFSCModal, currentFSCIndex,true);
        }
        else {
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };
});

wacorpApp.controller('charitiesOptionalRegistrationController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    /* --------- Charities Registration Functionality------------- */
    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    $scope.showError = false;
    $scope.Init = function () {
        $scope.messages = messages;
        $rootScope.BusinessTypeID = 7;//Charitable Organization business type
        //get business information
        // Here filingTypeID: 158 is CHARITABLE ORGANIZATION OPTIONAL REGISTRATION
        var data = { params: { businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 158, transactionID: $rootScope.transactionID } };
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/charitiesOptionalRegistration');
            }
            // CharitiesCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.CharitiesCriteria, data, function (response) {
                //angular.extend(response.data, $scope.modal);
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                //$scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
                //$scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.County = $scope.modal.EntityStreetAddress.County != null ? $scope.modal.EntityStreetAddress.County : "";
                $scope.modal.EntityStreetAddress.Country = codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = codes.USA;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';
                $scope.modal.IsNewRegistration = true;
                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;
                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                if (!($scope.modal.FederalTaxExemptId == null || $scope.modal.FederalTaxExemptId == undefined))
                    $scope.modal.FederalTaxExemptId = $scope.modal.FederalTaxExemptId == 0 ? '' : $scope.modal.FederalTaxExemptId.toString();

                if (!($scope.modal.OSJurisdictionCountyId == null || $scope.modal.OSJurisdictionCountyId == undefined))
                    $scope.modal.OSJurisdictionCountyId = $scope.modal.OSJurisdictionCountyId == 0 ? '' : $scope.modal.OSJurisdictionCountyId.toString();

                if (!($scope.modal.OSJurisdictionStateId == null || $scope.modal.OSJurisdictionStateId == undefined))
                    $scope.modal.OSJurisdictionStateId = $scope.modal.OSJurisdictionStateId == 0 ? '' : $scope.modal.OSJurisdictionStateId.toString();

                if (!($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == undefined))
                    $scope.modal.JurisdictionCountry = $scope.modal.JurisdictionCountry == 0 ? '' : $scope.modal.JurisdictionCountry.toString();

                if (!($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == undefined))
                    $scope.modal.JurisdictionState = $scope.modal.JurisdictionState == 0 ? '' : $scope.modal.JurisdictionState.toString();

                $scope.modal.isShowReturnAddress = true;
            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.isShowReturnAddress = true;
        }
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    $scope.Review = function (charitiesOptionalRegistrationForm) {
         
        if (!$scope.modal.IsAnyOnePaid) {
            $scope.validateErrorMessage = true;

            //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {
                $scope.EntityNameCheck = true;

                var isOrgNameValid = $scope.modal.EntityName != null && $scope.modal.EntityName != "" ? true : false;

                var isPurposeValid = $scope.modal.Purpose != null ? true : false;

                var isSolicitUpload = ($scope.modal.IsUploadAddress ? ($scope.modal.UploadListOfAddresses.length > 0 ? true : false) : true);

                //var isEntityNameValid = $scope.charitiesRegistrationForm.cftEntityName.$valid;

                var isTaxUploadValid = $scope.modal.IsShowFederalTax ? ($scope.modal.FederaltaxUpload.length > 0 ? true : false) : true;

                //var isEntityNameValid = $scope.modal.isBusinessNameAvailable ? true : false;

                //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);

                var result = $scope.modal.IsQualified ? true : false;

                //var isEntityNameValid = ($scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : ($scope.modal.isBusinessNameChanged ? true : false)));
                var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

                if (isEntityNameValid) {
                    $scope.EntityNameCheck = false;
                }
                else {
                    $scope.EntityNameCheck = true;
                }

                var isEntityInfo = ($scope.charitiesOptionalRegistrationForm.entityInfo.$valid);

                var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

                var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalActionsUploads.length > 0 ? true : false) : true);

                //var isLegalInfo = ($scope.charitiesOptionalRegistrationForm.fundraiserLegalInfo.$valid);

                var Fein = $scope.modal.FEINNumber;
                var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

                var Ubi = $scope.modal.UBINumber;
                var isValidUbi = $scope.modal.IsEntityRegisteredInWA && $scope.modal.JurisdictionState == "271" ?
                    (Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9 ? true : false) : (Ubi == null || Ubi == '' || Ubi.length == 9 ? true : false);


                var isSignatureAttestationValidate = ($scope.charitiesOptionalRegistrationForm.SignatureForm.$valid);
                var isCorrespondenceAddressValid = $scope.charitiesOptionalRegistrationForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.charitiesOptionalRegistrationForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;

                //var isIntegratedAuxiliary = $scope.modal.IsIntegratedAuxiliary ? true : false;

                //var isPoliticalOrganization = $scope.modal.IsPoliticalOrganization ? true : false;

                //var isQualifierOption = (!$scope.modal.IsRaisingFundsForIndividual && !$scope.modal.IsRaisingLessThan50000 ? false : true)

                var isInfoAccurate = $scope.modal.IsInfoAccurate ? true : false;

                //Upload Additional Documents
                var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

                var isFormValidate = isOrgNameValid && isTaxUploadValid && isPurposeValid && isSolicitUpload && isEntityNameValid && isEntityInfo
                   && isLegalActionsListValid && isLegalActionsUploadValid && isSignatureAttestationValidate && isValidFein && isValidUbi && isInfoAccurate
                   && isAdditionalUploadValid && isCorrespondenceAddressValid && result;

                $scope.fillOptionalRegData(); // fillOptionalRegData method is available in this controller only.

                if (isFormValidate) {
                    $scope.validateErrorMessage = false;
                    $scope.isReview = true;
                    $location.path('/charitiesOptionalRegistrationReview');
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: InvalidFilingMsg method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
            //}
            //else {
            //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
            //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
            //        return false;
            //    }
            //}
        }
        else {
            // Folder Name: app Folder
            // Alert Name: qualifier method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifier);
            $rootScope.modal = null;
            $location.path("/charitiesRegistration");
        }

    };

    $scope.validateQualifierQuestions = function () {

        $scope.modal.IsQualified = ($scope.modal.IsIntegratedAuxiliary || $scope.modal.IsPoliticalOrganization
            || $scope.modal.IsRaisingFundsForIndividual || $scope.modal.IsRaisingLessThan50000)
    };

    $scope.fillOptionalRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.EntityName = $scope.modal.EntityName || null;
        $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
        $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
        $scope.modal.OSJurisdictionId = $scope.modal.OSJurisdictionStateId != "" ? $scope.modal.OSJurisdictionStateId : $scope.modal.OSJurisdictionCountyId;
        $scope.modal.isBusinessNameAvailable = $scope.modal.isBusinessNameAvailable || false;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;

        $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
        $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
        $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);
        $scope.modal.EntityStreetAddress.IsAddressSame = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        //if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
        //    $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.IsIntegratedAuxiliary = $scope.modal.IsIntegratedAuxiliary;
        $scope.modal.IsPoliticalOrganization = $scope.modal.IsPoliticalOrganization;
        $scope.modal.IsRaisingFundsForIndividual = $scope.modal.IsRaisingFundsForIndividual;
        $scope.modal.IsRaisingLessThan50000 = $scope.modal.IsRaisingLessThan50000;

        $rootScope.modal = $scope.modal;
    }

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillOptionalRegData(); // fillOptionalRegData method is available in this controller only.
        $scope.modal.OnlineNavigationUrl = "/charitiesOptionalRegistration";
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    //to validate the Qualifier Questioner
    $scope.validateQualifier = function () {

        if ($scope.modal.IsAnyOnePaid) {
            // Folder Name: app Folder
            // Alert Name: qualifier method is available in alertMessages.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifier);
            $rootScope.modal = null;
            $location.path("/charitiesRegistration");
        }
        else {
            return true;
        }
    };
});
wacorpApp.controller('charitiesOptionalRegistrationReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Charities Registration Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        $scope.modal = $rootScope.modal;
    };

    $scope.CharitiesAddToCart = function () {

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/shoppingCart');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/charitiesOptionalRegistration');
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

});

wacorpApp.controller('charitiesOptionalSearchController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
    
    /* --------Business Search Functionality------------- */

    $rootScope.charitySearchPath = $routeParams.charitySearchType;
    $scope.selectedEntity = null;
    $scope.submitCharityEntity = getNavigation;

    function getNavigation() {
        $rootScope.CharityID = $scope.selectedEntity.CFTId;
        if ($rootScope.charitySearchPath == 'OptionalRegistration') {
            $location.path('/charitiesOptionalRegistrationUpdate/' + $scope.selectedEntity.CFTId);
        }
    }

});



wacorpApp.controller('charitiesOptionalRegistrationUpdateController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    /* --------- Charities Registration Functionality------------- */
    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;

    $scope.Init = function () {
        $scope.messages = messages;
        $rootScope.BusinessTypeID = 7;//Charitable Organization business type
        //get business information
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 162 is CHARITABLE ORGANIZATION OPTIONAL RENEWAL
            data = { params: { businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 162, transactionID: $rootScope.transactionID } };
        else
            // here filingTypeID: 160 is CHARITABLE ORGANIZATION RENEWAL
            data = { params: { CharityID: $rootScope.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 160, transactionID: $rootScope.transactionID } };

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/charitiesOptionalRegistrationUpdate');
            }
            // getOptionalRegistrationUpdateDetails method is available in constants.js.
            wacorpService.get(webservices.CFT.getOptionalRegistrationUpdateDetails, data, function (response) {
                //angular.extend(response.data, $scope.modal);
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                //$scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
                //$scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.County = $scope.modal.EntityStreetAddress.County != null ? $scope.modal.EntityStreetAddress.County : "";
                $scope.modal.EntityStreetAddress.Country = codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = codes.USA;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';
                $scope.modal.IsShowFederalTax = $scope.modal.FederaltaxUpload.length > 0 ? true : false;

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);

                    $scope.modal.FeinOldvalue = $scope.modal.FEINNumber;
                }
                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;
                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                if (!($scope.modal.FederalTaxExemptId == null || $scope.modal.FederalTaxExemptId == undefined))
                    $scope.modal.FederalTaxExemptId = $scope.modal.FederalTaxExemptId == 0 ? '' : $scope.modal.FederalTaxExemptId.toString();

                if (!($scope.modal.OSJurisdictionCountyId == null || $scope.modal.OSJurisdictionCountyId == undefined))
                    $scope.modal.OSJurisdictionCountyId = $scope.modal.OSJurisdictionCountyId == 0 ? '' : $scope.modal.OSJurisdictionCountyId.toString();

                if (!($scope.modal.OSJurisdictionStateId == null || $scope.modal.OSJurisdictionStateId == undefined))
                    $scope.modal.OSJurisdictionStateId = $scope.modal.OSJurisdictionStateId == 0 ? '' : $scope.modal.OSJurisdictionStateId.toString();

                if (!($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == undefined))
                    $scope.modal.JurisdictionCountry = $scope.modal.JurisdictionCountry == 0 ? '' : $scope.modal.JurisdictionCountry.toString();

                if (!($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == undefined))
                    $scope.modal.JurisdictionState = $scope.modal.JurisdictionState == 0 ? '' : $scope.modal.JurisdictionState.toString();

                if ($scope.modal.LegalInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.LegalInfoEntityList, function (cftLegalInfo) {
                        cftLegalInfo.SequenceNo = cftLegalInfo.LegalInfoId;
                    });
                }

                if ($scope.modal.AKANamesList.length > 0) {
                    angular.forEach($scope.modal.AKANamesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }

                $scope.modal.isShowReturnAddress = true;
            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.isShowReturnAddress = true;
        }

        // multi dropdown settings
        $scope.dropdownsettings = {
            scrollableHeight: '200px',
            key: "Value",
            value: "Key",
            scrollable: true,
            isKeyList: false
        };

        function isFormValid(form) {
            if (form == undefined) return true;
            return form.$valid
        }

        $scope.Review = function (charitiesOptionalRegistrationForm) {
            $scope.validateErrorMessage = true;
            //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {
            $scope.EntityNameCheck = true;

            var isOrgNameValid = $scope.modal.EntityName != null && $scope.modal.EntityName != "" ? true : false;

            var isPurposeValid = $scope.modal.Purpose != null ? true : false;

            var isSolicitUpload = ($scope.modal.IsUploadAddress ? ($scope.modal.UploadListOfAddresses.length > 0 ? true : false) : true);

            //var isEntityNameValid = $scope.charitiesRegistrationForm.cftEntityName.$valid;

            var isTaxUploadValid = $scope.modal.IsShowFederalTax ? ($scope.modal.FederaltaxUpload.length > 0 ? true : false) : true;

            //var isEntityNameValid = $scope.modal.isBusinessNameAvailable ? true : false;

            //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);

            if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
                if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                    $scope.modal.isBusinessNameChanged = true;
                }
                else {
                    $scope.modal.isBusinessNameChanged = false;
                }
            }

            //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (!$scope.modal.isBusinessNameChanged ? true : false));
            var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

            if (isEntityNameValid) {
                $scope.EntityNameCheck = false;
            }
            else {
                $scope.EntityNameCheck = true;
            }

            var isEntityInfo = ($scope.charitiesOptionalRegistrationUpdateForm.entityInfo.$valid);

            var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

            var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalActionsUploads.length > 0 ? true : false) : true);

            //var isLegalInfo = ($scope.charitiesOptionalRegistrationForm.fundraiserLegalInfo.$valid);

            var Fein = $scope.modal.FEINNumber;
            var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

            var Ubi = $scope.modal.UBINumber;
            // here JurisdictionState = 271 is Washington
            var isValidUbi = $scope.modal.IsEntityRegisteredInWA && $scope.modal.JurisdictionState == "271" ?
                (Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9 ? true : false) : (Ubi == null || Ubi == '' || Ubi.length == 9 ? true : false);


            var isSignatureAttestationValidate = ($scope.charitiesOptionalRegistrationUpdateForm.SignatureForm.$valid);
            var isCorrespondenceAddressValid = $scope.charitiesOptionalRegistrationUpdateForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.charitiesOptionalRegistrationUpdateForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;

            //Upload Additional Documents
            var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

            var isFormValidate = isOrgNameValid && isTaxUploadValid && isPurposeValid && isSolicitUpload && isEntityNameValid && isEntityInfo
               && isLegalActionsListValid && isLegalActionsUploadValid && isSignatureAttestationValidate && isValidFein && isValidUbi
               && isAdditionalUploadValid && isCorrespondenceAddressValid;

            $scope.fillOptionalRegData();

            if (isFormValidate) {
                $scope.validateErrorMessage = false;
                $scope.isReview = true;
                $location.path('/charitiesOptionalRegistrationUpdateReview');
            }
            else
                // Folder Name: app Folder
                // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
            //}
            //else {
            //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
            //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
            //        return false;
            //    }
            //}
        }
    };

    $scope.fillOptionalRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.EntityName = $scope.modal.EntityName || null;
        $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
        $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
        $scope.modal.OSJurisdictionId = $scope.modal.OSJurisdictionStateId != "" ? $scope.modal.OSJurisdictionStateId : $scope.modal.OSJurisdictionCountyId;
        $scope.modal.isBusinessNameAvailable = $scope.modal.isBusinessNameAvailable || false;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
        $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
        $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

        $scope.modal.EntityStreetAddress.IsAddressSame = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        //if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
        //    $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;

        $rootScope.modal = $scope.modal;
    }

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillOptionalRegData(); // fillOptionalRegData method is available in this controller only.
        $scope.modal.OnlineNavigationUrl = "/charitiesOptionalRegistrationUpdate";
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {

            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }
});
wacorpApp.controller('charitiesOptionalRegistrationUpdateReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Charities optional Registration update Functionality------------- */
    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        $scope.modal = $rootScope.modal;
    };

    $scope.CharitiesAddToCart = function () {

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/shoppingCart');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/charitiesOptionalRegistrationUpdate');
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

});

wacorpApp.controller('commercialFundraiserRegistrationController', function ($scope, $location, $rootScope, lookupService, wacorpService) {

    /* --------Commercial Fundraiser Registration Functionality------------- */
    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    var fundriaserProcessedList = [];
    var fundraiserObject = {};



    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        // here BusinessTypeID = 10 is COMMERCIAL FUNDRAISER
        $rootScope.BusinessTypeID = 10;
        //get business information
        // here filingTypeID: 187 is COMMERCIAL FUNDRAISER REGISTRATION
        var data = { params: { businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 187, transactionID: $rootScope.transactionID } };
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/fundraiserRegistration');
            }
            // FundraiserCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.FundraiserCriteria, data, function (response) {
                //angular.extend(response.data, $scope.modal);
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                //FundraiserFEIN
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingYearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingYearBeginningDate);
                $scope.modal.AccountingYearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingYearEndingDate);
                $scope.modal.FirstAccountingYearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingYearEndDate);
                $scope.modal.BondWaiversBondExpirationDate = wacorpService.dateFormatService($scope.modal.BondWaiversBondExpirationDate);
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                $scope.modal.AllContributionsReceived = $scope.modal.AllContributionsReceived || null;
                $scope.modal.AveragePercentToCharity = $scope.modal.AveragePercentToCharity || null;
                $scope.modal.AmountOfFunds = $scope.modal.AmountOfFunds || null;
                //$scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures || null;
                //$scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets || null;
                //$scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets || null;
                //$scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts || null;
                $scope.modal.ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.ContributionServicesTypeId) ? [] : $scope.modal.ContributionServicesTypeId.split(',');
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');

                $scope.modal.CharityAkaInfoEntity.CountiesServedId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CountiesServedId) ? [] : $scope.modal.CharityAkaInfoEntity.CountiesServedId.split(',');
                $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId) ? [] : $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.split(',');
                //$scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
                //$scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.County = $scope.modal.EntityStreetAddress.County != null ? $scope.modal.EntityStreetAddress.County : "";
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country != null ? $scope.modal.LegalInfo.LegalInfoAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';
                $scope.modal.AKASolicitNameId = '';
                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;                
                $scope.modal.isShowReturnAddress = true;
                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }
                else {
                    $scope.modal.IsBondWaiverSubmittedProofOfSurety = true;
                }

                if (!($scope.modal.FederalTaxExemptId == null || $scope.modal.FederalTaxExemptId == undefined))
                    $scope.modal.FederalTaxExemptId = $scope.modal.FederalTaxExemptId == 0 ? '' : $scope.modal.FederalTaxExemptId.toString();

                if (!($scope.modal.OSJurisdictionCountyId == null || $scope.modal.OSJurisdictionCountyId == undefined))
                    $scope.modal.OSJurisdictionCountyId = $scope.modal.OSJurisdictionCountyId == 0 ? '' : $scope.modal.OSJurisdictionCountyId.toString();

                if (!($scope.modal.OSJurisdictionStateId == null || $scope.modal.OSJurisdictionStateId == undefined))
                    $scope.modal.OSJurisdictionStateId = $scope.modal.OSJurisdictionStateId == 0 ? '' : $scope.modal.OSJurisdictionStateId.toString();

                if (!($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == undefined))
                    $scope.modal.JurisdictionCountry = $scope.modal.JurisdictionCountry == 0 ? '' : $scope.modal.JurisdictionCountry.toString();

                if (!($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == undefined))
                    $scope.modal.JurisdictionState = $scope.modal.JurisdictionState == 0 ? '' : $scope.modal.JurisdictionState.toString();

            }, function (response) { });

        }
        else {

            //$scope.modal.FederalTaxExemptId = $scope.modal.FederalTaxExemptId.toString();
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.UBINumber = ($scope.modal.UBINumber != null && $scope.modal.UBINumber != undefined && $scope.modal.UBINumber != '') ? $scope.modal.UBINumber.replace(/\s/g, ''): $scope.modal.UBINumber;

            //Assigning 0's to Empty
            $scope.modal.AllContributionsReceived = $scope.modal.AllContributionsReceived == 0 ? null : $scope.modal.AllContributionsReceived;
            $scope.modal.AveragePercentToCharity = $scope.modal.AveragePercentToCharity == 0 ? null : $scope.modal.AveragePercentToCharity;
            $scope.modal.AmountOfFunds = $scope.modal.AmountOfFunds == 0 ? null : $scope.modal.AmountOfFunds;
            $scope.modal.isShowReturnAddress = true;
        }
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    $scope.Review = function () {
        $scope.validateErrorMessage = true;
        //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {
        var isOrgNameValid = $scope.modal.EntityName != null && $scope.modal.EntityName != "" ? true : false;

        var isEntityInfo = ($scope.commercialFundraiserRegistrationForm.entityInfo.$valid);

        $scope.EntityNameCheck = true;

        $scope.modal.NewEntityName = $scope.modal.EntityName;

        if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
            if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                $scope.modal.isBusinessNameChanged = true;
            }
            else {
                $scope.modal.isBusinessNameChanged = false;
            }
        }

        //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);
        var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);

        if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
            $scope.EntityNameCheck = false;
        }
        else {
            $scope.EntityNameCheck = true;
        }

        var isDateValid = ($scope.modal.HasOrganizationCompletedFullAccountingYear ? (new Date($scope.modal.AccountingYearEndingDate) > new Date($scope.modal.AccountingYearBeginningDate) ? true : false) : true);

        var isJurisdictionValid = ($scope.modal.JurisdictionState != NaN && $scope.modal.JurisdictionState != null && $scope.modal.JurisdictionState != undefined && $scope.modal.JurisdictionState != "") ? true: false;

        $scope.checkAccYearVaild = false;
        if ($scope.modal.HasOrganizationCompletedFullAccountingYear) {
            if (typeof ($scope.modal.AccountingYearEndingDate) != typeof (undefined) && $scope.modal.AccountingYearEndingDate != null && $scope.modal.AccountingYearEndingDate != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.checkAccYearVaild = wacorpService.checkAccYearEndDateForReg($scope.modal.AccountingYearEndingDate, true);
            }
        }
        else {
            if (typeof ($scope.modal.FirstAccountingYearEndDate) != typeof (undefined) && $scope.modal.FirstAccountingYearEndDate != null && $scope.modal.FirstAccountingYearEndDate != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.checkAccYearVaild = wacorpService.checkAccYearEndDateForReg($scope.modal.FirstAccountingYearEndDate, false);
            }
        }

        //var isOverrideDocUploaded = ($scope.modal.IsFundraiserOverrideMandetoryReq) ? ($scope.modal.UploadOverrideList.length > 0 ? true : false) : true;

        var isAddressUpload = ($scope.modal.IsUploadAddress) ? ($scope.modal.UploadListOfAddresses.length > 0 ? true : false) : true;

        var isOrgSubmittedSOSProof = ($scope.modal.IsBondWaiverSubmittedProofOfSurety) ? true : ($scope.modal.BondWaiversSOSBondUploadList.length > 0 ? true : false);

        //var isBondWaiver = ($scope.modal.IsBondWaiver) ? ($scope.modal.BondWaiversUploadedSuretyBondsList.length > 0 ? true : false) : true;

        var isCollectedContributions = ($scope.modal.IsOrganizationCollectedContributionsInWA) ? (($scope.modal.ContributionServicesTypeId == null || $scope.modal.ContributionServicesTypeId == undefined || $scope.modal.ContributionServicesTypeId == "") ? false : true) : true;

        var isRegisteredOutside = ($scope.modal.IsRegisteredOutSideOfWashington) ? (($scope.modal.FinancialInfoStateId == null || $scope.modal.FinancialInfoStateId == undefined || $scope.modal.FinancialInfoStateId == "") ? false : true) : true;

        var isOfficerHighPay = ($scope.modal.OfficersHighPayList.length > 0) ? true : false;

        var isExpensesValid = ($scope.modal.HasOrganizationCompletedFullAccountingYear ? ($scope.modal.AllContributionsReceived < $scope.modal.AmountOfFunds ? false : true) : true);

        var isCharitiesFinancialInfo = ($scope.commercialFundraiserRegistrationForm.fundraiserFinancialInfo.$valid);

        var isCftOfficesListValid = ($scope.modal.CFTOfficersList.length > 0);

        var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

        var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.UploadSurityBondList.length > 0 ? true : false) : true);

        var isLegalInfo = $scope.modal.isUpdated ? ($scope.commercialFundraiserRegistrationForm.fundraiserLegalInfo.$valid) : true;

        var isFundraiserListValid = true;
        if ($scope.modal.IsCommercialFundraisersContributionsInWA)
            isFundraiserListValid = $scope.modal.FundraisersList.length > 0;

        var Fein = $scope.modal.FEINNumber;
        var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

        var Ubi = $scope.modal.UBINumber;
        var isValidUbi = true;
        //if (!$scope.modal.IsFundraiserOverrideMandetoryReq) {
        isValidUbi = (Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9) ? true : false;
        //}

        var isSignatureAttestationValidate = ($scope.commercialFundraiserRegistrationForm.SignatureForm.$valid);
        //var isCorrespondenceAddressValid = $scope.commercialFundraiserRegistrationForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.commercialFundraiserRegistrationForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.commercialFundraiserRegistrationForm.cftCorrespondenceAddressForm.$valid;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

        var isFormValidate = isOrgNameValid && isEntityInfo && isAddressUpload && !$scope.checkAccYearVaild && isJurisdictionValid
                                && isOrgSubmittedSOSProof && isCharitiesFinancialInfo && isCftOfficesListValid && isDateValid
                                   && isLegalActionsListValid && isLegalActionsUploadValid && isEntityNameValid &&
                                         isFundraiserListValid && isCollectedContributions && isExpensesValid
                                        && isRegisteredOutside && isOfficerHighPay && isSignatureAttestationValidate && isValidFein && isValidUbi && isLegalInfo && isAdditionalUploadValid && isCorrespondenceAddressValid;

        if (isFormValidate) {
            $scope.fillRegData(); // fillRegData method is available in this controller only.
            $scope.validateErrorMessage = false;
            $scope.isReview = true;
            $location.path('/fundraiserRegistrationReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        //}
        //else {
        //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
        //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
        //        return false;
        //    }
        //}

    };

    $scope.fillRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        //Organization Information
        $scope.modal.EntityName = $scope.modal.EntityName != null && $scope.modal.EntityName != '' ? $scope.modal.EntityName : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        //$scope.modal.UBINumber = $scope.modal.UBINumber.replace(/\s/g, '');
        $scope.modal.RegistrationNumber = $scope.modal.RegistrationNumber || null;
        //$scope.modal.IsEntityRegisteredInWA = false;
        //$scope.modal.IsFundraiserOverrideMandetoryReq = $scope.modal.IsFundraiserOverrideMandetoryReq;
        $scope.modal.IsFundraiserOverrideMandetoryReq = false;
        $scope.modal.HotList = false;
        $scope.modal.AttorneyGeneral = false;
        $scope.modal.AKANamesList = angular.isNullorEmpty($scope.modal.AKANamesList) ? [] : $scope.modal.AKANamesList;
        //$scope.modal.JurisdictionState = "";
        //$scope.modal.JurisdictionStateDesc = "";
        //$scope.modal.UploadOverrideList = angular.isNullorEmpty($scope.modal.UploadOverrideList) ? [] : $scope.modal.UploadOverrideList;
        $scope.modal.UploadOverrideList = [];

        //Contact information
        $scope.modal.EntityEmailAddress = $scope.modal.EntityEmailAddress != null && $scope.modal.EntityEmailAddress != '' ? $scope.modal.EntityEmailAddress : null;
        $scope.modal.EntityConfirmEmailAddress = $scope.modal.EntityConfirmEmailAddress != null && $scope.modal.EntityConfirmEmailAddress != '' ? $scope.modal.EntityConfirmEmailAddress : null;
        $scope.modal.EntityWebsite = $scope.modal.EntityWebsite != null && $scope.modal.EntityWebsite != '' ? $scope.modal.EntityWebsite : null;
        $scope.modal.IsForeignContact = $scope.modal.IsForeignContact;
        $scope.modal.CountryCode = $scope.modal.CountryCode || null;
        $scope.modal.EntityPhoneNumber = $scope.modal.EntityPhoneNumber;
        $scope.modal.PhoneExtension = $scope.modal.PhoneExtension
        $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
        $scope.modal.IsSameasStreetAddr = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
        $scope.modal.IsUploadAddress = $scope.modal.IsUploadAddress;
        $scope.modal.UploadListOfAddresses = angular.isNullorEmpty($scope.modal.UploadListOfAddresses) ? [] : $scope.modal.UploadListOfAddresses;

        //Surety Bond
        $scope.modal.IsBondWaiverSubmittedProofOfSurety = $scope.modal.IsBondWaiverSubmittedProofOfSurety;
        $scope.modal.BondWaiversSOSBondUploadList = angular.isNullorEmpty($scope.modal.BondWaiversSOSBondUploadList) ? [] : $scope.modal.BondWaiversSOSBondUploadList;
        $scope.modal.BondWaiversBondExpirationDate = $scope.modal.BondWaiversBondExpirationDate;
        //$scope.modal.IsBondWaiver = $scope.modal.IsBondWaiver;
        $scope.modal.IsBondWaiver = false;
        //$scope.modal.BondWaiversUploadedSuretyBondsList = angular.isNullorEmpty($scope.modal.BondWaiversUploadedSuretyBondsList) ? [] : $scope.modal.BondWaiversUploadedSuretyBondsList;
        $scope.modal.BondWaiversUploadedSuretyBondsList = [];

        //Financial Information
        $scope.modal.HasOrganizationCompletedFullAccountingYear = $scope.modal.HasOrganizationCompletedFullAccountingYear;
        $scope.modal.AccountingYearBeginningDate = $scope.modal.AccountingYearBeginningDate;
        $scope.modal.AccountingYearEndingDate = $scope.modal.AccountingYearEndingDate;
        $scope.modal.FirstAccountingYearEndDate = $scope.modal.FirstAccountingYearEndDate;
        //$scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets;
        $scope.modal.AllContributionsReceived = $scope.modal.AllContributionsReceived;
        $scope.modal.AveragePercentToCharity = $scope.modal.AveragePercentToCharity;
        //$scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts;
        //$scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets;
        $scope.modal.AmountOfFunds = $scope.modal.AmountOfFunds;
        //$scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures;
        $scope.modal.SolicitationComments = $scope.modal.SolicitationComments;
        //$scope.modal.PercentToProgramServices = $scope.modal.PercentToProgramServices;
        $scope.modal.IsOrganizationCollectedContributionsInWA = $scope.modal.IsOrganizationCollectedContributionsInWA;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0 && angular.isArray($scope.modal.ContributionServicesTypeId)) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }
        $scope.modal.IsRegisteredOutSideOfWashington = $scope.modal.IsRegisteredOutSideOfWashington;
        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0 && angular.isArray($scope.modal.FinancialInfoStateId)) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }
        $scope.modal.OfficersHighPayList = angular.isNullorEmpty($scope.modal.OfficersHighPayList) ? [] : $scope.modal.OfficersHighPayList;
        if ($scope.modal.OfficersHighPayList.length > 0) {
            $scope.modal.OfficersHighPay.IsPayOfficers = true;
        } else {
            $scope.modal.OfficersHighPay.IsPayOfficers = false;
        }

        //Person Accepting Responsibility
        $scope.modal.IsSameAsAddressContactInfo = $scope.modal.IsSameAsAddressContactInfo;
        $scope.modal.CFTOfficersList = angular.isNullorEmpty($scope.modal.CFTOfficersList) ? [] : $scope.modal.CFTOfficersList;

        //Financial Preparer
        $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID;
        $scope.modal.LegalInfo.FirstName = $scope.modal.LegalInfo.FirstName || null;
        $scope.modal.LegalInfo.LastName = $scope.modal.LegalInfo.LastName || null;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName || null;
        $scope.modal.LegalInfo.EntityRepresentativeFirstName = $scope.modal.LegalInfo.EntityRepresentativeFirstName || null;
        $scope.modal.LegalInfo.EntityRepresentativeLastName = $scope.modal.LegalInfo.EntityRepresentativeLastName || null;
        $scope.modal.LegalInfo.Title = $scope.modal.LegalInfo.Title || null;
        $scope.modal.LegalInfo.LegalInfoAddress = $scope.modal.LegalInfo.LegalInfoAddress || null;
        $scope.modal.LegalInfo.IsAnyLegalActions = $scope.modal.LegalInfo.IsAnyLegalActions;

        //Legal Information
        $scope.modal.LegalInfoEntityList = angular.isNullorEmpty($scope.modal.LegalInfoEntityList) ? [] : $scope.modal.LegalInfoEntityList;
        $scope.modal.UploadSurityBondList = angular.isNullorEmpty($scope.modal.UploadSurityBondList) ? [] : $scope.modal.UploadSurityBondList;

        //CFR Sub’s
        $scope.modal.IsCommercialFundraisersContributionsInWA = $scope.modal.IsCommercialFundraisersContributionsInWA;
        $scope.modal.FundraisersList = angular.isNullorEmpty($scope.modal.FundraisersList) ? [] : $scope.modal.FundraisersList;

        //Charity Clients
        $scope.modal.CharitiesList = angular.isNullorEmpty($scope.modal.CharitiesList) ? [] : $scope.modal.CharitiesList;

        //Filing Correspondence
        $scope.modal.CFTAttention = $scope.modal.CFTAttention;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        //ONLINE UPLOAD DOCUMENTS
        $scope.modal.CFTUploadDocumentsList = angular.isNullorEmpty($scope.modal.CFTUploadDocumentsList) ? [] : $scope.modal.CFTUploadDocumentsList;

        //Attestation
        $scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;

        $rootScope.modal = $scope.modal;
    };

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillRegData();
        $scope.modal.OnlineNavigationUrl = "/fundraiserRegistration";
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // FundraiserSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.FundraiserSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }


});


wacorpApp.controller('fundraiserRegistrationReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Commercial Fundraiser Registration Functionality------------- */
    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            $location.path("/fundraiserRegistration");
        }
        else {
            $scope.modal = $rootScope.modal;
            if ($scope.modal.UBINumber != '' && $scope.modal.UBINumber != undefined) {
                $scope.modal.UBINumber = $scope.modal.UBINumber.replace(/(?!^)(?=(?:\d{3})+(?:\.|$))/gm, ' ');
            }
        }
    };

    $scope.FundraiserAddToCart = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber.replace(/\s/g, '');
        if ($scope.modal.ContributionServicesTypeId != null || $scope.modal.ContributionServicesTypeId != undefined) {
            if ($scope.modal.ContributionServicesTypeId.length > 0)
                $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }
        if ($scope.modal.FinancialInfoStateId != null || $scope.modal.FinancialInfoStateId != undefined) {
            if ($scope.modal.FinancialInfoStateId.length > 0)
                $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }

        //$scope.modal.UBIJurisdictionId = $scope.modal.JurisdictionCountry == usaCode ? $scope.modal.JurisdictionState : $scope.modal.JurisdictionCountry;
        //$scope.modal.OrganizationalStructureJurisdictionId = $scope.modal.OrganizationStructureJurisdictionCountryId == usaCode ? $scope.modal.OrganizationalStructureStateJurisdictionId : $scope.modal.OrganizationStructureJurisdictionCountryId;

        $scope.modal.IsOnline = true;

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // FundraiserAddToCart method is availble in constants.js
        wacorpService.post(webservices.CFT.FundraiserAddToCart, $scope.modal, function (response) {
            //$rootScope.commercialStatementofChangeModal = null;
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
            $rootScope.modal = null;
            $location.path('/shoppingcart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/fundraiserRegistration');
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

});

wacorpApp.controller('fundraiserSearchController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    // declare scope variables
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
   
    /* --------Entity Search Functionality------------- */

    $rootScope.fundraiserSearchPath = $routeParams.fundraiserSearchType;
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        $rootScope.FundRaiserID = $scope.selectedBusiness.FundRaiserID;
        if ($rootScope.fundraiserSearchPath == 'Renewal') {
            $location.path('/fundraiserRenewal/' + $scope.selectedBusiness.FundRaiserID);
        }
        if ($rootScope.fundraiserSearchPath == 'Amendment') {
            $location.path('/fundraiserAmendment/' + $scope.selectedBusiness.FundRaiserID);
        }
        if ($rootScope.fundraiserSearchPath == 'Closure') {
            $location.path('/fundraiserClosure/' + $scope.selectedBusiness.FundRaiserID);
        }
    }

});



wacorpApp.controller('fundraiserRenewalController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Entity Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    var originalEntityName = "";

    function getNavigation() {
        if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.Status) >= constant.ZERO) {
            $rootScope.FundRaiserID = $scope.selectedBusiness.FundRaiserID;
            $rootScope.fundraiserRenewalModal = null;
            $rootScope.transactionID = null;
            $location.path('/FundraiserSearch/' + $scope.selectedBusiness.FundRaiserID);
        }
        else {
            // Folder Name: app Folder
            // Alert Name: selectedEntity method is available in alertMessages.js 
            wacorpService.alertDialog(messages.selectedEntity.replace('{0}', $scope.selectedBusiness.Status));
        }
    }


    /* --------Commercial Fundraiser Renewal Functionality------------- */
    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    //// page load
    $scope.Init = function () {
        $scope.messages = messages;
        // here BusinessTypeID = 10 is COMMERCIAL FUNDRAISER
        $rootScope.BusinessTypeID = 10;
        //get business information
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 188 is COMMERCIAL FUNDRAISER RENEWAL
            data = { params: { fundraiserID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 188, transactionID: $rootScope.transactionID } };
        else
            data = { params: { fundraiserID: $routeParams.id, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 188, transactionID: $rootScope.transactionID } };

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/FundraiserSearch');
            }
            // FundraiserRenewalCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.FundraiserRenewalCriteria, data, function (response) {
                $scope.modal = response.data;
                //angular.copy(response.data, $scope.modal);
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                //$scope.modal.BusinessTransaction.BusinessName = $scope.modal.EntityName || null;
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                originalEntityName = $scope.modal.EntityName;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingYearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingYearBeginningDate);
                $scope.modal.AccountingYearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingYearEndingDate);
                $scope.modal.FirstAccountingYearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingYearEndDate);

                $scope.FirstAccountingYearEndDate = new Date();
                $scope.FirstAccountingYearEndDate = $scope.modal.FirstAccountingYearEndDate;
                var accEndDate;

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.BondWaiversBondExpirationDate = wacorpService.dateFormatService($scope.modal.BondWaiversBondExpirationDate);
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);
                //$scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets || null;
                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.HasOrganizationCompletedFullAccountingYear) {
                        if ($scope.modal.AccountingYearEndingDate != "01/01/0001") {
                            accEndDate = new Date($scope.modal.AccountingYearEndingDate);
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            accEndDate = wacorpService.dateFormatService(accEndDate.setDate(accEndDate.getDate() + 1));
                            $scope.modal.AccountingYearBeginningDate = accEndDate;
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)S
                            $scope.modal.FirstAccountingYearEndDate = wacorpService.dateFormatService($scope.calculateEndDate(accEndDate));
                        }
                        else
                            $scope.modal.IsRenewalMinDates = true;
                    }
                    else {
                        if ($scope.modal.FirstAccountingYearEndDate && $scope.modal.FirstAccountingYearEndDate != "01/01/0001") {

                            var _enddate = new Date($scope.modal.FirstAccountingYearEndDate);
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            $scope.modal.AccountingYearBeginningDate = wacorpService.dateFormatService($scope.calculateAccountingYearBgnDate(_enddate));

                            // accEndDate = new Date($scope.modal.FirstAccountingYearEndDate);
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            $scope.modal.FirstAccountingYearEndDate = wacorpService.dateFormatService($scope.calculateEndDate($scope.modal.AccountingYearBeginningDate));
                            //var beginDate = new Date($scope.FirstAccountingYearEndDate);
                            //beginDate = wacorpService.dateFormatService(beginDate.setDate(beginDate.getDate() + 1));
                            //$scope.modal.AccountingYearBeginningDate = beginDate;
                            $scope.modal.BeginingGrossAssets = $scope.modal.EndingGrossAssets != null ? $scope.modal.EndingGrossAssets : null;
                        }
                        else {
                            $scope.modal.IsRenewalMinDates = true;
                        }
                        $scope.modal.HasOrganizationCompletedFullAccountingYear = true;
                    }
                    if ($scope.modal.AccountingYearBeginningDate != "01/01/0001") //added on 9/13/2017
                    {
                        $scope.modal.AllContributionsReceived = null;
                        $scope.modal.AveragePercentToCharity = null;
                        ////$scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts || null;
                        $scope.modal.AmountOfFunds = null;
                        //$scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures || null;
                        //$scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets || null;
                    }
                }

                $scope.modal.ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.ContributionServicesTypeId) ? [] : $scope.modal.ContributionServicesTypeId.split(',');
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');

                $scope.modal.CharityAkaInfoEntity.CountiesServedId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CountiesServedId) ? [] : $scope.modal.CharityAkaInfoEntity.CountiesServedId.split(',');
                $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId) ? [] : $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.split(',');
                //$scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
                //$scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.County = $scope.modal.EntityStreetAddress.County != null ? $scope.modal.EntityStreetAddress.County : "";
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country != null ? $scope.modal.LegalInfo.LegalInfoAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';
                $scope.modal.AKASolicitNameId = '';
                if ($scope.modal.IsActiveFilingExist) {
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }
                if ($scope.modal.HasOrganizationCompletedFullAccountingYear)
                    $scope.modal.oldFiscalYear = $scope.modal.AccountingYearBeginningDate != '01/01/0001' || $scope.modal.AccountingYearBeginningDate != null ? $scope.modal.AccountingYearBeginningDate : null;
                else
                    $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingYearEndDate != '01/01/0001' || $scope.modal.FirstAccountingYearEndDate != null ? $scope.modal.FirstAccountingYearEndDate : null;

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }
                //$scope.modal.IsOrgNameExists = $scope.modal.EntityName != null && $scope.modal.FEINNumber != "" && $scope.modal.FEINNumber != null || $scope.modal.UBINumber != null && $scope.modal.UBINumber != "" && $scope.modal.EntityName != "" ? true : false;

                $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;

                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;

                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if ($scope.modal.UploadOverrideList.length > 0) {
                    angular.forEach($scope.modal.UploadOverrideList, function (ovrdData) {
                        ovrdData.SequenceNo = ovrdData.ID;
                    });
                }

                if ($scope.modal.OfficersHighPayList.length > 0) {
                    angular.forEach($scope.modal.OfficersHighPayList, function (cftHihPay) {
                        cftHihPay.SequenceNo = cftHihPay.ID;
                    });
                }

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.CFTOfficersList.length > 0) {
                        angular.forEach($scope.modal.CFTOfficersList, function (cftOffice) {
                            cftOffice.SequenceNo = cftOffice.OfficerID;
                        });
                    }
                }


                if ($scope.modal.LegalInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.LegalInfoEntityList, function (cftLegalInfo) {
                        cftLegalInfo.SequenceNo = cftLegalInfo.LegalInfoId;
                    });
                }


                if ($scope.modal.CFTFinancialHistoryList.length > 0) {
                    angular.forEach($scope.modal.CFTFinancialHistoryList, function (fundraiser) {
                        fundraiser.SequenceNo = fundraiser.FinancialId;
                    });
                }

                if ($scope.modal.AKANamesList.length > 0) {
                    angular.forEach($scope.modal.AKANamesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }

                if ($scope.modal.CharitiesList.length > 0) {
                    angular.forEach($scope.modal.CharitiesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }
                $scope.modal.isShowReturnAddress = true;
                $scope.checkHighpayCount(); // checkHighpayCount method is avilable in this controller only.
                $scope.ValidateRenewalDate(); // ValidateRenewalDate method is avilable in this controller only.
            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
            $scope.checkHighpayCount(); // checkHighpayCount method is avilable in this controller only.
            //Assigning 0's to Empty
            $scope.modal.AllContributionsReceived = $scope.modal.AllContributionsReceived == 0 ? null : $scope.modal.AllContributionsReceived;
            $scope.modal.AveragePercentToCharity = $scope.modal.AveragePercentToCharity == 0 ? null : $scope.modal.AveragePercentToCharity;
            $scope.modal.AmountOfFunds = $scope.modal.AmountOfFunds == 0 ? null : $scope.modal.AmountOfFunds;
            $scope.modal.isShowReturnAddress = true;
        }
    };

    $scope.checkHighpayCount = function () {
        var count = 0;
        angular.forEach($scope.modal.OfficersHighPayList, function (highpayItem) {
            if (highpayItem.Status != "D") {
                count++;
            }
        });

        if (count >= 3) {
            $scope.modal.OfficersHighPay.IsCountMax = true;
        }
        else {
            $scope.modal.OfficersHighPay.IsCountMax = false;
        }
        return count <= 0;
    };

    $scope.ValidateRenewalDate = function () {
        var result = $scope.modal.ErrorMsg == null || $scope.modal.ErrorMsg == "" ? true : false;
        if (!result) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.modal.ErrorMsg);
            return false;
        }
        return true;
    };

    $scope.FundraiserValidateEndDate = function () {
        return (new Date($scope.modal.AccountingYearEndingDate) < new Date($scope.modal.AccountingYearBeginningDate));
    };

    $scope.Review = function (FundraiserRenewalForm) {
        // ValidateRenewalDate method is available in this controller only.
        if ($scope.ValidateRenewalDate()) {

            var endDate = $scope.modal.AccountingYearEndingDate;
            if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                if (isEndDateMore) {
                    // Folder Name: app Folder
                    // Alert Name: InvalidFilingMsg method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                    return false;
                }
            }

            $scope.validateErrorMessage = true;
            //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {

            var isOrgNameValid = $scope.modal.EntityName != null && $scope.modal.EntityName != "" ? true : false;

            var isEntityInfo = ($scope.commercialFundraiserRenewalForm.entityInfo.$valid);

            //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);
            $scope.modal.NewEntityName = $scope.modal.EntityName;

            if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
                if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                    $scope.modal.isBusinessNameChanged = true;
                }
                else {
                    $scope.modal.isBusinessNameChanged = false;
                }
            }

            //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase(originalEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));
            var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

            if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
                $scope.EntityNameCheck = false;
            }
            else {
                $scope.EntityNameCheck = true;
            }

            var isJurisdictionValid = ($scope.modal.JurisdictionState != NaN && $scope.modal.JurisdictionState != null && $scope.modal.JurisdictionState != undefined && $scope.modal.JurisdictionState != "") ? true: false;

            //var isOverrideDocUploaded = ($scope.modal.IsFundraiserOverrideMandetoryReq) ? ($scope.modal.UploadOverrideList.length > 0 ? true : false) : true;

            var isAddressUpload = ($scope.modal.IsUploadAddress) ? ($scope.modal.UploadListOfAddresses.length > 0 ? true : false) : true;

            var isOrgSubmittedSOSProof = ($scope.modal.IsBondWaiverSubmittedProofOfSurety) ? true : ($scope.modal.BondWaiversSOSBondUploadList.length > 0 ? true : false);

            //var isBondWaiver = ($scope.modal.IsBondWaiver) ? ($scope.modal.BondWaiversUploadedSuretyBondsList.length > 0 ? true : false) : true;

            var isCollectedContributions = ($scope.modal.IsOrganizationCollectedContributionsInWA) ? (($scope.modal.ContributionServicesTypeId == null || $scope.modal.ContributionServicesTypeId == undefined || $scope.modal.ContributionServicesTypeId == "") ? false : true) : true;

            var isRegisteredOutside = ($scope.modal.IsRegisteredOutSideOfWashington) ? (($scope.modal.FinancialInfoStateId == null || $scope.modal.FinancialInfoStateId == undefined || $scope.modal.FinancialInfoStateId == "") ? false : true) : true;

            var isOfficerHighPay = ($scope.modal.OfficersHighPayList.length > 0) ? true : false;

            var isExpensesValid = ($scope.modal.HasOrganizationCompletedFullAccountingYear ? ($scope.modal.AllContributionsReceived < $scope.modal.AmountOfFunds ? false : true) : true);

            var isCharitiesFinancialInfo = ($scope.commercialFundraiserRenewalForm.fundraiserFinancialInfo.$valid);

            var isCftOfficesListValid = ($scope.checkOfficersCount() > 0);

            var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

            var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.UploadSurityBondList.length > 0 ? true : false) : true);

            var isLegalInfo = ($scope.commercialFundraiserRenewalForm.fundraiserLegalInfo.$valid);

            var isFundraiserListValid = true;
            if ($scope.modal.IsCommercialFundraisersContributionsInWA)
                isFundraiserListValid = $scope.modal.FundraisersList.length > 0;

            var Fein = $scope.modal.FEINNumber;
            var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

            var Ubi = $scope.modal.UBINumber;
            var isValidUbi = true;
            //if (!$scope.modal.IsFundraiserOverrideMandetoryReq) {
            isValidUbi = $scope.modal.IsFundraiserOverrideMandetoryReq ? true : ((Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9) ? true : false);
            //}

            var isSignatureAttestationValidate = ($scope.commercialFundraiserRenewalForm.SignatureForm.$valid);
            //var isCorrespondenceAddressValid = $scope.commercialFundraiserRenewalForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.commercialFundraiserRenewalForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
            var isCorrespondenceAddressValid = $scope.commercialFundraiserRenewalForm.cftCorrespondenceAddressForm.$valid;

            //Upload Additional Documents
            var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

            var isFormValidate = isOrgNameValid && isEntityInfo && isAddressUpload && isJurisdictionValid
                                    && isOrgSubmittedSOSProof && isCharitiesFinancialInfo && isCftOfficesListValid
                                       && isLegalActionsListValid && isLegalActionsUploadValid && isEntityNameValid &&
                                             isFundraiserListValid && isCollectedContributions && isExpensesValid
                                            && isRegisteredOutside && isOfficerHighPay && isSignatureAttestationValidate && isValidFein && isValidUbi && isLegalInfo && isAdditionalUploadValid && isCorrespondenceAddressValid;
            $scope.fillRegData();

            if (isFormValidate) {
                $scope.validateErrorMessage = false;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
                $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
                $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

                $rootScope.modal = $scope.modal;
                $location.path('/fundraiserRenewalReview');
            }
            else
                // Folder Name: app Folder
                // Alert Name: InvalidFilingMsg method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
            //}
            //else {
            //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
            //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
            //        return false;
            //    }
            //}
        }
    };

    $scope.checkOfficersCount = function () {
        var count = 0;
        angular.forEach($scope.modal.CFTOfficersList, function (value) {
            if (value.OfficerStatus != 'D')
                count++;
        });

        if (count == 0 || count == undefined)
            return $scope.modal.CFTOfficersList.length = 0;
        else
            return $scope.modal.CFTOfficersList.length;
    };

    $scope.fillRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.FinancialId = $scope.modal.FinancialId || null;

        //if ($scope.modal.HasOrganizationCompletedFullAccountingYear)
        //    $scope.modal.oldFiscalYear = $scope.modal.AccountingYearBeginningDate != '01/01/0001' || $scope.modal.AccountingYearBeginningDate != null ? $scope.modal.AccountingYearBeginningDate : null;
        //else
        //    $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingYearEndDate != '01/01/0001' || $scope.modal.FirstAccountingYearEndDate != null ? $scope.modal.FirstAccountingYearEndDate : null;

        //Organization Information
        $scope.modal.EntityName = $scope.modal.EntityName != null && $scope.modal.EntityName != '' ? $scope.modal.EntityName : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        //$scope.modal.UBINumber = $scope.modal.UBINumber.replace(/\s/g, '');
        $scope.modal.RegistrationNumber = $scope.modal.RegistrationNumber || null;
        //$scope.modal.IsEntityRegisteredInWA = false;
        $scope.modal.IsFundraiserOverrideMandetoryReq = $scope.modal.IsFundraiserOverrideMandetoryReq;
        //$scope.modal.IsFundraiserOverrideMandetoryReq = false;
        $scope.modal.HotList = false;
        $scope.modal.AttorneyGeneral = false;
        $scope.modal.AKANamesList = angular.isNullorEmpty($scope.modal.AKANamesList) ? [] : $scope.modal.AKANamesList;
        //$scope.modal.JurisdictionState = "";
        //$scope.modal.JurisdictionStateDesc = "";
        //$scope.modal.UploadOverrideList = angular.isNullorEmpty($scope.modal.UploadOverrideList) ? [] : $scope.modal.UploadOverrideList;
        //$scope.modal.UploadOverrideList = [];

        //Contact information
        $scope.modal.EntityEmailAddress = $scope.modal.EntityEmailAddress != null && $scope.modal.EntityEmailAddress != '' ? $scope.modal.EntityEmailAddress : null;
        $scope.modal.EntityConfirmEmailAddress = $scope.modal.EntityConfirmEmailAddress != null && $scope.modal.EntityConfirmEmailAddress != '' ? $scope.modal.EntityConfirmEmailAddress : null;
        $scope.modal.EntityWebsite = $scope.modal.EntityWebsite != null && $scope.modal.EntityWebsite != '' ? $scope.modal.EntityWebsite : null;
        $scope.modal.IsForeignContact = $scope.modal.IsForeignContact;
        $scope.modal.CountryCode = $scope.modal.CountryCode || null;
        $scope.modal.EntityPhoneNumber = $scope.modal.EntityPhoneNumber;
        $scope.modal.PhoneExtension = $scope.modal.PhoneExtension
        $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
        $scope.modal.IsSameasStreetAddr = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
        $scope.modal.IsUploadAddress = $scope.modal.IsUploadAddress;
        //$scope.modal.UploadListOfAddresses = angular.isNullorEmpty($scope.modal.UploadListOfAddresses) ? [] : $scope.modal.UploadListOfAddresses;

        //Surety Bond
        $scope.modal.IsBondWaiverSubmittedProofOfSurety = $scope.modal.IsBondWaiverSubmittedProofOfSurety;
        $scope.modal.BondWaiversSOSBondUploadList = angular.isNullorEmpty($scope.modal.BondWaiversSOSBondUploadList) ? [] : $scope.modal.BondWaiversSOSBondUploadList;
        $scope.modal.BondWaiversBondExpirationDate = $scope.modal.BondWaiversBondExpirationDate;
        $scope.modal.IsBondWaiver = $scope.modal.IsBondWaiver;
        //$scope.modal.IsBondWaiver = false;
        //$scope.modal.BondWaiversUploadedSuretyBondsList = angular.isNullorEmpty($scope.modal.BondWaiversUploadedSuretyBondsList) ? [] : $scope.modal.BondWaiversUploadedSuretyBondsList;
        //$scope.modal.BondWaiversUploadedSuretyBondsList = [];

        //Financial Information
        $scope.modal.HasOrganizationCompletedFullAccountingYear = $scope.modal.HasOrganizationCompletedFullAccountingYear;
        $scope.modal.AccountingYearBeginningDate = $scope.modal.AccountingYearBeginningDate;
        $scope.modal.AccountingYearEndingDate = $scope.modal.AccountingYearEndingDate;
        $scope.modal.FirstAccountingYearEndDate = $scope.modal.FirstAccountingYearEndDate;
        //$scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets;
        $scope.modal.AllContributionsReceived = $scope.modal.AllContributionsReceived;
        $scope.modal.AveragePercentToCharity = $scope.modal.AveragePercentToCharity;
        //$scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts;
        //$scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets;
        $scope.modal.AmountOfFunds = $scope.modal.AmountOfFunds;
        //$scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures;
        $scope.modal.SolicitationComments = $scope.modal.SolicitationComments;
        //$scope.modal.PercentToProgramServices = $scope.modal.PercentToProgramServices;
        $scope.modal.IsOrganizationCollectedContributionsInWA = $scope.modal.IsOrganizationCollectedContributionsInWA;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0 && angular.isArray($scope.modal.ContributionServicesTypeId)) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }
        $scope.modal.IsRegisteredOutSideOfWashington = $scope.modal.IsRegisteredOutSideOfWashington;
        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0 && angular.isArray($scope.modal.FinancialInfoStateId)) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }
        //$scope.modal.OfficersHighPayList = angular.isNullorEmpty($scope.modal.OfficersHighPayList) ? [] : $scope.modal.OfficersHighPayList;
        if ($scope.modal.OfficersHighPayList.length > 0) {
            $scope.modal.OfficersHighPay.IsPayOfficers = true;
        } else {
            $scope.modal.OfficersHighPay.IsPayOfficers = false;
        }

        //Person Accepting Responsibility
        $scope.modal.IsSameAsAddressContactInfo = $scope.modal.IsSameAsAddressContactInfo;
        //$scope.modal.CFTOfficersList = angular.isNullorEmpty($scope.modal.CFTOfficersList) ? [] : $scope.modal.CFTOfficersList;

        //Financial Preparer
        $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID;
        $scope.modal.LegalInfo.FirstName = $scope.modal.LegalInfo.FirstName || null;
        $scope.modal.LegalInfo.LastName = $scope.modal.LegalInfo.LastName || null;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName || null;
        $scope.modal.LegalInfo.EntityRepresentativeFirstName = $scope.modal.LegalInfo.EntityRepresentativeFirstName || null;
        $scope.modal.LegalInfo.EntityRepresentativeLastName = $scope.modal.LegalInfo.EntityRepresentativeLastName || null;
        $scope.modal.LegalInfo.Title = $scope.modal.LegalInfo.Title || null;
        $scope.modal.LegalInfo.LegalInfoAddress = $scope.modal.LegalInfo.LegalInfoAddress || null;
        $scope.modal.LegalInfo.IsAnyLegalActions = $scope.modal.LegalInfo.IsAnyLegalActions;

        //Legal Information
        //$scope.modal.LegalInfoEntityList = angular.isNullorEmpty($scope.modal.LegalInfoEntityList) ? [] : $scope.modal.LegalInfoEntityList;
        //$scope.modal.UploadSurityBondList = angular.isNullorEmpty($scope.modal.UploadSurityBondList) ? [] : $scope.modal.UploadSurityBondList;

        //CFR Sub’s
        $scope.modal.IsCommercialFundraisersContributionsInWA = $scope.modal.IsCommercialFundraisersContributionsInWA;
        //$scope.modal.FundraisersList = angular.isNullorEmpty($scope.modal.FundraisersList) ? [] : $scope.modal.FundraisersList;

        //Charity Clients
        //$scope.modal.CharitiesList = angular.isNullorEmpty($scope.modal.CharitiesList) ? [] : $scope.modal.CharitiesList;

        //Filing Correspondence
        $scope.modal.CFTAttention = $scope.modal.CFTAttention;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        //ONLINE UPLOAD DOCUMENTS
        //$scope.modal.CFTUploadDocumentsList = angular.isNullorEmpty($scope.modal.CFTUploadDocumentsList) ? [] : $scope.modal.CFTUploadDocumentsList;

        //Attestation
        $scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;

        $rootScope.modal = $scope.modal;
    };

    $scope.calculateAccountingYearBgnDate = function (value) {
        if (value != null && value != undefined) {
            var accEndDate = new Date(value)
            accEndDate = new Date(accEndDate.setMonth(accEndDate.getMonth() - 11))
            accEndDate = new Date(accEndDate.getFullYear(), accEndDate.getMonth(), 1)
            return accEndDate;
        }
    }


    //$scope.SaveClose = function () {
    //    $scope.modal.isBusinessNameAvailable = false;
    //    $scope.fillRegData();
    //    $scope.modal.OnlineNavigationUrl = "/fundraiserRenewal";
        
    //    //TFS 1143 submitting filing means you have said agent consents
    //    if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
    //        $scope.modal.Agent.IsRegisteredAgentConsent =
    //            true;
    //    }
    //    if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
    //        $scope.modal.IsRegisteredAgentConsent = true; 
    //    }
    //    //TFS 1143

    //    // FundraiserSaveandClose method is available in constants.js
    //    wacorpService.post(webservices.CFT.FundraiserSaveandClose, $scope.modal, function (response) {
    //        $rootScope.BusinessType = null;
    //        $rootScope.modal = null;
    //        $location.path('/Dashboard');
    //    }, function (response) {
    //        // Service Folder: services
    //        // File Name: wacorpService.js (you can search with file name in solution explorer)
    //        wacorpService.alertDialog(response.data);
    //    });
    //};

    $scope.calculateEndDate = function (value) {
        if (value != null && value != undefined) {
            var endDate = new Date(value);
            endDate.setYear(endDate.getFullYear() + 1);
            var firstDay = new Date(endDate.getFullYear(), endDate.getMonth(), 1);
            var lastDay = new Date(endDate.getFullYear(), endDate.getMonth(), 0);
            var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
            return lastDayWithSlashes;
        }
    }

    //TFS 1159 Old Code
    $scope.calculateAccountingYearBgnDate = function (value) {
        if (value != null && value != undefined) {
            var accEndDate = new Date(value)
            accEndDate = new Date(accEndDate.setMonth(accEndDate.getMonth() - 11))
            accEndDate = new Date(accEndDate.getFullYear(), accEndDate.getMonth(), 1)
            return accEndDate;
        }
    }
    //TFS 1159 Old Code

    //TFS 1159 Updated Code
    //$scope.calculateAccountingYearBgnDate = function (value) {
    //    if (value != null && value != undefined) {
    //        var accEndDate = new Date(value);
    //        //TFS 1159 Updated Logic
    //        //Note: months are 0-11
    //        //if (accEndDate.getMonth() < 11) {  //month 0-10 (not december)
    //        //    var getStartMonth = accEndDate.getMonth() + 1;  //get next month
    //        //    var getStartYear = accEndDate.getFullYear() - 1;  //get previous year
    //        //} else {  //month 11 = 1/1/YYYY to 12/31/YYYY
    //        //    var getStartMonth = 0; //get month 0 (January)
    //        //    var getStartYear = accEndDate.getFullYear();  //no year change
    //        //}
            
            
    //        //accEndDate = new Date(getStartYear, getStartMonth);
    //        //return accEndDate;
    //        
    //    }
    //}
    //TFS 1159 Updated Logic
});
wacorpApp.controller('fundraiserRenewalReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Commercial Fundraiser Renewal Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            $location.path("/fundraiserRegistration");
        }
        else {
            $scope.modal = $rootScope.modal;
            if ($scope.modal.UBINumber != '' && $scope.modal.UBINumber != undefined) {
                $scope.modal.UBINumber = $scope.modal.UBINumber.replace(/(?!^)(?=(?:\d{3})+(?:\.|$))/gm, ' ');
            }
        }
        $scope.usaCode = usaCode;
    };


    $scope.FundraiserRenewalAddToCart = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = ($scope.modal.UBINumber != null && $scope.modal.UBINumber != '') ? $scope.modal.UBINumber.replace(/\s/g, '') : null;

        $scope.modal.IsOnline = true;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0 && angular.isArray($scope.modal.ContributionServicesTypeId)) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }
       
        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0 && angular.isArray($scope.modal.FinancialInfoStateId)) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }
        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // FundraiserAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.FundraiserAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
            $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/fundraiserRenewal/' + $scope.modal.FundRaiserID);
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

});

wacorpApp.controller('fundraiserAmendmentController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Entity Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    var originalEntityName = "";
    var isShortFiscalYearChecked = false;

    var getShortYearStartDate = function () {
        if ($scope.modal.CurrentEndDateForAmendment != null && typeof ($scope.modal.CurrentEndDateForAmendment) != typeof (undefined)) {
            $scope.modal.shortFiscalYearEntity.FiscalStartDate = "";
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            var startDate = wacorpService.getShortYearStartDate($scope.modal.CurrentEndDateForAmendment);
            $scope.modal.shortFiscalYearEntity.FiscalStartDate = wacorpService.dateFormatService(startDate);

            return $scope.modal.shortFiscalYearEntity.FiscalStartDate;
        }
    };

    var getShortYearEndDate = function () {
        if ($scope.modal.AccountingYearBeginningDate != null && typeof ($scope.modal.AccountingYearBeginningDate) != typeof (undefined)) {
            $scope.modal.shortFiscalYearEntity.FiscalEndDate = "";
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            var endDate = wacorpService.getShortYearEndDate($scope.modal.AccountingYearBeginningDate);
            $scope.modal.shortFiscalYearEntity.FiscalEndDate = wacorpService.dateFormatService(endDate);

            return $scope.modal.shortFiscalYearEntity.FiscalEndDate;
        }
    };

    function getNavigation() {
        if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.Status) >= constant.ZERO) {
            $rootScope.FundRaiserID = $scope.selectedBusiness.FundRaiserID;
            $rootScope.fundraiserAmendmentModal = null;
            $rootScope.transactionID = null;
            $location.path('/FundraiserSearch/' + $scope.selectedBusiness.FundRaiserID);
        }
        else {
            // Folder Name: app Folder
            // Alert Name: selectedEntity method is available in alertMessages.js 
            wacorpService.alertDialog(messages.selectedEntity.replace('{0}', $scope.selectedBusiness.Status));
        }
    }


    /* --------Commercial Fundraiser Amendment Functionality------------- */
    // scope variables
    $scope.modal = {
        SignatureAttestation: {},
        CFTFinancialHistoryList: []
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    //// page load
    $scope.Init = function () {
        $scope.messages = messages;
        // here BusinessTypeID = 10 is COMMERCIAL FUNDRAISER
        $rootScope.BusinessTypeID = 10;
        //get business information
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 185 is COMMERCIAL FUNDRAISER AMENDMENT
            data = { params: { fundraiserID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 185, transactionID: $rootScope.transactionID } };
        else
            data = { params: { fundraiserID: $routeParams.id, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 185, transactionID: $rootScope.transactionID } };

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/FundraiserSearch');
            }
            // FundraiserAmendmentCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.FundraiserAmendmentCriteria, data, function (response) {
                angular.copy(response.data, $scope.modal);
                //$scope.modal = response.data;

                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                //$scope.modal.BusinessTransaction.BusinessName = $scope.modal.EntityName || null;
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                originalEntityName = $scope.modal.EntityName;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;

                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingYearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingYearBeginningDate);
                $scope.modal.AccountingYearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingYearEndingDate);
                $scope.modal.FirstAccountingYearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingYearEndDate);
                $scope.modal.BondWaiversBondExpirationDate = wacorpService.dateFormatService($scope.modal.BondWaiversBondExpirationDate);
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                if ($scope.modal.IsActiveFilingExist) {
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js 
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.HasOrganizationCompletedFullAccountingYear) {
                        $scope.modal.CurrentStartDateForAmendment = ($scope.modal.AccountingYearBeginningDate != '01/01/0001' || $scope.modal.AccountingYearBeginningDate != null) ? $scope.modal.AccountingYearBeginningDate : null;
                        $scope.modal.CurrentEndDateForAmendment = ($scope.modal.AccountingYearEndingDate != '01/01/0001' || $scope.modal.AccountingYearEndingDate != null) ? $scope.modal.AccountingYearEndingDate : null;
                        $scope.modal.shortFiscalYearEntity.PreviousFiscalStartDate = $scope.modal.AccountingYearBeginningDate;
                        $scope.modal.shortFiscalYearEntity.PreviousFiscalEndDate = $scope.modal.AccountingYearEndingDate;
                    }
                    else {
                        $scope.modal.CurrentEndDateForAmendment = ($scope.modal.FirstAccountingYearEndDate != '01/01/0001' || $scope.modal.FirstAccountingYearEndDate != null) ? $scope.modal.FirstAccountingYearEndDate : null;
                        $scope.modal.shortFiscalYearEntity.PreviousFiscalEndDate = $scope.modal.FirstAccountingYearEndDate;
                    }
                }

                $scope.modal.ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.ContributionServicesTypeId) ? [] : $scope.modal.ContributionServicesTypeId.split(',');
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');

                $scope.modal.CharityAkaInfoEntity.CountiesServedId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CountiesServedId) ? [] : $scope.modal.CharityAkaInfoEntity.CountiesServedId.split(',');
                $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId) ? [] : $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.split(',');
                //$scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
                //$scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.County = $scope.modal.EntityStreetAddress.County != null ? $scope.modal.EntityStreetAddress.County : "";
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country != null ? $scope.modal.LegalInfo.LegalInfoAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';
                $scope.modal.AKASolicitNameId = '';
                //$scope.modal.isUpdated = $scope.modal.HasOrganizationCompletedFullAccountingYear == true ? true : false;

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.HasOrganizationCompletedFullAccountingYear)
                        $scope.modal.oldFiscalYear = $scope.modal.AccountingYearBeginningDate != '01/01/0001' || $scope.modal.AccountingYearBeginningDate != null ? $scope.modal.AccountingYearBeginningDate : null;
                    else
                        $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingYearEndDate != '01/01/0001' || $scope.modal.FirstAccountingYearEndDate != null ? $scope.modal.FirstAccountingYearEndDate : null;
                }
                //Empty the Previous Financials
                if (!$rootScope.IsShoppingCart) {
                    $scope.modal.HasOrganizationCompletedFullAccountingYear = false;
                    $scope.modal.isUpdated = false;
                    $scope.modal.AccountingYearBeginningDate = null;
                    $scope.modal.AccountingYearEndingDate = null;
                    //$scope.modal.FirstAccountingYearEndDate = null;
                    $scope.modal.AllContributionsReceived = null;
                    $scope.modal.AveragePercentToCharity = null;
                    $scope.modal.AmountOfFunds = null;
                    $scope.modal.shortFiscalYearEntity.AllContributionsReceivedForShortFY = null;
                    $scope.modal.shortFiscalYearEntity.AveragePercentToCharityForShortFY = null;
                    $scope.modal.shortFiscalYearEntity.AmountOfFundsForShortFY = null;
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }
                //$scope.modal.IsOrgNameExists = $scope.modal.EntityName != null && $scope.modal.FEINNumber != "" && $scope.modal.FEINNumber != null || $scope.modal.UBINumber != null && $scope.modal.UBINumber != "" && $scope.modal.EntityName != "" ? true : false;

                $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;

                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;

                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if ($scope.modal.UploadOverrideList.length > 0) {
                    angular.forEach($scope.modal.UploadOverrideList, function (ovrdData) {
                        ovrdData.SequenceNo = ovrdData.ID;
                    });
                }

                if ($scope.modal.OfficersHighPayList.length > 0) {
                    angular.forEach($scope.modal.OfficersHighPayList, function (cftHihPay) {
                        cftHihPay.SequenceNo = cftHihPay.ID;
                    });
                }

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.CFTOfficersList.length > 0) {
                        angular.forEach($scope.modal.CFTOfficersList, function (cftOffice) {
                            cftOffice.SequenceNo = cftOffice.OfficerID;
                        });
                    }
                }



                if ($scope.modal.LegalInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.LegalInfoEntityList, function (cftLegalInfo) {
                        cftLegalInfo.SequenceNo = cftLegalInfo.LegalInfoId;
                    });
                }

                //if (!$rootScope.IsShoppingCart) {
                //    if ($scope.modal.CFTFinancialHistoryList.length > 0) {
                //        $scope.modal.CFTFinancialHistoryList.splice(0, 1);
                //    }
                //}

                if ($scope.modal.CFTFinancialHistoryList.length > 0) {
                    angular.forEach($scope.modal.CFTFinancialHistoryList, function (fundraiser) {
                        fundraiser.SequenceNo = fundraiser.FinancialId;
                    });
                }

                if ($scope.modal.AKANamesList.length > 0) {
                    angular.forEach($scope.modal.AKANamesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }

                if ($scope.modal.CharitiesList.length > 0) {
                    angular.forEach($scope.modal.CharitiesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }
                $scope.modal.isShowReturnAddress = true;
                $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.
            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;

            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.UBINumber = ($scope.modal.UBINumber != null && $scope.modal.UBINumber != '') ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
            $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.
            //Assigning 0's to Empty
            $scope.modal.AllContributionsReceived = $scope.modal.AllContributionsReceived == 0 ? null : $scope.modal.AllContributionsReceived;
            $scope.modal.AveragePercentToCharity = $scope.modal.AveragePercentToCharity == 0 ? null : $scope.modal.AveragePercentToCharity;
            $scope.modal.AmountOfFunds = $scope.modal.AmountOfFunds == 0 ? null : $scope.modal.AmountOfFunds;
            $scope.modal.shortFiscalYearEntity.AllContributionsReceivedForShortFY = $scope.modal.shortFiscalYearEntity.AllContributionsReceivedForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.AllContributionsReceivedForShortFY;
            $scope.modal.shortFiscalYearEntity.AveragePercentToCharityForShortFY = $scope.modal.shortFiscalYearEntity.AveragePercentToCharityForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.AveragePercentToCharityForShortFY;
            $scope.modal.shortFiscalYearEntity.AmountOfFundsForShortFY = $scope.modal.shortFiscalYearEntity.AmountOfFundsForShortFY == 0 ? null : $scope.modal.shortFiscalYearEntity.AmountOfFundsForShortFY;
            $scope.modal.isShowReturnAddress = true;
        }
    };

    $scope.checkHighpayCount = function () {
        var count = 0;
        angular.forEach($scope.modal.OfficersHighPayList, function (highpayItem) {
            if (highpayItem.Status != "D") {
                count++;
            }
        });

        if (count >= 3) {
            $scope.modal.OfficersHighPay.IsCountMax = true;
        }
        else {
            $scope.modal.OfficersHighPay.IsCountMax = false;
        }
        return count <= 0;
    };

    $scope.FundraiserValidateEndDate = function () {
        return (new Date($scope.modal.AccountingYearEndingDate) < new Date($scope.modal.AccountingYearBeginningDate));
    };

    $scope.Review = function (FundraiserAmendmentForm) {
        $scope.validateErrorMessage = true;

        if (typeof ($scope.modal.CFTFinancialHistoryList) != typeof (undefined) && $scope.modal.CFTFinancialHistoryList.length == 0) {
            var endDate = $scope.modal.AccountingYearEndingDate;
            if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                if (isEndDateMore) {
                    wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                    return false;
                }
            }
        }

        var endFiscalDate = $scope.modal.shortFiscalYearEntity.FiscalEndDate;
        if (typeof (endFiscalDate) != typeof (undefined) && endFiscalDate != null && endFiscalDate != "" && $scope.modal.CFTFinancialHistoryList.length > 0) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            var isEndDateMore = wacorpService.isEndDateMoreThanToday(endFiscalDate);
            if (isEndDateMore) {
                // Folder Name: app Folder
                // Alert Name: shortYearEndDateNotGreaterThanTodayDate method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.CharitiesFinancial.shortYearEndDateNotGreaterThanTodayDate);
                return false;
            }
        }

        //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {
        var isOrgNameValid = $scope.modal.EntityName != null && $scope.modal.EntityName != "" ? true : false;

        var isEntityInfo = ($scope.commercialFundraiserAmendmentForm.entityInfo.$valid);

        $scope.EntityNameCheck = true;

        $scope.modal.NewEntityName = $scope.modal.EntityName;

        if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
            if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                $scope.modal.isBusinessNameChanged = true;
            }
            else {
                $scope.modal.isBusinessNameChanged = false;
            }
        }

        //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : false);
        //var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase(originalEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));
        var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

        if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
            $scope.EntityNameCheck = false;
        }
        else {
            $scope.EntityNameCheck = true;
        }

        $scope.modal.AccEndDateLessThanCurrentYear = ($scope.modal.HasOrganizationCompletedFullAccountingYear) ? $scope.modal.AccEndDateLessThanCurrentYear : false;

        if ($scope.modal.IsShortFiscalYear) {
            var preAccEndDate = wacorpService.dateFormatService($scope.modal.AccountingYearEndingDate);
            var currAccStartDate = wacorpService.dateFormatService($scope.modal.AccountingYearEndingDate);
            if (preAccEndDate != null && currAccStartDate != null && currAccStartDate != undefined && preAccEndDate != undefined) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                var val = wacorpService.checkDateValidity($scope.modal.CurrentEndDateForAmendment, $scope.modal.AccountingYearBeginningDate, $scope.modal.IsShortFiscalYear);
                $scope.modal.IsShortFiscalYear = false;
                $scope.modal.AccEndDateLessThanCurrentYear = false;
                $scope.modal.AccStartDateMoreThanOneYear = false;
                if (val == 'SFY') {
                    $scope.modal.IsShortFiscalYear = true;
                    isShortFiscalYearChecked = true;
                } else if (val == 'SDgPnD') {
                    $scope.modal.AccEndDateLessThanCurrentYear = true;
                } else if (val == 'Y1Plus') {

                    $scope.modal.AccStartDateMoreThanOneYear = true;
                } else {
                    $scope.modal.IsShortFiscalYear = false;
                    $scope.modal.AccEndDateLessThanCurrentYear = false;
                    $scope.modal.AccStartDateMoreThanOneYear = false;
                }
            }
            else {
                $scope.modal.AccEndDateLessThanCurrentYear = false;
                $scope.modal.AccStartDateMoreThanOneYear = false;
            }
        }

        if ($scope.modal.IsShortFiscalYear) {
            getShortYearStartDate(); // getShortYearStartDate method is available in this controller only.
            getShortYearEndDate(); // getShortYearEndDate method is available in this controller only.
        }

        //var shortFiscalInfoValid = $scope.modal.IsShortFiscalYear ? (isShortFiscalYearChecked ? true : false) : true;

        //var isOverrideDocUploaded = ($scope.modal.IsFundraiserOverrideMandetoryReq) ? ($scope.modal.UploadOverrideList.length > 0 ? true : false) : true;

        var isAddressUpload = ($scope.modal.IsUploadAddress) ? ($scope.modal.UploadListOfAddresses.length > 0 ? true : false) : true;

        var isOrgSubmittedSOSProof = ($scope.modal.IsBondWaiverSubmittedProofOfSurety) ? true : ($scope.modal.BondWaiversSOSBondUploadList.length > 0 ? true : false);

        //var isBondWaiver = ($scope.modal.IsBondWaiver) ? ($scope.modal.BondWaiversUploadedSuretyBondsList.length > 0 ? true : false) : true;

        var isCollectedContributions = ($scope.modal.IsOrganizationCollectedContributionsInWA) ? (($scope.modal.ContributionServicesTypeId == null || $scope.modal.ContributionServicesTypeId == undefined || $scope.modal.ContributionServicesTypeId == "") ? false : true) : true;

        var isRegisteredOutside = ($scope.modal.IsRegisteredOutSideOfWashington) ? (($scope.modal.FinancialInfoStateId == null || $scope.modal.FinancialInfoStateId == undefined || $scope.modal.FinancialInfoStateId == "") ? false : true) : true;

        var isOfficerHighPay = ($scope.modal.OfficersHighPayList.length > 0) ? true : false;

        var isExpensesValid = true;
        if (typeof ($scope.modal.CFTFinancialHistoryList) != typeof (undefined) && $scope.modal.CFTFinancialHistoryList.length == 0) {
            isExpensesValid = ($scope.modal.HasOrganizationCompletedFullAccountingYear ? ($scope.modal.AllContributionsReceived < $scope.modal.AmountOfFunds ? false : true) : true);
        }

        var isShortFiscalExpensesValid = true;
        if (typeof ($scope.modal.CFTFinancialHistoryList) != typeof (undefined) && $scope.modal.CFTFinancialHistoryList.length > 0) {
            isShortFiscalExpensesValid = ($scope.modal.IsShortFiscalYear ? ($scope.modal.shortFiscalYearEntity.AllContributionsReceivedForShortFY != null && $scope.modal.shortFiscalYearEntity.AmountOfFundsForShortFY != null ? ($scope.modal.shortFiscalYearEntity.AllContributionsReceivedForShortFY < $scope.modal.shortFiscalYearEntity.AmountOfFundsForShortFY ? false : true) : true) : true);
        }

        var isJurisdictionValid = ($scope.modal.JurisdictionState != NaN && $scope.modal.JurisdictionState != null && $scope.modal.JurisdictionState != undefined && $scope.modal.JurisdictionState != "") ? true : false;

        var isDatesValid = true;//($scope.modal.HasOrganizationCompletedFullAccountingYear ? ((new Date($scope.modal.AccountingYearEndingDate) > new Date($scope.modal.AccountingYearBeginningDate)) ? true : false) : true);

        var isCharitiesFinancialInfo = ($scope.commercialFundraiserAmendmentForm.fundraiserFinancialInfo.$valid) && (isDatesValid);

        var isCftOfficesListValid = ($scope.checkOfficersCount() > 0);

        var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

        var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.UploadSurityBondList.length > 0 ? true : false) : true);

        var isLegalInfo = $scope.modal.isUpdated ? ($scope.commercialFundraiserAmendmentForm.fundraiserLegalInfo.$valid) : true;

        var isFundraiserListValid = true;
        if ($scope.modal.IsCommercialFundraisersContributionsInWA)
            isFundraiserListValid = $scope.modal.FundraisersList.length > 0;

        var Fein = $scope.modal.FEINNumber;
        var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

        var Ubi = $scope.modal.UBINumber;
        var isValidUbi = true;
        //if (!$scope.modal.IsFundraiserOverrideMandetoryReq) {
        isValidUbi = $scope.modal.IsFundraiserOverrideMandetoryReq ? true : ((Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9) ? true : false);
        //}

        var isSignatureAttestationValidate = ($scope.commercialFundraiserAmendmentForm.SignatureForm.$valid);
        //var isCorrespondenceAddressValid = $scope.commercialFundraiserAmendmentForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.commercialFundraiserAmendmentForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.commercialFundraiserAmendmentForm.cftCorrespondenceAddressForm.$valid;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

        $scope.checkAccYearVaild = false;
        if (!$scope.modal.HasOrganizationCompletedFullAccountingYear) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            var FAYEDate = wacorpService.dateFormatService($scope.modal.FirstAccountingYearEndDate);
            if (typeof (FAYEDate) != typeof (undefined) && FAYEDate != null && FAYEDate != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.checkAccYearVaild = wacorpService.checkAccYearEndDateForReg($scope.modal.FirstAccountingYearEndDate, false);
            }
        }

        var isFormValidate = isOrgNameValid && isEntityInfo && isAddressUpload && !$scope.modal.AccStartDateMoreThanOneYear && !$scope.checkAccYearVaild
                                && isOrgSubmittedSOSProof && isCharitiesFinancialInfo && isCftOfficesListValid && isExpensesValid && isShortFiscalExpensesValid
                                   && isLegalActionsListValid && isLegalActionsUploadValid && isEntityNameValid && !$scope.modal.AccEndDateLessThanCurrentYear &&
                                         isFundraiserListValid && isCollectedContributions && isJurisdictionValid
                                        && isRegisteredOutside && isOfficerHighPay && isSignatureAttestationValidate && isValidFein && isValidUbi && isLegalInfo && isAdditionalUploadValid && isCorrespondenceAddressValid;
        $scope.fillRegData();



        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
            $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
            $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

            $rootScope.modal = $scope.modal;
            $location.path('/fundraiserAmendmentReview');
        }
        else

            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        //}
        //else {
        //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
        //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
        //        return false;
        //    }
        //}
    };

    $scope.checkOfficersCount = function () {
        var count = 0;
        angular.forEach($scope.modal.CFTOfficersList, function (value) {
            if (value.OfficerStatus != 'D')
                count++;
        });

        if (count == 0 || count == undefined)
            return $scope.modal.CFTOfficersList.length = 0;
        else
            return $scope.modal.CFTOfficersList.length;
    };

    $scope.fillRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.FinancialId = $scope.modal.FinancialId || null;

        //if ($scope.modal.HasOrganizationCompletedFullAccountingYear)
        //    $scope.modal.oldFiscalYear = $scope.modal.AccountingYearBeginningDate != '01/01/0001' || $scope.modal.AccountingYearBeginningDate != null ? $scope.modal.AccountingYearBeginningDate : null;
        //else
        //    $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingYearEndDate != '01/01/0001' || $scope.modal.FirstAccountingYearEndDate != null ? $scope.modal.FirstAccountingYearEndDate : null;

        //Organization Information
        $scope.modal.EntityName = $scope.modal.EntityName != null && $scope.modal.EntityName != '' ? $scope.modal.EntityName : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        //$scope.modal.UBINumber = $scope.modal.UBINumber.replace(/\s/g, '');
        $scope.modal.RegistrationNumber = $scope.modal.RegistrationNumber || null;
        //$scope.modal.IsEntityRegisteredInWA = false;
        //$scope.modal.IsFundraiserOverrideMandetoryReq = $scope.modal.IsFundraiserOverrideMandetoryReq;
        //$scope.modal.IsFundraiserOverrideMandetoryReq = false;
        $scope.modal.HotList = false;
        $scope.modal.AttorneyGeneral = false;
        $scope.modal.AKANamesList = angular.isNullorEmpty($scope.modal.AKANamesList) ? [] : $scope.modal.AKANamesList;
        //$scope.modal.JurisdictionState = "";
        //$scope.modal.JurisdictionStateDesc = "";
        //$scope.modal.UploadOverrideList = angular.isNullorEmpty($scope.modal.UploadOverrideList) ? [] : $scope.modal.UploadOverrideList;
        //$scope.modal.UploadOverrideList = [];

        //Contact information
        $scope.modal.EntityEmailAddress = $scope.modal.EntityEmailAddress != null && $scope.modal.EntityEmailAddress != '' ? $scope.modal.EntityEmailAddress : null;
        $scope.modal.EntityConfirmEmailAddress = $scope.modal.EntityConfirmEmailAddress != null && $scope.modal.EntityConfirmEmailAddress != '' ? $scope.modal.EntityConfirmEmailAddress : null;
        $scope.modal.EntityWebsite = $scope.modal.EntityWebsite != null && $scope.modal.EntityWebsite != '' ? $scope.modal.EntityWebsite : null;
        $scope.modal.IsForeignContact = $scope.modal.IsForeignContact;
        $scope.modal.CountryCode = $scope.modal.CountryCode || null;
        $scope.modal.EntityPhoneNumber = $scope.modal.EntityPhoneNumber;
        $scope.modal.PhoneExtension = $scope.modal.PhoneExtension
        $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
        $scope.modal.IsSameasStreetAddr = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
        $scope.modal.IsUploadAddress = $scope.modal.IsUploadAddress;
        //$scope.modal.UploadListOfAddresses = angular.isNullorEmpty($scope.modal.UploadListOfAddresses) ? [] : $scope.modal.UploadListOfAddresses;

        //Surety Bond
        $scope.modal.IsBondWaiverSubmittedProofOfSurety = $scope.modal.IsBondWaiverSubmittedProofOfSurety;
        $scope.modal.BondWaiversSOSBondUploadList = angular.isNullorEmpty($scope.modal.BondWaiversSOSBondUploadList) ? [] : $scope.modal.BondWaiversSOSBondUploadList;
        $scope.modal.BondWaiversBondExpirationDate = $scope.modal.BondWaiversBondExpirationDate;
        //$scope.modal.IsBondWaiver = $scope.modal.IsBondWaiver;
        //$scope.modal.IsBondWaiver = false;
        //$scope.modal.BondWaiversUploadedSuretyBondsList = angular.isNullorEmpty($scope.modal.BondWaiversUploadedSuretyBondsList) ? [] : $scope.modal.BondWaiversUploadedSuretyBondsList;
        //$scope.modal.BondWaiversUploadedSuretyBondsList = [];

        //Financial Information
        $scope.modal.HasOrganizationCompletedFullAccountingYear = $scope.modal.HasOrganizationCompletedFullAccountingYear;
        $scope.modal.AccountingYearBeginningDate = $scope.modal.AccountingYearBeginningDate;
        $scope.modal.AccountingYearEndingDate = $scope.modal.AccountingYearEndingDate;
        $scope.modal.FirstAccountingYearEndDate = $scope.modal.FirstAccountingYearEndDate;
        //$scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets;
        //$scope.modal.AllContributionsReceived = $scope.modal.AllContributionsReceived;
        //$scope.modal.AveragePercentToCharity = $scope.modal.AveragePercentToCharity;
        ////$scope.modal.TotalDollarValueofGrossReceipts = $scope.modal.TotalDollarValueofGrossReceipts;
        ////$scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets;
        //$scope.modal.AmountOfFunds = $scope.modal.AmountOfFunds;
        //$scope.modal.ExpensesGDValueofAllExpenditures = $scope.modal.ExpensesGDValueofAllExpenditures;
        $scope.modal.SolicitationComments = $scope.modal.SolicitationComments;
        //$scope.modal.PercentToProgramServices = $scope.modal.PercentToProgramServices;
        $scope.modal.IsOrganizationCollectedContributionsInWA = $scope.modal.IsOrganizationCollectedContributionsInWA;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0 && angular.isArray($scope.modal.ContributionServicesTypeId)) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }
        $scope.modal.IsRegisteredOutSideOfWashington = $scope.modal.IsRegisteredOutSideOfWashington;
        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0 && angular.isArray($scope.modal.FinancialInfoStateId)) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }
        //$scope.modal.OfficersHighPayList = angular.isNullorEmpty($scope.modal.OfficersHighPayList) ? [] : $scope.modal.OfficersHighPayList;
        if ($scope.modal.OfficersHighPayList.length > 0) {
            $scope.modal.OfficersHighPay.IsPayOfficers = true;
        } else {
            $scope.modal.OfficersHighPay.IsPayOfficers = false;
        }

        //Person Accepting Responsibility
        $scope.modal.IsSameAsAddressContactInfo = $scope.modal.IsSameAsAddressContactInfo;
        //$scope.modal.CFTOfficersList = angular.isNullorEmpty($scope.modal.CFTOfficersList) ? [] : $scope.modal.CFTOfficersList;

        //Financial Preparer
        $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID;
        $scope.modal.LegalInfo.FirstName = $scope.modal.LegalInfo.FirstName || null;
        $scope.modal.LegalInfo.LastName = $scope.modal.LegalInfo.LastName || null;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName || null;
        $scope.modal.LegalInfo.EntityRepresentativeFirstName = $scope.modal.LegalInfo.EntityRepresentativeFirstName || null;
        $scope.modal.LegalInfo.EntityRepresentativeLastName = $scope.modal.LegalInfo.EntityRepresentativeLastName || null;
        $scope.modal.LegalInfo.Title = $scope.modal.LegalInfo.Title || null;
        $scope.modal.LegalInfo.LegalInfoAddress = $scope.modal.LegalInfo.LegalInfoAddress || null;
        $scope.modal.LegalInfo.IsAnyLegalActions = $scope.modal.LegalInfo.IsAnyLegalActions;

        //Legal Information
        //$scope.modal.LegalInfoEntityList = angular.isNullorEmpty($scope.modal.LegalInfoEntityList) ? [] : $scope.modal.LegalInfoEntityList;
        //$scope.modal.UploadSurityBondList = angular.isNullorEmpty($scope.modal.UploadSurityBondList) ? [] : $scope.modal.UploadSurityBondList;

        //CFR Sub’s
        $scope.modal.IsCommercialFundraisersContributionsInWA = $scope.modal.IsCommercialFundraisersContributionsInWA;
        //$scope.modal.FundraisersList = angular.isNullorEmpty($scope.modal.FundraisersList) ? [] : $scope.modal.FundraisersList;

        //Charity Clients
        //$scope.modal.CharitiesList = angular.isNullorEmpty($scope.modal.CharitiesList) ? [] : $scope.modal.CharitiesList;

        //Filing Correspondence
        $scope.modal.CFTAttention = $scope.modal.CFTAttention;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        //ONLINE UPLOAD DOCUMENTS
        //$scope.modal.CFTUploadDocumentsList = angular.isNullorEmpty($scope.modal.CFTUploadDocumentsList) ? [] : $scope.modal.CFTUploadDocumentsList;

        //Attestation
        $scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;

        $rootScope.modal = $scope.modal;
    };

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillRegData(); // fillRegData method is available in this controller only.
        $scope.modal.OnlineNavigationUrl = "/fundraiserAmendment";
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // FundraiserSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.FundraiserSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});
wacorpApp.controller('fundraiserAmendmentReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Commercial Fundraiser Amendment Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            $location.path("/fundraiserRegistration");
        }
        else {
            $scope.modal = $rootScope.modal;
            if ($scope.modal.UBINumber != '' && $scope.modal.UBINumber != undefined) {
                $scope.modal.UBINumber = $scope.modal.UBINumber.replace(/(?!^)(?=(?:\d{3})+(?:\.|$))/gm, ' ');
            }
        }
        //$scope.modal = $rootScope.Modal;
        $scope.usaCode = usaCode;
    };


    $scope.FundraiserAmendmentAddToCart = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = ($scope.modal.UBINumber != null && $scope.modal.UBINumber != '') ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0 && angular.isArray($scope.modal.ContributionServicesTypeId)) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }

        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0 && angular.isArray($scope.modal.FinancialInfoStateId)) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }
        $scope.modal.IsOnline = true;

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // FundraiserAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.FundraiserAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
            $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/fundraiserAmendment/' + $scope.modal.FundRaiserID);
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

});

wacorpApp.controller('fundraiserClosureController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.ValidateFinancialEndDateMessage = false;
    $scope.IsFirstAcctyear = null;
    $scope.beginningdate = null;
    $scope.endingdate = null;
    $scope.isReview = false;
    $scope.addedReasons = [];
    $scope.Init = function () {
        $scope.messages = messages;

        $scope.getFundraiserDetails(); // getFundraiserDetails method is available in this controller only.
    }

    $scope.getFundraiserDetails = function () {
        var data = null;
        data = { params: { FundraiserId: $routeParams.FundraiserID, TransactionID: $rootScope.transactionID } };
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            // FundraiserClosureCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.FundraiserClosureCriteria, data, function (response) {
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.BusinessTransaction.DateTimeReceived = wacorpService.dateFormatService(new Date());
                $scope.modal.BusinessTransaction.FilingDate = wacorpService.dateFormatService(new Date());
                $scope.modal.RenewalDate = wacorpService.dateFormatService($scope.modal.RenewalDate);

                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                $scope.modal.FundraisersClosureReasonList = ['Organization Does not raise funds in WA', 'Organization No Longer Exists', 'Organization not needed to register', 'Other'];
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.EffectiveClosureDate = wacorpService.dateFormatService($scope.modal.EffectiveClosureDate);
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                $scope.modal.AccountingYearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingYearBeginningDate);
                $scope.modal.AccountingYearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingYearEndingDate);
                $scope.modal.FirstAccountingYearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingYearEndDate);
                $scope.beginningdate = wacorpService.dateFormatService($scope.modal.AccountingYearBeginningDate);
                $scope.endingdate = wacorpService.dateFormatService($scope.modal.AccountingYearEndingDate);
                $scope.IsFirstAcctyear = wacorpService.dateFormatService($scope.modal.FirstAccountingYearEndDate);

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }
                $scope.modal.HasOrganizationCompletedFullAccountingYear = $scope.modal.HasOrganizationCompletedFullAccountingYear;
                if (!$rootScope.IsShoppingCart || $rootScope.IsShoppingCart == undefined) {
                    $scope.modal.AllContributionsReceived = null;
                    $scope.modal.AveragePercentToCharity = null;
                    $scope.modal.AmountOfFunds = null;
                }
                if (!$rootScope.IsShoppingCart || $rootScope.IsShoppingCart == undefined) {
                    $scope.modal.CFTCorrespondenceAddress.Country = codes.USA;
                    $scope.modal.CFTCorrespondenceAddress.State = codes.WA;
                }
                else if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                //Assigning 0's to Empty
                $scope.modal.AllContributionsReceived = $scope.modal.IsAllContributionsReceivedEmpty ? null : $scope.modal.AllContributionsReceived;
                $scope.modal.AveragePercentToCharity = $scope.modal.IsAveragePercentToCharityEmpty ? null : $scope.modal.AveragePercentToCharity;
                $scope.modal.AmountOfFunds = $scope.modal.IsAmountOfFundsEmpty ? null : $scope.modal.AmountOfFunds;

                $scope.modal.SolicitationComments = $scope.modal.SolicitationComments;

                if ($scope.modal.FundraisersClosureReason != null && $scope.modal.FundraisersClosureReason != "" && $scope.modal.FundraisersClosureReason != undefined)
                    $scope.addedReasons = $scope.modal.FundraisersClosureReason.split(',');
                else
                    $scope.addedReasons = [];

                if (!$scope.modal.HasOrganizationCompletedFullAccountingYear) {
                    $scope.validateFinancialDates(); // validateFinancialDates method is available in this controller only.
                }
                $scope.modal.isShowReturnAddress = true;

            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            if ($scope.modal.FundraisersClosureReason != null && $scope.modal.FundraisersClosureReason != "" && $scope.modal.FundraisersClosureReason != undefined)
                $scope.addedReasons = $scope.modal.FundraisersClosureReason.split(',');
            else
                $scope.addedReasons = [];
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.BusinessTransaction.DateTimeReceived = wacorpService.dateFormatService($scope.modal.BusinessTransaction.DateTimeReceived);
            $scope.modal.BusinessTransaction.FilingDate = wacorpService.dateFormatService($scope.modal.BusinessTransaction.FilingDate);
            $scope.modal.RenewalDate = wacorpService.dateFormatService($scope.modal.RenewalDate);

            $scope.beginningdate = wacorpService.dateFormatService($scope.modal.AccountingYearBeginningDate);
            $scope.endingdate = wacorpService.dateFormatService($scope.modal.AccountingYearEndingDate);
            $scope.IsFirstAcctyear = wacorpService.dateFormatService($scope.modal.FirstAccountingYearEndDate);

            //Assigning 0's to Empty
            $scope.modal.AllContributionsReceived = $scope.modal.IsAllContributionsReceivedEmpty ? null : $scope.modal.AllContributionsReceived;
            $scope.modal.AveragePercentToCharity = $scope.modal.IsAveragePercentToCharityEmpty ? null : $scope.modal.AveragePercentToCharity;
            $scope.modal.AmountOfFunds = $scope.modal.IsAmountOfFundsEmpty ? null : $scope.modal.AmountOfFunds;
            $scope.modal.isShowReturnAddress = true;
        }
    };

    $scope.CheckEndDate = function () {
        if ($scope.modal.AccountingYearEndingDate != null && $scope.modal.AccountingYearBeginningDate != null) {
            if (new Date($scope.modal.AccountingYearEndingDate) < new Date($scope.modal.AccountingYearBeginningDate)) {
                $scope.ValidateFinancialEndDateMessage = true;
            }
            else
                $scope.ValidateFinancialEndDateMessage = false;
        }
    };

    $scope.Review = function () {
        $scope.validateErrorMessage = true;

        //var endDate = $scope.modal.AccountingYearEndingDate;
        //if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
        //    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
        //    if (isEndDateMore) {
        //        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
        //        return false;
        //    }
        //}

        var isEffectiveDateExists = ($scope.fundriaserClosureForm.EffectiveDate.$valid);
        var isFinancial = $scope.modal.IsDateEditable ? true : ($scope.fundriaserClosureForm.fundraiserFinancialInfo.$valid);
        $scope.modal.FundraisersClosureReason = $scope.addedReasons.join(',');
        $scope.modal.addedReasons = $scope.addedReasons;
        var isSignatureAttestationValidate = ($scope.fundriaserClosureForm.SignatureForm.$valid);
        //var isCorrespondenceAddressValid = $scope.fundriaserClosureForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.fundriaserClosureForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.fundriaserClosureForm.cftCorrespondenceAddressForm.$valid;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;
        var isExpensesValid = ($scope.modal.HasOrganizationCompletedFullAccountingYear ? ($scope.modal.AllContributionsReceived < $scope.modal.AmountOfFunds ? false : true) : true);

        var isFormValidate = isEffectiveDateExists && $scope.addedReasons.length > 0 && isFinancial && isExpensesValid && isSignatureAttestationValidate && isCorrespondenceAddressValid && isAdditionalUploadValid;
        $scope.fillRegData(); // fillRegData method is available in this controller only.
        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            $rootScope.modal = $scope.modal;
            $location.path('/fundraiserClosureReview');
        } else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    $scope.$watchGroup(['modal.AllContributionsReceived', 'modal.AmountOfFunds'], function () {
        var value1 = parseFloat($scope.modal.AmountOfFunds == null || $scope.modal.AmountOfFunds == '') ? 0 : $scope.modal.AmountOfFunds;
        var value2 = parseFloat($scope.modal.AllContributionsReceived == null || $scope.modal.AllContributionsReceived == '') ? 0 : $scope.modal.AllContributionsReceived;

        var percentage = null;
        if (value1 && value2)
            percentage = ((value1 / value2) * 100).toFixed(2);
        else
            percentage = null;

        if (isNaN(percentage) || percentage === 0)
            $scope.modal.AveragePercentToCharity = null;
        else
            $scope.modal.AveragePercentToCharity = Math.round(percentage);
    }, true);

    $scope.$watch('modal.SolicitationComments', function () {
        if ($scope.modal.SolicitationComments)
        {
            if ($scope.modal.SolicitationComments.length > 500)
            {
                $scope.modal.SolicitationComments = $scope.modal.SolicitationComments.replace(/(\r\n|\n|\r)/gm, "");
                $scope.modal.SolicitationComments = $scope.modal.SolicitationComments.substring(0, 500);
            }
        }
    });

    $scope.fillRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.FinancialId = $scope.modal.FinancialId || null;

        //Organization Information
        $scope.modal.EntityName = $scope.modal.EntityName != null && $scope.modal.EntityName != '' ? $scope.modal.EntityName : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        $scope.modal.FundraisersClosureReason = $scope.addedReasons.join(',');
        //Financial Information
        $scope.modal.HasOrganizationCompletedFullAccountingYear = $scope.modal.HasOrganizationCompletedFullAccountingYear;

        $scope.modal.AccountingYearBeginningDate = $scope.modal.AccountingYearBeginningDate;
        $scope.modal.AccountingYearEndingDate = $scope.modal.AccountingYearEndingDate;
        $scope.modal.FirstAccountingYearEndDate = $scope.modal.FirstAccountingYearEndDate;

        $scope.modal.IsAllContributionsReceivedEmpty = ($scope.modal.AllContributionsReceived == null || isNaN($scope.modal.AllContributionsReceived)) ? true : false;
        $scope.modal.IsAveragePercentToCharityEmpty = ($scope.modal.AveragePercentToCharity == null || isNaN($scope.modal.AveragePercentToCharity)) ? true : false;
        $scope.modal.IsAmountOfFundsEmpty = ($scope.modal.AmountOfFunds == null || isNaN($scope.modal.AmountOfFunds)) ? true : false;

        $scope.modal.AllContributionsReceived = $scope.modal.AllContributionsReceived == null ? null : $scope.modal.AllContributionsReceived;
        $scope.modal.AveragePercentToCharity = $scope.modal.AveragePercentToCharity == null ? null : $scope.modal.AveragePercentToCharity;
        $scope.modal.AmountOfFunds = $scope.modal.AmountOfFunds == null ? null : $scope.modal.AmountOfFunds;

        $scope.modal.SolicitationComments = $scope.modal.SolicitationComments;
        //Filing Correspondence
        $scope.modal.CFTAttention = $scope.modal.CFTAttention;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        //ONLINE UPLOAD DOCUMENTS
        $scope.modal.CFTUploadDocumentsList = angular.isNullorEmpty($scope.modal.CFTUploadDocumentsList) ? [] : $scope.modal.CFTUploadDocumentsList;

        //Attestation
        $scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;

        $scope.modal.addedReasons = $scope.addedReasons;

        $rootScope.modal = $scope.modal;
    };

    // Toggle selection for a given fruit by name
    $scope.toggleSelection = function toggleSelection(reason) {
        var idx = $scope.addedReasons.indexOf(reason);
        if (idx > -1) {
            $scope.addedReasons.splice(idx, 1);
        }
        else {
            $scope.addedReasons.push(reason);
        }
    };

    var resultDate = "";
    $scope.CalculateEndDate = function () {
        if ($scope.modal.AccountingYearBeginningDate != null && $scope.modal.AccountingYearBeginningDate != "") {
            var value = $scope.modal.AccountingYearBeginningDate;
            var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
            var result = value.match(rxDatePattern);
            if (result != null) {
                var dateValue = new Date(value);
                dateValue.setYear(dateValue.getFullYear() + 1);
                var firstDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 1);
                var lastDay = new Date(dateValue.getFullYear(), dateValue.getMonth(), 0);
                var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
                resultDate = lastDayWithSlashes;
                $scope.modal.AccountingYearEndingDate = lastDayWithSlashes.toString("mm/dd/yyyy");
                $("#idEndDate").datepicker("setDate", lastDayWithSlashes);
            }
            else {
                $scope.modal.AccountingYearEndingDate = null;
            }
        }
        $scope.validateFinancialDates(); // validateFinancialDates method is availble in this controller only.
    };

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillRegData(); // fillRegData method is availble in this controller only.
        $scope.modal.OnlineNavigationUrl = "/fundraiserClosure";
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // FundraiserSaveandClose method is availble in constants.js.
        wacorpService.post(webservices.CFT.FundraiserSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    //check Accounting year endat date is greater than current date
    $scope.validateFinancialDates = function () {
        var currentDate = new Date();
        if ($scope.modal.HasOrganizationCompletedFullAccountingYear) {

            var newDate = new Date($scope.modal.AccountingYearEndingDate);
            if (newDate > currentDate) {
                $scope.modal.IsDateEditable = true;
                $scope.modal.AllContributionsReceived = null;
                $scope.modal.AveragePercentToCharity = null;
                $scope.modal.AmountOfFunds = null;
                $scope.modal.AccountingYearBeginningDate = null;
                $scope.modal.AccountingYearEndingDate = null;
            }
        }
        else {
            var newDate = new Date($scope.modal.FirstAccountingYearEndDate);
            if (newDate > currentDate) {
                $scope.modal.IsDateEditable = true;
                $scope.modal.FirstAccountingYearEndDate = null;
            }
        }
    };

});
wacorpApp.controller('fundraiserClosureReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    $scope.Init = function () {
        $scope.modal = $rootScope.modal;
        $scope.messages = messages;
        $scope.isReview = true;
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            $location.path('/fundraiserClosure');
        }
        else {
            $scope.modal = $rootScope.modal;
            if ($scope.modal.UBINumber != '' && $scope.modal.UBINumber != undefined) {
                $scope.modal.UBINumber = $scope.modal.UBINumber.replace(/(?!^)(?=(?:\d{3})+(?:\.|$))/gm, ' ');
            }
        }
    }

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/fundraiserClosure/' + $scope.modal.FundRaiserID);
    }

    $scope.AddToCart = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.IsOnline = true;

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // FundraiserAddToCart method is available in constants.js
            wacorpService.post(webservices.CFT.FundraiserAddToCart, $scope.modal, function (response) {
                $rootScope.BusinessType = null;
                //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
                $location.path('/shoppingCart');
                //else
                //    $location.path('/Dashboard');
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
    };
});
wacorpApp.controller('trusteeRenewalSearchController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    // declare scope variables
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
    $scope.businessSearchCriteria = { Type: "entityname", ID: "", PageID: 1, PageCount: 10, isSearchClick: false };
    $scope.selectedBusiness = null;
    $scope.search = loadbusinessList;
    $scope.isEntityOrFEINRequired = $scope.isEntityOrFEINRequired || messages.EntityNameRequired;
    focus('searchField');

    // search business list
    $scope.submit = function (searchform) {
        $scope.isShowErrorFlag = true;
        $scope.isEntityOrFEINRequired = $scope.businessSearchCriteria.Type == 'entityname' ? messages.EntityNameRequired : messages.FEINNumberRequired;
        if ($scope[searchform].$valid) {
            $scope.businessSearchCriteria.isSearchClick = true;
            $scope.isShowErrorFlag = false;
            loadbusinessList($scope.page); // loadbusinessList method is available in this controller only.
        }
    };
    // clear fields
    $scope.clearFun = function () {
        $scope.businessSearchCriteria.ID = "";
        $scope.businessSearchCriteria.isSearchClick = false;
        focus('searchField');
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
    }

    // navigate to fundraiser renewal
    $scope.submitBusiness = function () {
        //if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.Status) >= constant.ZERO) {
            $rootScope.TrustID = $scope.selectedBusiness.TrustID;
            $rootScope.trusteeRenewalModal = null;
            $rootScope.transactionID = null;
            $location.path('/trusteeRenewal/' + $scope.selectedBusiness.TrustID);
        //}
        //else {
        //    wacorpService.alertDialog(messages.selectedEntity.replace('{0}', $scope.selectedBusiness.Status));
        //}
    };
    // get business list data from server
    function loadbusinessList(page) {
        page = page || 0;
        $scope.businessSearchCriteria.PageID = page == 0 ? 1 : page + 1;
        $scope.selectedBusiness = null;
        var data = $scope.businessSearchCriteria
        // getTrusteeSearchDetails method is available in constants.js
        wacorpService.post(webservices.CFT.getTrusteeSearchDetails, data, function (response) {
            $scope.BusinessList = response.data;
            if ($scope.totalCount == 0) {
                var totalcount = response.data[0].Criteria.TotalRowCount;
                $scope.pagesCount = Math.round(totalcount / response.data.length);
                $scope.totalCount = totalcount;
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus('tblBusinessSearch');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == 0) {
            $scope.totalCount = 0;
            $scope.pagesCount = 0;
            $scope.totalCount = 0;
            $scope.page = 0;
        }
    }, true);
});



wacorpApp.controller('trusteeRenewalController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    var originalEntityName = "";
    var getIRSDocumentList = function () {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.irsDocumentsList(function (response) { $scope.IRSDocumentTypes = response.data; });
    };
    function getNavigation() {
        //if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.Status) >= constant.ZERO) {
        $rootScope.TrustID = $scope.selectedBusiness.TrustID;
        $rootScope.trusteeRenewalModal = null;
        $rootScope.transactionID = null;
        $location.path('/TrusteeRenewalSearch/' + $scope.selectedBusiness.TrustID);
        //}
        //else {
        //    wacorpService.alertDialog(messages.selectedEntity.replace('{0}', $scope.selectedBusiness.Status));
        //}
    }


    /* --------Commercial Trust Renewal Functionality------------- */
    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    $scope.OfficersCount = false;
    //// page load
    $scope.Init = function () {
        $scope.messages = messages;
        // here BusinessTypeID = 8 is CHARITABLE TRUST
        $rootScope.BusinessTypeID = 8;
        //get business information
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 171 is CHARITABLE TRUST RENEWAL
            data = { params: { trustID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 171, transactionID: $rootScope.transactionID } };
        else
            data = { params: { trustID: $routeParams.id, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 171, transactionID: $rootScope.transactionID } };

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/TrusteeRenewalSearch');
            }
            // getTrustRenewalCriteria method is available in constants.js
            wacorpService.get(webservices.CFT.getTrustRenewalCriteria, data, function (response) {
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                originalEntityName = $scope.modal.EntityName;
                $scope.modal.JurisdictionCountry = response.data.JurisdictionCountry == 0 ? "" : response.data.JurisdictionCountry.toString();
                $scope.modal.JurisdictionState = response.data.JurisdictionState == 0 ? "" : response.data.JurisdictionState.toString();
                $scope.modal.FederalTaxExemptId = response.data.FederalTaxExemptId == null ? "" : response.data.FederalTaxExemptId.toString();
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                $scope.modal.PurposeId = angular.isNullorEmpty($scope.modal.PurposeId) ? [] : $scope.modal.PurposeId.split(',');
                $scope.modal.ContactPersonAddress.State = response.data.ContactPersonAddress.State == "" ? codes.WA : response.data.ContactPersonAddress.State;
                $scope.modal.ContactPersonAddress.Country = response.data.ContactPersonAddress.Country == "" ? codes.USA : response.data.ContactPersonAddress.Country;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.County = $scope.modal.EntityStreetAddress.County != null ? $scope.modal.EntityStreetAddress.County : "";
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country != null ? $scope.modal.LegalInfo.LegalInfoAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';

                $scope.modal.OldIsFederalTax = $scope.modal.IsFederalTax;
                $scope.modal.OldIsShowFederalTax = $scope.modal.IsShowFederalTax;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
                $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
                $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);

                $scope.FirstAccountingyearEndDate = new Date();
                $scope.FirstAccountingyearEndDate = $scope.modal.FirstAccountingyearEndDate;
                if ($scope.modal.IsActiveFilingExist) {
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }

                var accEndDate;


                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.IsFIFullAccountingYear) {
                        if ($scope.modal.AccountingyearEndingDate && $scope.modal.AccountingyearEndingDate != "01/01/0001") {
                            accEndDate = new Date($scope.modal.AccountingyearEndingDate);
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            accEndDate = wacorpService.dateFormatService(accEndDate.setDate(accEndDate.getDate() + 1));
                            $scope.modal.AccountingyearBeginningDate = accEndDate;
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.calculateEndDate(accEndDate));
                        }
                        else
                            $scope.modal.IsRenewalMinDates = true;
                    }
                    else {
                        if ($scope.modal.FirstAccountingyearEndDate && $scope.modal.FirstAccountingyearEndDate != "01/01/0001") {
                            var _enddate = new Date($scope.modal.FirstAccountingyearEndDate);
                            // Service Folder: services
                            // File Name: wacorpService.js (you can search with file name in solution explorer)
                            $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.calculateAccountingYearBgnDate(_enddate));

                            $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.calculateEndDate($scope.modal.AccountingyearBeginningDate));

                            //accEndDate = new Date($scope.modal.FirstAccountingyearEndDate);
                            //$scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.calculateEndDate(accEndDate));
                            //var beginDate = new Date($scope.FirstAccountingyearEndDate);
                            //beginDate = wacorpService.dateFormatService(beginDate.setDate(beginDate.getDate() + 1));
                            //$scope.modal.AccountingyearBeginningDate = beginDate;

                            $scope.modal.IsFIFullAccountingYear = true;
                            $scope.modal.BeginingGrossAssets = $scope.modal.EndingGrossAssets != null ? $scope.modal.EndingGrossAssets : null;
                        }
                        else {
                            $scope.modal.IsRenewalMinDates = true;
                            $scope.modal.IsFIFullAccountingYear = true;
                        }

                    }
                    if ($scope.modal.AccountingyearBeginningDate != "01/01/0001") //added on 9/13/2017
                    {
                        $scope.modal.BeginingGrossAssets = $scope.modal.EndingGrossAssets != null ? $scope.modal.EndingGrossAssets : null;
                        $scope.modal.TotalRevenue = null;
                        $scope.modal.GrantContributionsProgramService = null;
                        $scope.modal.Compensation = null;
                        $scope.modal.TotalExpenses = null;
                        $scope.modal.EndingGrossAssets = null;
                        $scope.modal.IRSDocumentId = 0;
                    }
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                if ($scope.modal.OfficersHighPayList.length > 0) {
                    angular.forEach($scope.modal.OfficersHighPayList, function (cftHihPay) {
                        cftHihPay.SequenceNo = cftHihPay.ID;
                    });
                }

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.CFTOfficersList.length > 0) {
                        angular.forEach($scope.modal.CFTOfficersList, function (cftOffice) {
                            cftOffice.SequenceNo = cftOffice.OfficerID;
                        });
                    }

                    if ($scope.modal.cftBeneficaryList.length > 0) {
                        angular.forEach($scope.modal.cftBeneficaryList, function (cftOffice) {
                            cftOffice.SequenceNo = cftOffice.CFTBeneficaryID;
                        });
                    }
                }


                //if ($scope.modal.CFTFinancialHistoryList.length > 0) {
                //    angular.forEach($scope.modal.CFTFinancialHistoryList, function (fundraiser) {
                //        fundraiser.SequenceNo = fundraiser.FinancialId;
                //    });
                //}

                if ($scope.modal.LegalInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.LegalInfoEntityList, function (cftLegalInfo) {
                        cftLegalInfo.SequenceNo = cftLegalInfo.LegalInfoId;
                    });
                }

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }

                $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;

                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;

                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                $scope.modal.isHavingEntityOnUBISearch = angular.isNullorEmpty($scope.modal.UBINumber) ? false : true;

                $scope.ValidateRenewalDate();
                $scope.modal.isShowReturnAddress = true;

            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;

            //Assigning 0's to Empty
            $scope.modal.TotalRevenue = $scope.modal.TotalRevenue == 0 ? null : $scope.modal.TotalRevenue;
            $scope.modal.GrantContributionsProgramService = $scope.modal.GrantContributionsProgramService == 0 ? null : $scope.modal.GrantContributionsProgramService;
            $scope.modal.Compensation = $scope.modal.Compensation == 0 ? null : $scope.modal.Compensation;
            $scope.modal.TotalExpenses = $scope.modal.TotalExpenses == 0 ? null : $scope.modal.TotalExpenses;
            $scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets == 0 ? null : $scope.modal.EndingGrossAssets;
            $scope.modal.isShowReturnAddress = true;
        }
        getIRSDocumentList(); // getIRSDocumentList method is available in this controller only.
    };

    $scope.TrusteeValidateEndDate = function () {
        return (new Date($scope.modal.AccountingyearEndingDate) < new Date($scope.modal.AccountingyearBeginningDate));
    };

    $scope.ValidateRenewalDate = function () {
        var result = $scope.modal.ErrorMsg == null || $scope.modal.ErrorMsg == "" ? true : false;
        if (!result) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.modal.ErrorMsg);
            return false;
        }
        return true;
    };

    $scope.Review = function (TrusteeRenewalForm) {
        // ValidateRenewalDate method is available in this controller only.
        if ($scope.ValidateRenewalDate()) {
            $scope.validateErrorMessage = true;

            var endDate = $scope.modal.AccountingyearEndingDate;
            if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
                if (isEndDateMore) {
                    // Folder Name: app Folder
                    // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
                    return false;
                }
            }

            //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {
            //var isFEINValid = ($scope.modal.UBINumber != "" ? $scope.modal.IsUBINumberExistsorNot : true) && $scope.TrusteeRenewalForm.fein.$valid;

            $scope.modal.NewEntityName = $scope.modal.EntityName;

            if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
                if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                    $scope.modal.isBusinessNameChanged = true;
                }
                else {
                    $scope.modal.isBusinessNameChanged = false;
                }
            }

            //var isEntityNameValid = $scope.TrusteeRenewalForm.cftEntityName.$valid;
            var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

            if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
                $scope.EntityNameCheck = false;
            }
            else {
                $scope.EntityNameCheck = true;
            }

            var isEntityInfoValid = ($scope.TrusteeRenewalForm.entityInfo.$valid)
                                   && ($scope.modal.isUploadAddress ? ($scope.modal.UploadListOfAddresses.length > 0) : true);

            //var isUploadTaxValid = ($scope.modal.IsFiscalAccountingYearReported ? ($scope.modal.UploadTaxReturnList.length > 0) : true);

            var Fein = $scope.modal.FEINNumber;
            var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

            var Ubi = $scope.modal.UBINumber;
            var isValidUbi = true;
            //if (!$scope.modal.IsFundraiserOverrideMandetoryReq) {
            isValidUbi = (Ubi == null || Ubi == '' || Ubi == undefined) ? true : (Ubi.length == 9);

            var isFeinPurposeValid = ($scope.modal.Purpose != "" && $scope.modal.Purpose != null && $scope.modal.Purpose != undefined) ? true : false;

            var isFederalTaxValid = $scope.modal.IsFederalTax ? (($scope.modal.FederalTaxExemptId == 0 || $scope.modal.FederalTaxExemptId == "" || $scope.modal.FederalTaxExemptId == null || $scope.modal.FederalTaxExemptId == undefined) ? false : true) : true;

            var isIRSDocumentTypeValid = $scope.modal.IRSDocumentId != 0 ? true : false;

            //var irsDocCount = 0;
            //angular.forEach($scope.modal.FinancialInfoIRSUpload, function (item) {
            //    if (item.Status == 'D') {
            //        irsDocCount++;
            //    }
            //    else {
            //        irsDocCount--;
            //    }
            //});
            //var isIRSDocumentValid = $scope.modal.FinancialInfoIRSUpload.length != irsDocCount ? true : false;

            var isFederalUpload = $scope.modal.IsShowFederalTax ? ($scope.modal.FederaltaxUpload.length > 0 ? true : false) : true;

            var isIRSDocumentValid = $scope.modal.FinancialInfoIRSUpload.length > 0 ? true : false;

            var isTrustFinancialInfoValid = $scope.TrusteeRenewalForm.trustFinancialInfoForm.$valid;

            var isCftOfficesListValid = ($scope.checkOfficersCount() > 0);

            //var isTrustBeneficariesListValid = ($scope.checkBeneficariesCount() > 0);

            // var isEstablishmentOfTrust = $scope.modal.ProbateOrder || $scope.modal.LastWillAndTestament || $scope.modal.TrustAgreement || $scope.modal.ArticlesOfIncorporationAndBylaws;

            var isDirectoryInfoValid = $scope.TrusteeRenewalForm.directoryInformationForm.$valid;

            var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

            var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalActionsUploads.length > 0 ? true : false) : true);

            //var isLegalInfo = ($scope.TrusteeRenewalForm.legalActionsForm.$valid);

            var isLegalInfo = ($scope.TrusteeRenewalForm.trustLegalInfo.$valid);

            var isPurposeValid = $scope.modal.IsIncludedInWACharitableTrust ? ($scope.modal.PurposeId.length <= 3 ? true : false) : true;

            var isSignatureAttestationValid = $scope.TrusteeRenewalForm.SignatureForm.$valid;

            //var isCorrespondenceAddressValid = $scope.TrusteeReRegistrationForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.commercialFundraiserReRegistrationForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
            var isCorrespondenceAddressValid = $scope.TrusteeRenewalForm.cftCorrespondenceAddressForm.$valid;

            //Upload Additional Documents
            var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

            var isFormValid = isEntityNameValid && isEntityInfoValid && isTrustFinancialInfoValid && isCftOfficesListValid && isDirectoryInfoValid && isLegalInfo && isFeinPurposeValid
                //&& isEstablishmentOfTrust 
                                && isIRSDocumentTypeValid && isIRSDocumentValid && isFederalUpload && isLegalActionsUploadValid && isCorrespondenceAddressValid && isFederalTaxValid
                                  && isLegalActionsListValid && isSignatureAttestationValid && isAdditionalUploadValid && isPurposeValid && isValidFein && isValidUbi;
            //&& isTrustBeneficariesListValid;

            $scope.fillRegData(); // fillRegData method is available in this controller only.

            if (isFormValid) {
                $scope.validateErrorMessage = false;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
                $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
                $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

                $rootScope.modal = $scope.modal;
                $location.path('/TrusteeRenewalReview');
            }
            else
                // Folder Name: app Folder
                // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
            //}
            //else {
            //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
            //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
            //        return false;
            //    }
            //}
        }
    };


    $scope.checkOfficersCount = function () {
        var count = 0;
        angular.forEach($scope.modal.CFTOfficersList, function (value) {
            if (value.OfficerStatus != 'D')
                count++;
        });

        if (count == 0 || count == undefined)
            return $scope.modal.CFTOfficersList.length = 0;
        else
            return $scope.modal.CFTOfficersList.length;
    };

    $scope.fillRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.FinancialId = $scope.modal.FinancialId || null;

        //Organization Information
        $scope.modal.EntityName = $scope.modal.EntityName != null && $scope.modal.EntityName != '' ? $scope.modal.EntityName : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        //$scope.modal.UBINumber = $scope.modal.UBINumber.replace(/\s/g, '');
        $scope.modal.RegistrationNumber = $scope.modal.RegistrationNumber || null;
        $scope.modal.IsEntityRegisteredInWA = false;
        $scope.modal.JurisdictionState = "";
        $scope.modal.JurisdictionStateDesc = "";

        //Contact information
        $scope.modal.EntityEmailAddress = $scope.modal.EntityEmailAddress != null && $scope.modal.EntityEmailAddress != '' ? $scope.modal.EntityEmailAddress : null;
        $scope.modal.EntityConfirmEmailAddress = $scope.modal.EntityConfirmEmailAddress != null && $scope.modal.EntityConfirmEmailAddress != '' ? $scope.modal.EntityConfirmEmailAddress : null;
        $scope.modal.EntityWebsite = $scope.modal.EntityWebsite != null && $scope.modal.EntityWebsite != '' ? $scope.modal.EntityWebsite : null;
        $scope.modal.IsForeignContact = $scope.modal.IsForeignContact;
        $scope.modal.CountryCode = $scope.modal.CountryCode || null;
        $scope.modal.EntityPhoneNumber = $scope.modal.EntityPhoneNumber;
        $scope.modal.PhoneExtension = $scope.modal.PhoneExtension
        $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
        $scope.modal.IsSameasStreetAddr = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
        $scope.modal.IsUploadAddress = $scope.modal.IsUploadAddress;
        //$scope.modal.UploadListOfAddresses = angular.isNullorEmpty($scope.modal.UploadListOfAddresses) ? [] : $scope.modal.UploadListOfAddresses;

        //Financial Information
        $scope.modal.IsFIFullAccountingYear = $scope.modal.IsFIFullAccountingYear;
        $scope.modal.AccountingyearBeginningDate = $scope.modal.AccountingyearBeginningDate;
        $scope.modal.AccountingyearEndingDate = $scope.modal.AccountingyearEndingDate;
        $scope.modal.FirstAccountingyearEndDate = $scope.modal.FirstAccountingyearEndDate;
        $scope.modal.BeginingGrossAssets = $scope.modal.BeginingGrossAssets;
        $scope.modal.TotalRevenue = $scope.modal.TotalRevenue;
        $scope.modal.GrantContributionsProgramService = $scope.modal.GrantContributionsProgramService;
        $scope.modal.Compensation = $scope.modal.Compensation;
        $scope.modal.EndingGrossAssets = $scope.modal.EndingGrossAssets;
        $scope.modal.TotalExpenses = $scope.modal.TotalExpenses;
        $scope.modal.Comments = $scope.modal.Comments;

        $scope.modal.IRSDocumentId = $scope.modal.IRSDocumentId

        if ($scope.modal.IRSDocumentId == 0) {
            $scope.modal.IRSDocumentTye = null;
        }
        else {
            angular.forEach($scope.IRSDocumentTypes, function (val) {
                if ($scope.modal.IRSDocumentId == val.Key) {
                    $scope.modal.IRSDocumentTye = val.Value;
                }
            });
        }

        $scope.modal.FinancialInfoIRSUploadTypeText = $scope.modal.IRSDocumentTye;

        //Person Accepting Responsibility
        $scope.modal.IsSameAsAddressContactInfo = $scope.modal.IsSameAsAddressContactInfo;
        //$scope.modal.CFTOfficersList = angular.isNullorEmpty($scope.modal.CFTOfficersList) ? [] : $scope.modal.CFTOfficersList;

        //Financial Preparer
        $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID;
        $scope.modal.LegalInfo.FirstName = $scope.modal.LegalInfo.FirstName || null;
        $scope.modal.LegalInfo.LastName = $scope.modal.LegalInfo.LastName || null;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName || null;
        $scope.modal.LegalInfo.EntityRepresentativeFirstName = $scope.modal.LegalInfo.EntityRepresentativeFirstName || null;
        $scope.modal.LegalInfo.EntityRepresentativeLastName = $scope.modal.LegalInfo.EntityRepresentativeLastName || null;
        $scope.modal.LegalInfo.Title = $scope.modal.LegalInfo.Title || null;
        $scope.modal.LegalInfo.LegalInfoAddress = $scope.modal.LegalInfo.LegalInfoAddress || null;
        $scope.modal.LegalInfo.IsAnyLegalActions = $scope.modal.LegalInfo.IsAnyLegalActions;

        //Legal Information
        //$scope.modal.LegalInfoEntityList = angular.isNullorEmpty($scope.modal.LegalInfoEntityList) ? [] : $scope.modal.LegalInfoEntityList;
        //$scope.modal.UploadSurityBondList = angular.isNullorEmpty($scope.modal.UploadSurityBondList) ? [] : $scope.modal.UploadSurityBondList;

        //Filing Correspondence
        $scope.modal.CFTAttention = $scope.modal.CFTAttention;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        //ONLINE UPLOAD DOCUMENTS
        //$scope.modal.CFTUploadDocumentsList = angular.isNullorEmpty($scope.modal.CFTUploadDocumentsList) ? [] : $scope.modal.CFTUploadDocumentsList;

        //Attestation
        $scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;
        if (typeof ($scope.modal.PurposeId) != typeof (undefined) && $scope.modal.PurposeId != null) {
            if (angular.isArray($scope.modal.PurposeId) && $scope.modal.PurposeId.length > 0)
                $scope.modal.PurposeId = $scope.modal.PurposeId.join(",");
        }
        $rootScope.modal = $scope.modal;
    };

    $scope.calculateEndDate = function (value) {
        if (value != null && value != undefined) {
            var endDate = new Date(value);
            endDate.setYear(endDate.getFullYear() + 1);
            var firstDay = new Date(endDate.getFullYear(), endDate.getMonth(), 1);
            var lastDay = new Date(endDate.getFullYear(), endDate.getMonth(), 0);
            var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
            return lastDayWithSlashes;
        }
    };

    //TFS 1159 Old Code
    $scope.calculateAccountingYearBgnDate = function (value) {
        if (value != null && value != undefined) {
            var accEndDate = new Date(value)
            accEndDate = new Date(accEndDate.setMonth(accEndDate.getMonth() - 11))
            accEndDate = new Date(accEndDate.getFullYear(), accEndDate.getMonth(), 1)
            return accEndDate;
        }
    }
    //TFS 1159 Old Code

    //TFS 1159 Updated Code
    //$scope.calculateAccountingYearBgnDate = function (value) {
    //    if (value != null && value != undefined) {
    //        var accEndDate = new Date(value);
    //        //TFS 1159 Updated Logic
    //        //Note: months are 0-11
    //        //if (accEndDate.getMonth() < 11) {  //month 0-10 (not december)
    //        //    var getStartMonth = accEndDate.getMonth() + 1;  //get next month
    //        //    var getStartYear = accEndDate.getFullYear() - 1;  //get previous year
    //        //} else {  //month 11 = 1/1/YYYY to 12/31/YYYY
    //        //    var getStartMonth = 0; //get month 0 (January)
    //        //    var getStartYear = accEndDate.getFullYear();  //no year change
    //        //}
            
            
    //        //accEndDate = new Date(getStartYear, getStartMonth);
    //        //return accEndDate;
    //        
    //    }
    //}
    //TFS 1159 Updated Logic

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillRegData(); // fillRegData method is available in this controller only.
        $scope.modal.OnlineNavigationUrl = "/trusteeRenewal/" + $scope.modal.TrustID;
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // TrustSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.TrustSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.checkBeneficariesCount = function () {
        var count = 0;
        angular.forEach($scope.modal.cftBeneficaryList, function (value) {
            if (value.Status != 'D')
                count++;
        });

        if (count == 0 || count == undefined)
            return $scope.modal.cftBeneficaryList.length = 0;
        else
            return $scope.modal.cftBeneficaryList.length;
    };

});
wacorpApp.controller('trusteeRenewalReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Commercial Trust Renewal Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            $location.path("/trusteeRegistration");
        }
        else {
            $scope.modal = $rootScope.modal;
            if ($scope.modal.UBINumber != '' && $scope.modal.UBINumber != undefined) {
                $scope.modal.UBINumber = $scope.modal.UBINumber.replace(/(?!^)(?=(?:\d{3})+(?:\.|$))/gm, ' ');
            }
        }
        $scope.usaCode = usaCode;
    };


    $scope.TrustRenewalAddToCart = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.IsOnline = true;
        $scope.modal.UBINumber = ($scope.modal.UBINumber != null && $scope.modal.UBINumber != '') ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        $scope.modal.UBIJurisdictionId = $scope.modal.JurisdictionCountry == usaCode ? $scope.modal.JurisdictionState : $scope.modal.JurisdictionCountry;
        if (typeof ($scope.modal.PurposeId) != typeof (undefined) && $scope.modal.PurposeId != null) {
            if (angular.isArray($scope.modal.PurposeId) && $scope.modal.PurposeId.length > 0)
                $scope.modal.PurposeId = $scope.modal.PurposeId.join(",");
        }

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // TrusteeAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.TrusteeAddToCart, $scope.modal, function (response) {
            $rootScope.TrustRenewalModal = null;
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
                $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/trusteeRenewal/' + $scope.modal.TrustID);
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }
});

wacorpApp.controller('trusteeSearchController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {
    // declare scope variables
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;

    /* --------Entity Search Functionality------------- */

    $rootScope.trusteeSearchPath = $routeParams.trusteeSearchType;
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        $rootScope.TrustID = $scope.selectedBusiness.TrustID;
        //if ($rootScope.trusteeSearchPath == 'Renewal') {
        //    $location.path('/fundraiserRenewal/' + $scope.selectedBusiness.TrustID);
        //}
        //if ($rootScope.trusteeSearchPath == 'Amendment') {
        //    $location.path('/fundraiserAmendment/' + $scope.selectedBusiness.TrustID);
        //}
        if ($rootScope.trusteeSearchPath == 'Closure') {
            $location.path('/trusteeClosure/' + $scope.selectedBusiness.TrustID);
        }
    }
});



wacorpApp.controller('cftReRegistrationSearchController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, $window) {
    // variable initilization
    $scope.page = constant.ZERO;
    $scope.page1 = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.pagesCount1 = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.States = [];
    $scope.Counties = [];
    $scope.isButtonSerach = false;
    $scope.cftBusinesssearchcriteria = {};
    $scope.cftAdvFeinSearchcriteria = {};
    $scope.criteria = [];
    $scope.cftBusinessSearch = {};
    $rootScope.cftData = {};
    $rootScope.isAdvanceSearch = false;
    $scope.cftOrganizationSearchType = false;
    $scope.showHome = false;
    $scope.isShowAdvanceSearch = false;
    $scope.hideBasicSearch = false;
    $scope.hideSearchButton = false;
    $scope.search = loadCFList;
    var reRegistrationFilingDate = "";
    var Add6YearsFromEffectiveDate = "";
    var MissingRenewalDate = false;  //TFS 2622

    $scope.cftSearchcriteria = {
        Type: searchTypes.RegistrationNumber, EntityName: null, KeyWordSearch: null, PrincipalName: null, PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false,
        RegistrationNumber: null, FEINNo: null, UBINumber: null, PercentToProgramServices: null, SortBy: null, SortType: null,
        PrincipalAddress: {
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
            State: null, OtherState: null, Country: null, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        CFSearchList: []
    };

    $scope.clearCFTSearchcriteria = {
        Type: searchTypes.RegistrationNumber, EntityName: null, KeyWordSearch: null, PrincipalName: null, PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false,
        RegistrationNumber: null, FEINNo: null, UBINumber: null, PercentToProgramServices: null, SortBy: null, SortType: null,
        PrincipalAddress: {
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
            State: null, OtherState: null, Country: null, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        CFSearchList: []
    };

    //scope initialization
    $scope.initCFTSearch = function () {

        $scope.cftOrganizationSearchType = true;
        if ($rootScope.isInitialSearch && $rootScope.data) {
            $scope.cftSearchcriteria = $rootScope.data;
            $cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
            $rootScope.data = null;
        }
        else if ($rootScope.isCftOrganizationSearchBack == true && $rootScope.data) {
            $scope.showAdvanceSearch(); // showAdvanceSearch method is availble in this controller only.
            $scope.cftSearchcriteria = $rootScope.data;
            $cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
            $rootScope.data = null;
        }
        else {
            $scope.page = $scope.page || constant.ZERO;
            $scope.cftSearchcriteria.PageID = $scope.page == constant.ZERO ? constant.ONE : $scope.page + constant.ONE;
        }
        if ($rootScope.isInitialSearch)
            loadCFList(constant.ZERO, false); // loadCFList method is available in this controller only.
        else if ($rootScope.isCftOrganizationSearchBack)
            loadCFList(constant.ZERO, true); // loadCFList method is available in this controller only.

        $scope.messages = messages;
        if ($rootScope.repository.loggedUser != undefined && $rootScope.repository.loggedUser != null) {
            if ($rootScope.repository.loggedUser.userid != undefined && $rootScope.repository.loggedUser.userid != null && $rootScope.repository.loggedUser.userid > 0) {
                $scope.IsUserLogedIn = true;
            }
            else {
                $scope.IsUserLogedIn = false;
            }
        }
        else {
            $scope.IsUserLogedIn = false;
            $scope.showAdvanceSearch(); // showAdvanceSearch method is availble in this controller only.
        }

    }

    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.cftSearchcriteria.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.cftSearchcriteria.UBINumber = pastedText;
            });
        }
    };

    $scope.setUBILength = function (e) {
        //if (e.currentTarget.value.length >= 9) {
        //    e.preventDefault();
        //}
        if (e.currentTarget.value != undefined && e.currentTarget.value.length != null && e.currentTarget.value.length != "" && e.currentTarget.value.length >= 9) {
            if (e.which != 97) {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                    // Allow: Ctrl+A, Command+A
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right, down, up
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
                e.preventDefault();
            }
        }
    };

    $scope.setPastedFEIN = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.cftSearchcriteria.FEINNo = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.cftSearchcriteria.FEINNo = pastedText;
            });
        }
    };

    $scope.setPastedRemoveSpaces = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\s/g, '');
            if (e.originalEvent.currentTarget.name == "OrganizationName")
                $scope.cftSearchcriteria.EntityName = pastedText;
            else if (e.originalEvent.currentTarget.name == "KeywordSearch")
                $scope.cftSearchcriteria.KeyWordSearch = pastedText;
            else if (e.originalEvent.currentTarget.name == "City")
                $scope.cftSearchcriteria.PrincipalAddress.City = pastedText;
            else if (e.originalEvent.currentTarget.name == "Officers")
                $scope.cftSearchcriteria.PrincipalName = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\s/g, '');
                if (e.originalEvent.currentTarget.name == "OrganizationName")
                    $scope.cftSearchcriteria.EntityName = pastedText;
                else if (e.originalEvent.currentTarget.name == "KeywordSearch")
                    $scope.cftSearchcriteria.KeyWordSearch = pastedText;
                else if (e.originalEvent.currentTarget.name == "City")
                    $scope.cftSearchcriteria.PrincipalAddress.City = pastedText;
                else if (e.originalEvent.currentTarget.name == "Officers")
                    $scope.cftSearchcriteria.PrincipalName = pastedText;
            });
        }
    };
    $scope.setPastedRegNumber = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
            $scope.cftSearchcriteria.RegistrationNumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                $scope.cftSearchcriteria.RegistrationNumber = pastedText;
            });
        }
    };

    $scope.setUBILength = function (e) {
        //if ($scope.cftSearchcriteria.UBINumber.length >= 9) {
        //    e.preventDefault();
        //}
        if ($scope.cftSearchcriteria.UBINumber != undefined && $scope.cftSearchcriteria.UBINumber != null && $scope.cftSearchcriteria.UBINumber != "" && $scope.cftSearchcriteria.UBINumber.length >= 9) {
            if (e.which != 97) {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                    // Allow: Ctrl+A, Command+A
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right, down, up
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
                e.preventDefault();
            }
        }
    };

    // search Charity and Fundraiser list
    $scope.searchCF = function (searchform, flag) {
        $scope.isShowErrorFlag = true;
        if ($scope[searchform].$valid) {
            $scope.isShowErrorFlag = false;
            $scope.cftSearchcriteria.IsSearch = true;
            $scope.isButtonSerach = true;
            loadCFList(constant.ZERO, flag); // loadCFList method is available in this controller only.
        }
    };

    // clear fields    
    $scope.clearFun = function () {
        $scope.cftSearchcriteria = $scope.clearCFTSearchcriteria = {
            Type: searchTypes.RegistrationNumber, EntityName: null, KeyWordSearch: null, PrincipalName: null, PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false,
            RegistrationNumber: null, FEINNo: null, UBINumber: null, PercentToProgramServices: null,
            PrincipalAddress: {
                FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                State: null, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
            },
            CFSearchList: []
        };
        $scope.cftSearchcriteria.IsSearch = false;
        $scope.isShowErrorFlag = false;
    };

    $scope.searchAdvFeinData = function (type, value) {
        $scope.cftAdvFeinSearchcriteria.Type = type;
        $scope.cftAdvFeinSearchcriteria.SearchValue = value;
        $('#divAdvCharitiesSearchResult').modal('toggle');
        loadAdvCFeinList(constant.ZERO); // loadAdvCFeinList method is available in this controller only.
    };

    // get Charity and Fundraiser list data from server
    function loadCFList(page, flag, sortBy) {
        var data = new Array();
        $scope.cftSearchcriteria.PageID = page == 0 ? 1 : page + 1;
        if (sortBy != undefined) {
            if ($scope.cftSearchcriteria.SortBy == sortBy) {
                if ($scope.cftSearchcriteria.SortType == 'ASC') {
                    $scope.cftSearchcriteria.SortType = 'DESC';
                } else {
                    $scope.cftSearchcriteria.SortType = 'ASC';
                }
            } else {
                $scope.cftSearchcriteria.SortBy = sortBy;
                $scope.cftSearchcriteria.SortType = 'ASC';
            }
        } else {
            if ($scope.cftSearchcriteria.Type == "RegistrationNumber") {
                if ($scope.cftSearchcriteria.SortBy == null ||
                    $scope.cftSearchcriteria.SortBy == "" ||
                    $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "Registration#";
                if ($scope.cftSearchcriteria.SortType == null ||
                    $scope.cftSearchcriteria.SortType == "" ||
                    $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = 'ASC';
            } else if ($scope.cftSearchcriteria.Type == "FEINNo") {
                if ($scope.cftSearchcriteria.SortBy == null ||
                    $scope.cftSearchcriteria.SortBy == "" ||
                    $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "FEIN#";
                if ($scope.cftSearchcriteria.SortType == null ||
                    $scope.cftSearchcriteria.SortType == "" ||
                    $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = 'ASC';
            } else if ($scope.cftSearchcriteria.Type == "UBINumber") {
                if ($scope.cftSearchcriteria.SortBy == null ||
                    $scope.cftSearchcriteria.SortBy == "" ||
                    $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "UBI#";
                if ($scope.cftSearchcriteria.SortType == null ||
                    $scope.cftSearchcriteria.SortType == "" ||
                    $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = 'ASC';
            } else if ($scope.cftSearchcriteria.Type == "OrganizationName") {
                if ($scope.cftSearchcriteria.SortBy == null ||
                    $scope.cftSearchcriteria.SortBy == "" ||
                    $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "OrganizationName";
                if ($scope.cftSearchcriteria.SortType == null ||
                    $scope.cftSearchcriteria.SortType == "" ||
                    $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = 'ASC';
            }
        }
        data = angular.copy($scope.cftSearchcriteria);
        if (flag == undefined || flag == null)
            flag = $rootScope.flag;
        //$cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
        if (flag) {
            $rootScope.isAdvanceSearch = true;
            $rootScope.isInitialSearch = null;
        } else {
            $rootScope.isInitialSearch = true;
            $rootScope.isAdvanceSearch = null;
        }
        $rootScope.flag = flag;
        $scope.isButtonSerach = page == 0;

        //TFS 1422 Removed for Search
        //TFS 1143 submitting filing means you have said agent consents
        //if (!(typeof $scope.modal === typeof undefined)) {
        //    if (!(typeof $scope.modal.Agent === typeof undefined)) { //TFS 1410
        //        $scope.modal.Agent.IsRegisteredAgentConsent =
        //            true;
        //    }
        //    if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) { //TFS 1410
        //        $scope.modal.IsRegisteredAgentConsent = true;
        //    }
        //}
        //TFS 1143
        //TFS 1422 Removed for Search

        // getCFPublicSearchDetails method is available in constants.js
        wacorpService.post(webservices.CopyRequest.getCFPublicSearchDetails, data, function (response) {
            $scope.cftSearchcriteria.CFSearchList = response.data;
            $cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
            if (response.data.length > constant.ZERO) {
                if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                    var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                    var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                        ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                    $scope.pagesCount = response.data.length < $scope.cftSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount : pagecount;
                    $scope.totalCount = totalcount;
                }
                $scope.page = page;
                $scope.BusinessListProgressBar = false;
                focus("tblCFSearch");
            }

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });

    }


    // search fein details associated to charity
    $scope.searchAdvFein = function (searchform) {
        $scope.cftAdvFeinSearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadAdvCFeinList(searchform); // loadAdvCFeinList method is available in this controller only.
    };


    //to get data for FEIN link
    function loadAdvCFeinList(page) {
        //if ($rootScope.isCftOrganizationSearchBack == true) {
        //    $scope.cftAdvFeinSearchcriteria = $cookieStore.get('cftAdvFeinSearchcriteria');
        //    page = page || constant.ZERO;
        //    $scope.cftAdvFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        //}
        //else {
        page = page || constant.ZERO;
        $scope.cftAdvFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        //$scope.cftFeinSearchcriteria.Type = $scope.criteria.Type;
        //$scope.cftFeinSearchcriteria.SearchValue = $scope.criteria.SearchValue;
        $scope.cftAdvFeinSearchcriteria.SearchCriteria = "";
        //}
        var data = angular.copy($scope.cftAdvFeinSearchcriteria);
        $scope.isButtonSerach = page == 0;

        //TFS 1143 submitting filing means you have said agent consents
        //if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
        //    $scope.modal.Agent.IsRegisteredAgentConsent =
        //        true;
        //}
        //if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
        //    $scope.modal.IsRegisteredAgentConsent = true; 
        //}
        //TFS 1143

        wacorpService.post(webservices.CopyRequest.getCFPublicSearchDetails, data, function (response) {
            $scope.feinDataDetails = response.data;
            if ($scope.cftAdvFeinSearchcriteria.PageID == 1)
                //$('#divAdvCharitiesSearchResult').modal('toggle');
                $cookieStore.put('cftAdvFeinSearchcriteria', $scope.cftAdvFeinSearchcriteria);

            if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                    ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                $scope.pagesCount1 = response.data.length < $scope.cftAdvFeinSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount1 : pagecount;
                $scope.totalCount = totalcount;
            }
            $scope.page1 = page;
            $scope.BusinessListProgressBar = false;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.cancel = function () {
        $("#divAdvCharitiesSearchResult").modal('toggle');
    }

    //navigate to business information
    $scope.showBusineInfo = function (id, businessType, flag) {

        //if (!flag) {
        //    $scope.cftSearchcriteria.CFSearchList.CFTId = id;
        //    $scope.cftSearchcriteria.CFSearchList.Businesstype = businessType;
        //    $rootScope.data = $scope.cftSearchcriteria.CFSearchList;
        //    $rootScope = $scope.cftSearchcriteria;
        //    $rootScope.isAdvanceSearch = true;
        //    $cookieStore.put('cftBusinessSearchListcriteriaId', $scope.cftSearchcriteria.CFSearchList.CFTId);
        //    $cookieStore.put('cftBusinessSearchListcriteriaType', $scope.cftSearchcriteria.CFSearchList.Businesstype);

        //    $scope.navCharityFoundationOrganization();
        //}
        //else {
        //    $scope.cftSearchcriteria.CFSearchList.CFTId = id;
        //    $scope.cftSearchcriteria.CFSearchList.Businesstype = businessType;
        //    $rootScope.isAdvanceSearch = true;
        //    $cookieStore.put('cftBusinessSearchListcriteriaId', $scope.cftSearchcriteria.CFSearchList.CFTId);
        //    $cookieStore.put('cftBusinessSearchListcriteriaType', $scope.cftSearchcriteria.CFSearchList.Businesstype);
        //    $rootScope.data = $scope.cftSearchcriteria.CFSearchList;
        //    $rootScope = $scope.cftSearchcriteria;
        //    $scope.navigate($rootScope.data);
        //}
        if (!flag) {
            $scope.cftSearchcriteria.CFTId = id;
            $scope.cftSearchcriteria.Businesstype = businessType;
            $rootScope.data = $scope.cftSearchcriteria;
            if ($scope.isShowAdvanceSearch) {
                $rootScope.isAdvanceSearch = true;
                $rootScope.isInitialSearch = null;
            }
            else {
                $rootScope.isInitialSearch = true;
                $rootScope.isAdvanceSearch = null;
            }
            //$rootScope.isAdvanceSearch = true;
            //$rootScope.isInitialSearch = true;
            $cookieStore.put('cftBusinessSearchListcriteriaId', $scope.cftSearchcriteria.CFSearchList.CFTId);
            $cookieStore.put('cftBusinessSearchListcriteriaType', $scope.cftSearchcriteria.CFSearchList.Businesstype);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCharityFoundationOrganization();
        }
        else {
            $scope.cftSearchcriteria.CFTId = id;
            $scope.cftSearchcriteria.Businesstype = businessType;
            $rootScope.isAdvanceSearch = true;
            $cookieStore.put('cftBusinessSearchListcriteriaId', $scope.cftSearchcriteria.CFSearchList.CFTId);
            $cookieStore.put('cftBusinessSearchListcriteriaType', $scope.cftSearchcriteria.CFSearchList.Businesstype);
            $rootScope.data = $scope.cftSearchcriteria;

            $scope.navigate($rootScope.data); // navigate method is availble in this controller only.
        }

    }

    $scope.navigate = function (data) {
        $window.sessionStorage.removeItem('orgData');
        var obj = {
            org: data,
            viewMode: true,
            flag: true,
            isAdvanced: true,

        }
        $window.sessionStorage.setItem('orgData', JSON.stringify(obj));
        $window.open('#/organization', "_blank");
        $window.sessionStorage.removeItem('orgData');
    }

    $scope.showAdvanceSearch = function () {
        $scope.isShowAdvanceSearch = true;
        $scope.hideSearchButton = true;
    };

    //$scope.$watch('cftSearchcriteria', function () {
    //    if ($scope.cftSearchcriteria.CFSearchList == undefined)
    //        return;
    //    if ($scope.cftSearchcriteria.CFSearchList.length == constant.ZERO) {
    //        $scope.totalCount = constant.ZERO;
    //        $scope.pagesCount = constant.ZERO;
    //        $scope.totalCount = constant.ZERO;
    //        $scope.page = constant.ZERO;
    //    }
    //}, true);

    $scope.cleartext = function (value) {
        switch (value) {
            case "RegistrationNumber":
                $scope.cftSearchcriteria.EntityName = null;
                $scope.cftSearchcriteria.FEINNo = null;
                $scope.cftSearchcriteria.UBINumber = null;
                $scope.cftSearchcriteria.SortBy = null;
                $scope.cftSearchcriteria.SortType = null;
                break;
            case "FEINNo":
                $scope.cftSearchcriteria.RegistrationNumber = null;
                $scope.cftSearchcriteria.EntityName = null;
                $scope.cftSearchcriteria.UBINumber = null;
                $scope.cftSearchcriteria.SortBy = null;
                $scope.cftSearchcriteria.SortType = null;
                break;
            case "UBINumber":
                $scope.cftSearchcriteria.RegistrationNumber = null;
                $scope.cftSearchcriteria.EntityName = null;
                $scope.cftSearchcriteria.FEINNo = null;
                $scope.cftSearchcriteria.SortBy = null;
                $scope.cftSearchcriteria.SortType = null;
                break;
            case "OrganizationName":
                $scope.cftSearchcriteria.RegistrationNumber = null;
                $scope.cftSearchcriteria.FEINNo = null;
                $scope.cftSearchcriteria.UBINumber = null;
                $scope.cftSearchcriteria.SortBy = null;
                $scope.cftSearchcriteria.SortType = null;
                break;
            default:

        }
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
        $scope.selectedCFTID = business.CFTId;
        $scope.IsSelectedBusinessOptional = business.IsOptionalRegistration;
        $scope.Status = business.Status;
        $scope.OrgType = business.BusinessType;
        //$scope.EffectiveClosureDate = business.EffectiveClosureDate; -- As Per Changes in 16Jan2018
        $scope.RenewalDate = business.RenewalDate;
        reRegistrationFilingDate = new Date();
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        if (wacorpService.dateFormatService($scope.RenewalDate) != null)
            Add6YearsFromEffectiveDate = wacorpService.addYearsToGivenDate($scope.RenewalDate, 6);
        //if (wacorpService.dateFormatService($scope.EffectiveClosureDate) != null)
        //    Add6YearsFromEffectiveDate = wacorpService.addYearsToGivenDate($scope.EffectiveClosureDate, 6);

        //TFS 2622
        //alert("business.RenewalDate: " + business.RenewalDate +
        //    "\r\n" + "business.IsMissingFullYear: " + business.IsMissingFullYear);
        MissingRenewalDate = false;
        if (business.RenewalDate == '0001-01-01T00:00:00'
            || business.IsMissingFullYear  //DevOps 1978 DevOps 2002 Stop Gap, throw exception on short year
        ) {  //No Renewal Date
            //alert('Default Date');
            MissingRenewalDate = true;
        };
        //TFS 2622
    };

    // get Selected Business Details
    $scope.submitBusiness = function () {
        //angular.forEach(CFTStatus, function (value, data) {
        //if ($scope.Status != value.closed && $scope.Status != value.involuntaryClosure) {
        if ($scope.OrgType == "Charity") {
            localStorage.setItem("isOptionalReRegistration", false);
            $rootScope.CharityID = $scope.selectedCFTID;
            if ($scope.Status == "Active" || $scope.Status == "Delinquent") {
                // Folder Name: app Folder
                // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.reregistrationToRenewal);
                //$location.path('/charitiesRenewal/' + $rootScope.CharityID);
            }
            else if ($scope.Status == "Closed" || $scope.Status == "Involuntarily Closed") {
                //TFS 2622
                if (MissingRenewalDate == true) {
                    wacorpService.alertDialog($scope.messages.reregistrationMissingRenewalDate);
                }
                else if (reRegistrationFilingDate > Add6YearsFromEffectiveDate && Add6YearsFromEffectiveDate != "") {
                    //TFS 2622
                    //TFS 2622 Orig Code
                    // if (reRegistrationFilingDate > Add6YearsFromEffectiveDate && Add6YearsFromEffectiveDate!="") {
                    //TFS 2622 Orig Code
                    //Cannot Re-Registrted
                    wacorpService.alertDialog($scope.messages.reregistrationNotAllowed);
                }
                else if ($scope.IsSelectedBusinessOptional) {
                    $rootScope.OptionalData = null;
                    $rootScope.isOptionalReRegistration = true;
                    localStorage.setItem("isOptionalReRegistration", true);
                    $location.path("/charitiesOptionalQualifier");
                }
                else {
                    //wacorpService.alertDialog("It is an Regular Record");
                    $location.path('/charitiesReRegistration/' + $rootScope.CharityID);
                }
            }
            else {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog("Charity Re-Registration is allowed only for Closed and Involuntary Closed Organizations.");
            }
        }
        else if ($scope.OrgType == "Fundraiser") {
            $rootScope.FundraisedID = $scope.selectedCFTID;
            if ($scope.Status == "Active" || $scope.Status == "Delinquent") {
                // Folder Name: app Folder
                // Alert Name: reregistrationToRenewal method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.reregistrationToRenewal);
                //$location.path('/fundraiserRenewal/' + $rootScope.FundraisedID);
            }
            else if ($scope.Status == "Closed" || $scope.Status == "Involuntarily Closed") {
                if (reRegistrationFilingDate > Add6YearsFromEffectiveDate && Add6YearsFromEffectiveDate != "") {
                    //Cannot Re-Registrted
                    // Folder Name: app Folder
                    // Alert Name: reregistrationNotAllowed method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.reregistrationNotAllowed);
                }
                else {
                    $location.path('/fundraiserReRegistration/' + $rootScope.FundraisedID);
                }
            }
            else {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog("Fundraiser Re-Registration is allowed only for Closed and Involuntary Closed Organizations.");
            }
        }
        else if ($scope.OrgType == "Trust") {
            $rootScope.TrustID = $scope.selectedCFTID;
            if ($scope.Status == "Active" || $scope.Status == "Delinquent") {
                // Folder Name: app Folder
                // Alert Name: reregistrationToRenewal method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.reregistrationToRenewal);
                //$location.path('/trusteeRenewal/' + $rootScope.TrustID);
            }
            else if ($scope.Status == "Involuntarily Closed") {
                $location.path('/trustReRegistration/' + $rootScope.TrustID);
            }
            else {
                //Cannot Re-Registrted
                //$scope.messages.reregistrationNotAllowed
                wacorpService.alertDialog("Trust Re-Registration is allowed only for Involuntary Closed Organizations.");
            }
            //Commented on 08/10/2018 based in 11.2 Regression Testing
            //else if ($scope.Status == "Closed") {
            //    //Cannot Re-Registrted
            //    //$scope.messages.reregistrationNotAllowed
            //    wacorpService.alertDialog("Trust Re-Registration is allowed only for Involuntary Closed Organizations.");
            //}
            //else {
            //    $location.path('/trustReRegistration/' + $rootScope.TrustID);
            //}
        }
        //}
        //else {
        //    wacorpService.alertDialog(messages.CFTPublicSearch.alert);
        //}
        //});
    };

});
wacorpApp.controller('charitiesReRegistrationController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------- Charities Amendmenet Functionality------------- */

    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    var originalEntityName = "";
    var isShortFiscalYearChecked = false;
    var isOptionalCharityReRegistration = false;

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.getCharitiesDetails(); // getCharitiesDetails method is available in this controller only.
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    var getShortYearStartDate = function () {
        if ($scope.modal.CurrentEndDateForAmendment != null && typeof ($scope.modal.CurrentEndDateForAmendment) != typeof (undefined)) {
            $scope.modal.shortFiscalYearEntity.FiscalStartDate = "";
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            var startDate = wacorpService.getShortYearStartDate($scope.modal.CurrentEndDateForAmendment);
            $scope.modal.shortFiscalYearEntity.FiscalStartDate = wacorpService.dateFormatService(startDate);
            return $scope.modal.shortFiscalYearEntity.FiscalStartDate;
        }
    };

    var getShortYearEndDate = function () {
        if ($scope.modal.AccountingyearBeginningDate != null && typeof ($scope.modal.AccountingyearBeginningDate) != typeof (undefined)) {
            $scope.modal.shortFiscalYearEntity.FiscalEndDate = "";
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            var endDate = wacorpService.getShortYearEndDate($scope.modal.AccountingyearBeginningDate);
            $scope.modal.shortFiscalYearEntity.FiscalEndDate = wacorpService.dateFormatService(endDate);
            return $scope.modal.shortFiscalYearEntity.FiscalEndDate;
        }
    };

    //Get Charities Details from Registration Number
    $scope.getCharitiesDetails = function () {
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (localStorage.getItem("isOptionalReRegistration") != undefined && localStorage.getItem("isOptionalReRegistration") != null) {
                if (localStorage.getItem("isOptionalReRegistration") == "true") {
                    isOptionalCharityReRegistration = true;
                }
                else {
                    isOptionalCharityReRegistration = false;
                }
            }
            else {
                isOptionalCharityReRegistration = false;
            }
        }
        // here BusinessTypeID = 7 is CHARITABLE ORGANIZATION
        $rootScope.BusinessTypeID = 7;
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 3587 is RE-REGISTRATION
            data = { params: { CharityID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3587, transactionID: $rootScope.transactionID, isOptionalReRegistration: isOptionalCharityReRegistration } };
        else
            data = { params: { CharityID: $routeParams.CharityID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3587, transactionID: $rootScope.transactionID, isOptionalReRegistration: isOptionalCharityReRegistration } };

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/CharitiesSearch');
            }
            // getCharitiesReRegistrationDetails method is available in constants.js
            wacorpService.get(webservices.CFT.getCharitiesReRegistrationDetails, data, function (response) {
                $scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                originalEntityName = $scope.modal.EntityName;
                $scope.modal.UBIOtherDescp = $scope.modal.UBIOtherDescp || null;
                $scope.modal.IsFIFullAccountingYear = true;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
                $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);

                $scope.modal.AccountingyearEndingDateForFAY = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDateForFAY);

                if ($scope.modal.AccountingyearBeginningDate == null || $scope.modal.AccountingyearEndingDate == null) {
                    $scope.modal.IsDatesNull = true;
                }

                if ($scope.modal.IsActiveFilingExist) {
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js 
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }

                if (isOptionalCharityReRegistration == false) {
                    $scope.modal.IsOptionalRegistration = false;
                    $rootScope.OptionalData = null;
                }
                else if (isOptionalCharityReRegistration == true) {
                    $scope.modal.IsOptionalRegistration = true;
                }

                if ($rootScope.OptionalData != null && $rootScope.OptionalData != undefined) {
                    $scope.modal.IsIntegratedAuxiliary = $rootScope.OptionalData.IntegratedAuxiliary == "Yes" ? true : false;
                    $scope.modal.IsPoliticalOrganization = $rootScope.OptionalData.PoliticalOrganization == "Yes" ? true : false;
                    $scope.modal.IsRaisingFundsForIndividual = $rootScope.OptionalData.RaisingFundsForIndividual == "Yes" ? true : false;
                    $scope.modal.IsRaisingLessThan50000 = $rootScope.OptionalData.RaisingLessThan50000 == "Yes" ? true : false;
                    $scope.modal.IsAnyOnePaid = $rootScope.OptionalData.AnyOnePaid == "Yes" ? true : false;
                    $scope.modal.IsInfoAccurate = $rootScope.OptionalData.InfoAccurate == "Yes" ? true : false;
                }
                else {
                    $scope.modal.IsIntegratedAuxiliary = $scope.modal.IsIntegratedAuxiliary;
                    $scope.modal.IsPoliticalOrganization = $scope.modal.IsPoliticalOrganization;
                    $scope.modal.IsRaisingFundsForIndividual = $scope.modal.IsRaisingFundsForIndividual;
                    $scope.modal.IsRaisingLessThan50000 = $scope.modal.IsRaisingLessThan50000;
                    $scope.modal.IsAnyOnePaid = $scope.modal.IsAnyOnePaid;
                    $scope.modal.IsInfoAccurate = $scope.modal.IsInfoAccurate;
                }
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.IsFIFullAccountingYear)
                        $scope.modal.oldFiscalYear = $scope.modal.AccountingyearBeginningDate != '01/01/0001' || $scope.modal.AccountingyearBeginningDate != null ? $scope.modal.AccountingyearBeginningDate : null;
                    else
                        $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingyearEndDate != '01/01/0001' || $scope.modal.FirstAccountingyearEndDate != null ? $scope.modal.FirstAccountingyearEndDate : null;
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }

                $scope.modal.UBINumber = $scope.modal.UBINumber || null;
                $scope.modal.AKANamesList = $scope.modal.AKANamesList || null;
                if ($scope.modal.FederaltaxUpload.length > 0)
                    $scope.modal.FederaltaxUpload.length = 0;
                $scope.modal.OldIsFederalTax = $scope.modal.IsFederalTax;
                $scope.modal.OldIsShowFederalTax = $scope.modal.IsShowFederalTax = false;

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.IsFIFullAccountingYear) {
                        $scope.modal.CurrentStartDateForAmendment = ($scope.modal.AccountingyearBeginningDate != '01/01/0001' || $scope.modal.AccountingyearBeginningDate != null) ? $scope.modal.AccountingyearBeginningDate : null;
                        $scope.modal.CurrentEndDateForAmendment = ($scope.modal.AccountingyearEndingDate != '01/01/0001' || $scope.modal.AccountingyearEndingDate != null) ? $scope.modal.AccountingyearEndingDate : null;
                        $scope.modal.shortFiscalYearEntity.PreviousFiscalStartDate = $scope.modal.AccountingyearBeginningDate;
                        $scope.modal.shortFiscalYearEntity.PreviousFiscalEndDate = $scope.modal.AccountingyearEndingDate;
                    }
                    else {
                        $scope.modal.CurrentEndDateForAmendment = ($scope.modal.FirstAccountingyearEndDate != '01/01/0001' || $scope.modal.FirstAccountingyearEndDate != null) ? $scope.modal.FirstAccountingyearEndDate : null;
                        $scope.modal.shortFiscalYearEntity.PreviousFiscalEndDate = $scope.modal.FirstAccountingyearEndDate;
                    }
                }

                $scope.modal.ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.ContributionServicesTypeId) ? [] : $scope.modal.ContributionServicesTypeId.split(',');
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');

                $scope.modal.CharityAkaInfoEntity.CountiesServedId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CountiesServedId) ? [] : $scope.modal.CharityAkaInfoEntity.CountiesServedId.split(',');
                $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId) ? [] : $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.split(',');
                $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress != null ? $scope.modal.EntityStreetAddress : null;
                $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress != null ? $scope.modal.EntityMailingAddress : null;
                $scope.modal.EntityStreetAddress.IsSameAsEntityMailingAddress = $scope.modal.IsSameAsEntityMailingAddress;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country != null ? $scope.modal.LegalInfo.LegalInfoAddress.Country : codes.USA;

                checkForNAN(); // checkForNAN method is available in this controller only.

                $scope.modal.CFTCorrespondenceAddress.Attention = $scope.modal.CFTCorrespondenceAddress.Attention != null ? $scope.modal.CFTCorrespondenceAddress.Attention : null;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;

                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : "I";
                $scope.modal.LegalInfo.IsAnyLegalActions = $scope.modal.LegalInfo.IsAnyLegalActions || false;
                $scope.modal.LegalInfoEntityList = $scope.modal.LegalInfoEntityList != null ? $scope.modal.LegalInfoEntityList : null;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.shortFiscalYearEntity = wacorpService.shortFisicalYearDataFormat($scope.modal.shortFiscalYearEntity);
                $scope.modal.AKASolicitNameId = '';
                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;

                if ($scope.modal.CFTFinancialHistoryList.length > 0) {
                    angular.forEach($scope.modal.CFTFinancialHistoryList, function (charity) {
                        charity.SequenceNo = charity.FinancialId;
                    });
                }

                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if (!($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == undefined))
                    $scope.modal.JurisdictionCountry = $scope.modal.JurisdictionCountry == 0 ? '' : $scope.modal.JurisdictionCountry.toString();

                if (!($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == undefined))
                    $scope.modal.JurisdictionState = $scope.modal.JurisdictionState == 0 ? '' : $scope.modal.JurisdictionState.toString();

                if (!($scope.modal.FederalTaxExemptId == null || $scope.modal.FederalTaxExemptId == undefined))
                    $scope.modal.FederalTaxExemptId = $scope.modal.FederalTaxExemptId == 0 ? '' : $scope.modal.FederalTaxExemptId.toString();

                if (!($scope.modal.OSJurisdictionCountyId == null || $scope.modal.OSJurisdictionCountyId == undefined))
                    $scope.modal.OSJurisdictionCountyId = $scope.modal.OSJurisdictionCountyId == 0 ? '' : $scope.modal.OSJurisdictionCountyId.toString();

                if (!($scope.modal.OSJurisdictionStateId == null || $scope.modal.OSJurisdictionStateId == undefined))
                    $scope.modal.OSJurisdictionStateId = $scope.modal.OSJurisdictionStateId == 0 ? '' : $scope.modal.OSJurisdictionStateId.toString();

                if ($scope.modal.OfficersHighPayList.length > 0) {
                    angular.forEach($scope.modal.OfficersHighPayList, function (cftHihPay) {
                        cftHihPay.SequenceNo = cftHihPay.ID;
                    });
                }
                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.CFTOfficersList.length > 0) {
                        angular.forEach($scope.modal.CFTOfficersList, function (cftOffice) {
                            cftOffice.SequenceNo = cftOffice.OfficerID;
                        });
                    }
                }


                if ($scope.modal.LegalInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.LegalInfoEntityList, function (cftLegalInfo) {
                        cftLegalInfo.SequenceNo = cftLegalInfo.LegalInfoId;
                    });
                }

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaEntity) {
                        akaEntity.SequenceNo = akaEntity.AKASolicitNameId;
                    });
                }
                if ($scope.modal.FundraisersList.length > 0) {
                    angular.forEach($scope.modal.FundraisersList, function (fundraiser) {
                        fundraiser.SequenceNo = fundraiser.FundRaiserID;
                    });
                }
                if ($scope.modal.AKANamesList.length > 0) {
                    angular.forEach($scope.modal.AKANamesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }

                $scope.modal.isShowReturnAddress = true;
                $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.

            }, function (response) { });
        }
        else {
            var pupose = $rootScope.modal.Purpose;
            $scope.modal = $rootScope.modal;
            $scope.modal.Purpose = pupose;


            //if (localStorage.getItem("isOptionalReRegistration") == "false") {
            //    $scope.modal.IsOptionalRegistration = false;
            //    $rootScope.OptionalData = null;
            //}
            //else if (localStorage.getItem("isOptionalReRegistration") == "true") {
            //    $scope.modal.IsOptionalRegistration = true;
            //}

            if ($rootScope.OptionalData != null && $rootScope.OptionalData != undefined) {
                $scope.modal.IsIntegratedAuxiliary = $rootScope.OptionalData.IntegratedAuxiliary == "Yes" ? true : false;
                $scope.modal.IsPoliticalOrganization = $rootScope.OptionalData.PoliticalOrganization == "Yes" ? true : false;
                $scope.modal.IsRaisingFundsForIndividual = $rootScope.OptionalData.RaisingFundsForIndividual == "Yes" ? true : false;
                $scope.modal.IsRaisingLessThan50000 = $rootScope.OptionalData.RaisingLessThan50000 == "Yes" ? true : false;
                $scope.modal.IsAnyOnePaid = $rootScope.OptionalData.AnyOnePaid == "Yes" ? true : false;
                $scope.modal.IsInfoAccurate = $rootScope.OptionalData.InfoAccurate == "Yes" ? true : false;
            }
            else {
                $scope.modal.IsIntegratedAuxiliary = $scope.modal.IsIntegratedAuxiliary;
                $scope.modal.IsPoliticalOrganization = $scope.modal.IsPoliticalOrganization;
                $scope.modal.IsRaisingFundsForIndividual = $scope.modal.IsRaisingFundsForIndividual;
                $scope.modal.IsRaisingLessThan50000 = $scope.modal.IsRaisingLessThan50000;
                $scope.modal.IsAnyOnePaid = $scope.modal.IsAnyOnePaid;
                $scope.modal.IsInfoAccurate = $scope.modal.IsInfoAccurate;
                //$scope.modal.IsOptionalRegistration = false;
            }

            if ($scope.modal.IsOptionalRegistration == false) {
                localStorage.setItem("isOptionalReRegistration", false);
                $rootScope.OptionalData = null;
            }
            else if ($scope.modal.IsOptionalRegistration == true) {
                localStorage.setItem("isOptionalReRegistration", true);
            }

            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.
            checkForNAN(); // checkForNAN method is available in this controller only.
            $scope.modal.isShowReturnAddress = true;
        }



    };

    var checkForNAN = function () {
        $scope.modal.BeginingGrossAssets = isNaN($scope.modal.BeginingGrossAssets) ? null : $scope.modal.BeginingGrossAssets;
        $scope.modal.EndingGrossAssets = isNaN($scope.modal.EndingGrossAssets) ? null : $scope.modal.EndingGrossAssets;
        $scope.modal.RevenueGDfromSolicitations = isNaN($scope.modal.RevenueGDfromSolicitations) ? null : $scope.modal.RevenueGDfromSolicitations;
        $scope.modal.RevenueGDRevenueAllOtherSources = isNaN($scope.modal.RevenueGDRevenueAllOtherSources) ? null : $scope.modal.RevenueGDRevenueAllOtherSources;
        $scope.modal.ExpensesGDExpendituresProgramServices = isNaN($scope.modal.ExpensesGDExpendituresProgramServices) ? null : $scope.modal.ExpensesGDExpendituresProgramServices;
        $scope.modal.ExpensesGDValueofAllExpenditures = isNaN($scope.modal.ExpensesGDValueofAllExpenditures) ? null : $scope.modal.ExpensesGDValueofAllExpenditures;
        $scope.modal.TotalDollarValueofGrossReceipts = isNaN($scope.modal.TotalDollarValueofGrossReceipts) ? null : $scope.modal.TotalDollarValueofGrossReceipts;
        $scope.modal.PercentToProgramServices = isNaN($scope.modal.PercentToProgramServices) ? null : $scope.modal.PercentToProgramServices;
    };

    $scope.checkHighpayCount = function () {
        var count = 0;
        angular.forEach($scope.modal.OfficersHighPayList, function (highpayItem) {
            if (highpayItem.Status != "D") {
                count++;
            }
        });

        if (count >= 3) {
            $scope.modal.OfficersHighPay.IsCountMax = true;
        }
        else {
            $scope.modal.OfficersHighPay.IsCountMax = false;
        }
        return count <= 0;
    };

    $scope.checkFederalCount = function () {
        var count = 0;
        angular.forEach($scope.modal.FederaltaxUpload, function (value) {
            if (value.Status != 'D')
                count++;
        });
        if (count == 0 || count == undefined)
            return $scope.modal.FederaltaxUpload.length = 0;
        else
            return $scope.modal.FederaltaxUpload.length = count;
    };

    $scope.Review = function (charitiesAmendmentForm) {

        $scope.validateErrorMessage = true;

        //var endDate = $scope.modal.AccountingyearEndingDate;
        //if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
        //    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
        //    if (isEndDateMore) {
        //        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
        //        return false;
        //    }
        //}

        var isOrgNameValid = $scope.modal.EntityName != null ? true : false;

        var isPurposeValid = $scope.modal.Purpose != null ? true : false;

        var isTaxUploadValid = $scope.modal.IsShowFederalTax ? ($scope.checkFederalCount() > 0 ? true : false) : true;

        $scope.EntityNameCheck = true;

        $scope.modal.NewEntityName = $scope.modal.EntityName;

        if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
            if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                $scope.modal.isBusinessNameChanged = true;
            }
            else {
                $scope.modal.isBusinessNameChanged = false;
            }
        }

        var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

        if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
            $scope.EntityNameCheck = false;
        }
        else {
            $scope.EntityNameCheck = true;
        }

        var isEntityInfo = ($scope.charitiesReRegistrationForm.entityInfo.$valid);

        var isExpensesValid = ($scope.modal.IsFIFullAccountingYear ? ($scope.modal.ExpensesGDValueofAllExpenditures != null && $scope.modal.ExpensesGDExpendituresProgramServices != null ? ($scope.modal.ExpensesGDValueofAllExpenditures < $scope.modal.ExpensesGDExpendituresProgramServices ? false : true) : true) : true);

        var isDatesValid = true;//($scope.modal.IsFIFullAccountingYear ? ((new Date($scope.modal.AccountingyearEndingDate) > new Date($scope.modal.AccountingyearBeginningDate)) ? true : false) : true);

        var isCharitiesFinancialInfo = ($scope.charitiesReRegistrationForm.CharityFinancialInfoForm.currentYearFiscalInfo.$valid) && (isDatesValid);

        var isCurrentDatesValid = true;
        if (typeof ($scope.modal.AccountingyearBeginningDate) != typeof (undefined)
                    && $scope.modal.AccountingyearBeginningDate != null) {
            if ($scope.modal.AccountingyearEndingDate && $scope.modal.LastAccountingYearEndDate) {

                if (new Date($scope.modal.AccountingyearBeginningDate) < new Date($scope.modal.LastAccountingYearEndDate && !$scope.modal.IsCurrentYearExistsForReRegistration)) {
                    isCurrentDatesValid = false;
                    $scope.modal.AccEndDateLessThanCurrentYear = true;
                }
                else {
                    isCurrentDatesValid = true;
                    $scope.modal.AccEndDateLessThanCurrentYear = false;
                }
            }
        }

        var isCurrentEndDateValid = true;
        if ($scope.modal.AccountingyearEndingDate != null && $scope.modal.AccountingyearBeginningDate != null) {
            if (new Date($scope.modal.AccountingyearEndingDate) < new Date($scope.modal.AccountingyearBeginningDate)) {
                isCurrentEndDateValid = false;
            }
            else {
                isCurrentEndDateValid = true;
            }
        }

        $scope.checkAccYearVaild = false;
        //if (typeof ($scope.modal.AccountingyearEndingDate) != typeof (undefined) && $scope.modal.AccountingyearEndingDate != null && $scope.modal.AccountingyearEndingDate != "") {
        //    $scope.checkAccYearVaild = wacorpService.checkAccYearEndDateForReg($scope.modal.AccountingyearEndingDate, true);
        //}

        var isOfficerHighpay = !$scope.modal.OfficersHighPay.IsPayOfficers || ($scope.modal.OfficersHighPay.IsPayOfficers && !$scope.checkHighpayCount()); // checkHighpayCount method is available in this controller only.

        var isCftOfficesListValid = ($scope.checkOfficersCount() > 0);

        var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

        var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalActionsUploads.length > 0 ? true : false) : true);

        var isLegalInfo = $scope.modal.isUpdated ? ($scope.charitiesReRegistrationForm.fundraiserLegalInfo.$valid) : true;

        var isFundraiserListValid = true;
        if ($scope.modal.IsCommercialFundraisersContributionsInWA)
            isFundraiserListValid = $scope.modal.FundraisersList.length > 0;

        var Fein = $scope.modal.FEINNumber;
        var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

        var Ubi = $scope.modal.UBINumber;
        // here JurisdictionState = 271 is washington
        var isValidUbi = $scope.modal.IsEntityRegisteredInWA && $scope.modal.JurisdictionState == "271" ?
            (Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9 ? true : false) : (Ubi == null || Ubi == '' || Ubi.length == 9 ? true : false);;

        var isSignatureAttestationValidate = ($scope.charitiesReRegistrationForm.SignatureForm.$valid);
        //var isCorrespondenceAddressValid = $scope.charitiesReRegistrationForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.charitiesReRegistrationForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.charitiesReRegistrationForm.cftCorrespondenceAddressForm.$valid;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

        var isFormValidate = isOrgNameValid && isPurposeValid && isTaxUploadValid && isEntityNameValid && isEntityInfo && isExpensesValid && !$scope.checkAccYearVaild &&
                                isCharitiesFinancialInfo && isOfficerHighpay && isCftOfficesListValid && isLegalActionsListValid && isLegalInfo &&
                                    isCorrespondenceAddressValid && isLegalActionsUploadValid && isFundraiserListValid && isSignatureAttestationValidate &&
                                        isValidFein && isValidUbi && isAdditionalUploadValid && isCurrentEndDateValid;

        $scope.fillAmendmentData(); // fillAmendmentData method is available in this controller only.

        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
            $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
            $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

            $scope.isReview = true;
            $location.path('/charitiesReRegistrationReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        //}
        //else {
        //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
        //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
        //        return false;
        //    }
        //}
    };

    $scope.checkOfficersCount = function () {
        var count = 0;
        angular.forEach($scope.modal.CFTOfficersList, function (value) {
            if (value.OfficerStatus != 'D')
                count++;
        });

        if (count == 0 || count == undefined)
            return $scope.modal.CFTOfficersList.length = 0;
        else
            return $scope.modal.CFTOfficersList.length;
    };

    $scope.fillAmendmentData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.EntityName = $scope.modal.EntityName || null;
        $scope.modal.FinancialId = $scope.modal.FinancialId || null;
        if ($scope.modal.IsFIFullAccountingYear)
            $scope.modal.oldFiscalYear = $scope.modal.AccountingyearBeginningDate != '01/01/0001' || $scope.modal.AccountingyearBeginningDate != null ? $scope.modal.AccountingyearBeginningDate : null;
        else
            $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingyearEndDate != '01/01/0001' || $scope.modal.FirstAccountingyearEndDate != null ? $scope.modal.FirstAccountingyearEndDate : null;

        $scope.modal.OSJurisdictionId = $scope.modal.OSJurisdictionStateId != "" ? $scope.modal.OSJurisdictionStateId : $scope.modal.OSJurisdictionCountyId;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }

        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }

        if ($scope.modal.CharityAkaInfoEntity.CountiesServedId != null && $scope.modal.CharityAkaInfoEntity.CountiesServedId.length > 0) {
            $scope.modal.CharityAkaInfoEntity.CountiesServedId = $scope.modal.CharityAkaInfoEntity.CountiesServedId.join(",");
        }
        if ($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId != null && $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.length > 0) {
            $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.join(",");
        }

        if ($scope.modal.OfficersHighPayList != null && $scope.modal.OfficersHighPayList.length == 3)
            $scope.modal.OfficersHighPay.IsCountMax = true;

        if ($scope.modal.CharityAkaInfoEntityList != null && $scope.modal.CharityAkaInfoEntityList.length > 0) {
            angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                if (akaInfo.CountiesServedId != null && akaInfo.CountiesServedId.length > 0)
                    akaInfo.CountiesServedId = akaInfo.CountiesServedId.join(",");
                if (akaInfo.CategoryOfServiceId != null && akaInfo.CategoryOfServiceId.length > 0)
                    akaInfo.CategoryOfServiceId = akaInfo.CategoryOfServiceId.join(",");
            });
        }
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        // Service Folder: services
        // File Name: wacorpService.js (you can search with file name in solution explorer)
        $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
        $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
        $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

        $scope.modal.EntityStreetAddress.IsAddressSame = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName;
        $scope.modal.IsCommercialFundraisersContributionsInWA = $scope.modal.IsCommercialFundraisersContributionsInWA;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;

        $scope.modal.BeginingGrossAssets = ($scope.modal.BeginingGrossAssets == null) ? null : $scope.modal.BeginingGrossAssets;
        $scope.modal.EndingGrossAssets = ($scope.modal.EndingGrossAssets == null) ? null : $scope.modal.EndingGrossAssets;
        $scope.modal.RevenueGDfromSolicitations = ($scope.modal.RevenueGDfromSolicitations == null) ? null : $scope.modal.RevenueGDfromSolicitations;
        $scope.modal.RevenueGDRevenueAllOtherSources = ($scope.modal.RevenueGDRevenueAllOtherSources == null) ? null : $scope.modal.RevenueGDRevenueAllOtherSources;
        $scope.modal.ExpensesGDExpendituresProgramServices = ($scope.modal.ExpensesGDExpendituresProgramServices == null) ? null : $scope.modal.ExpensesGDExpendituresProgramServices;
        $scope.modal.ExpensesGDValueofAllExpenditures = ($scope.modal.ExpensesGDValueofAllExpenditures == null) ? null : $scope.modal.ExpensesGDValueofAllExpenditures;
        $scope.modal.TotalDollarValueofGrossReceipts = ($scope.modal.TotalDollarValueofGrossReceipts == null) ? null : $scope.modal.TotalDollarValueofGrossReceipts;
        $scope.modal.PercentToProgramServices = ($scope.modal.PercentToProgramServices == null) ? null : $scope.modal.PercentToProgramServices;

        //if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
        //    $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $rootScope.modal = $scope.modal;
    };

    $scope.AmendSaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillAmendmentData(); // fillAmendmentData method is available in this controller only.
        $scope.modal.OnlineNavigationUrl = "/charitiesReRegistration";
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    $scope.RenewalBack = function () {

        $scope.fillAmendmentData(); // fillAmendmentData method is available in this controller only.
        var optioanlData = {
            IntegratedAuxiliary: $scope.modal.IsIntegratedAuxiliary ? "Yes" : "No",
            PoliticalOrganization: $scope.modal.IsPoliticalOrganization ? "Yes" : "No",
            RaisingFundsForIndividual: $scope.modal.IsRaisingFundsForIndividual ? "Yes" : "No",
            RaisingLessThan50000: $scope.modal.IsRaisingLessThan50000 ? "Yes" : "No",
            AnyOnePaid: $scope.modal.IsAnyOnePaid ? "Yes" : "No",
            InfoAccurate: $scope.modal.IsInfoAccurate ? "Yes" : "No",
        };
        $rootScope.OptionalData = optioanlData;
        $rootScope.isOptionalReRegistration = true;
        $rootScope.CharityID = $scope.modal.CFTId;
        localStorage.setItem("IsBack", true);
        $location.path("/charitiesOptionalQualifier");

    };

});

wacorpApp.controller('charitiesReRegistrationReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Charities Registration Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        $scope.modal = $rootScope.modal;
    };

    $scope.CharitiesAmendmentAddToCart = function () {

        if ($scope.modal.ContributionServicesTypeId!=null && $scope.modal.ContributionServicesTypeId.length > 0)
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");

        if ($scope.modal.FinancialInfoStateId!=null && $scope.modal.FinancialInfoStateId.length > 0)
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // CharitiesAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.CharitiesAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
                $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
            $rootScope.modal = null;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/charitiesReRegistration');
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

});

wacorpApp.controller('fundraiserReRegistrationController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Entity Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    var originalEntityName = "";

    function getNavigation() {
        if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.Status) >= constant.ZERO) {
            $rootScope.FundRaiserID = $scope.selectedBusiness.FundRaiserID;
            $rootScope.fundraiserAmendmentModal = null;
            $rootScope.transactionID = null;
            $location.path('/FundraiserSearch/' + $scope.selectedBusiness.FundRaiserID);
        }
        else {
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog(messages.selectedEntity.replace('{0}', $scope.selectedBusiness.Status));
        }
    }


    /* --------Commercial Fundraiser Amendment Functionality------------- */
    // scope variables
    $scope.modal = {
        SignatureAttestation: {},
        CFTFinancialHistoryList :[]
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    //// page load
    $scope.Init = function () {
        $scope.messages = messages;
        // here BusinessTypeID = 10 is COMMERCIAL FUNDRAISER
        $rootScope.BusinessTypeID = 10;
        //get business information
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 3588 is RE-REGISTRATION
            data = { params: { fundraiserID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3588, transactionID: $rootScope.transactionID } };
        else
            data = { params: { fundraiserID: $routeParams.FundraisedID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3588, transactionID: $rootScope.transactionID } };

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/cftReRegistration');
            }
            // getFundraiserReRegistrationDetails method is available in constants.js
            wacorpService.get(webservices.CFT.getFundraiserReRegistrationDetails, data, function (response) {
                angular.copy(response.data, $scope.modal);
                //$scope.modal = response.data;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                //$scope.modal.BusinessTransaction.BusinessName = $scope.modal.EntityName || null;
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                $scope.modal.HasOrganizationCompletedFullAccountingYear = true;
                originalEntityName = $scope.modal.EntityName;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingYearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingYearBeginningDate);
                $scope.modal.AccountingYearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingYearEndingDate);
                $scope.modal.AccountingyearEndingDateForFAY = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDateForFAY);

                $scope.modal.FirstAccountingYearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingYearEndDate);
                $scope.modal.BondWaiversBondExpirationDate = wacorpService.dateFormatService($scope.modal.BondWaiversBondExpirationDate);
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                checkForNAN(); // checkForNAN method is available in this controller only.

                if ($scope.modal.AccountingYearBeginningDate == null || $scope.modal.AccountingYearEndingDate == null) {
                    $scope.modal.IsDatesNull = true;
                }

                if ($scope.modal.IsActiveFilingExist) {
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js 
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                $scope.modal.ContributionServicesTypeId = angular.isNullorEmpty($scope.modal.ContributionServicesTypeId) ? [] : $scope.modal.ContributionServicesTypeId.split(',');
                $scope.modal.FinancialInfoStateId = angular.isNullorEmpty($scope.modal.FinancialInfoStateId) ? [] : $scope.modal.FinancialInfoStateId.split(',');

                $scope.modal.CharityAkaInfoEntity.CountiesServedId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CountiesServedId) ? [] : $scope.modal.CharityAkaInfoEntity.CountiesServedId.split(',');
                $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId = angular.isNullorEmpty($scope.modal.CharityAkaInfoEntity.CategoryOfServiceId) ? [] : $scope.modal.CharityAkaInfoEntity.CategoryOfServiceId.split(',');
                //$scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
                //$scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.County = $scope.modal.EntityStreetAddress.County != null ? $scope.modal.EntityStreetAddress.County : "";
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country != null ? $scope.modal.LegalInfo.LegalInfoAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';
                $scope.modal.AKASolicitNameId = '';
                //$scope.modal.isUpdated = $scope.modal.HasOrganizationCompletedFullAccountingYear == true ? true : false;

                //Empty the Previous Financials
                //if (!$rootScope.IsShoppingCart) {
                //    //$scope.modal.isUpdated = false;
                //    $scope.modal.AllContributionsReceived = null;
                //    $scope.modal.AveragePercentToCharity = null;
                //    $scope.modal.AmountOfFunds = null;
                //}

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }
                //$scope.modal.IsOrgNameExists = $scope.modal.EntityName != null && $scope.modal.FEINNumber != "" && $scope.modal.FEINNumber != null || $scope.modal.UBINumber != null && $scope.modal.UBINumber != "" && $scope.modal.EntityName != "" ? true : false;

                $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;

                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;

                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';

                if ($scope.modal.CharityAkaInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.CharityAkaInfoEntityList, function (akaInfo) {
                        akaInfo.CountiesServedId = angular.isNullorEmpty(akaInfo.CountiesServedId) ? [] : akaInfo.CountiesServedId.split(',');
                        akaInfo.CategoryOfServiceId = angular.isNullorEmpty(akaInfo.CategoryOfServiceId) ? [] : akaInfo.CategoryOfServiceId.split(',');
                    });
                }

                if ($scope.modal.UploadOverrideList.length > 0) {
                    angular.forEach($scope.modal.UploadOverrideList, function (ovrdData) {
                        ovrdData.SequenceNo = ovrdData.ID;
                    });
                }

                if ($scope.modal.OfficersHighPayList.length > 0) {
                    angular.forEach($scope.modal.OfficersHighPayList, function (cftHihPay) {
                        cftHihPay.SequenceNo = cftHihPay.ID;
                    });
                }

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.CFTOfficersList.length > 0) {
                        angular.forEach($scope.modal.CFTOfficersList, function (cftOffice) {
                            cftOffice.SequenceNo = cftOffice.OfficerID;
                        });
                    }
                }


                if ($scope.modal.LegalInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.LegalInfoEntityList, function (cftLegalInfo) {
                        cftLegalInfo.SequenceNo = cftLegalInfo.LegalInfoId;
                    });
                }

                //if (!$rootScope.IsShoppingCart) {
                //    if ($scope.modal.CFTFinancialHistoryList.length > 0) {
                //        $scope.modal.CFTFinancialHistoryList.splice(0, 1);
                //    }
                //}

                if ($scope.modal.CFTFinancialHistoryList.length > 0) {
                    angular.forEach($scope.modal.CFTFinancialHistoryList, function (fundraiser) {
                        fundraiser.SequenceNo = fundraiser.FinancialId;
                    });
                }

                if ($scope.modal.AKANamesList.length > 0) {
                    angular.forEach($scope.modal.AKANamesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }

                if ($scope.modal.CharitiesList.length > 0) {
                    angular.forEach($scope.modal.CharitiesList, function (akaName) {
                        akaName.SequenceNo = akaName.ID;
                    });
                }
                $scope.modal.isShowReturnAddress = true;
                $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.
            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
            $scope.checkHighpayCount(); // checkHighpayCount method is available in this controller only.
            checkForNAN(); // checkForNAN method is available in this controller only.
            $scope.modal.isShowReturnAddress = true;
        }
    };

    var checkForNAN = function () {
        $scope.modal.AllContributionsReceived = isNaN($scope.modal.AllContributionsReceived) ? null : $scope.modal.AllContributionsReceived;
        $scope.modal.AveragePercentToCharity = isNaN($scope.modal.AveragePercentToCharity) ? null : $scope.modal.AveragePercentToCharity;
        $scope.modal.AmountOfFunds = isNaN($scope.modal.AmountOfFunds) ? null : $scope.modal.AmountOfFunds;
    };

    $scope.checkHighpayCount = function () {
        var count = 0;
        angular.forEach($scope.modal.OfficersHighPayList, function (highpayItem) {
            if (highpayItem.Status != "D") {
                count++;
            }
        });

        if (count >= 3) {
            $scope.modal.OfficersHighPay.IsCountMax = true;
        }
        else {
            $scope.modal.OfficersHighPay.IsCountMax = false;
        }
        return count <= 0;
    };

    $scope.FundraiserValidateEndDate = function () {
        return (new Date($scope.modal.AccountingYearEndingDate) < new Date($scope.modal.AccountingYearBeginningDate));
    };

    $scope.Review = function (FundraiserAmendmentForm) {
        $scope.validateErrorMessage = true;

        //var endDate = $scope.modal.AccountingYearEndingDate;
        //if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
        //    // Service Folder: services
        //    // File Name: wacorpService.js (you can search with file name in solution explorer)
        //    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
        //    if (isEndDateMore) {
        //        // Folder Name: app Folder
        //        // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js
        //        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
        //        return false;
        //    }
        //}

        //if ($scope.modal.UBINumber == null || $scope.modal.UBINumber == "" || !$scope.modal.IsUbiAssociated) {
        var isOrgNameValid = $scope.modal.EntityName != null && $scope.modal.EntityName != "" ? true : false;

        var isEntityInfo = ($scope.commercialFundraiserReRegistrationForm.entityInfo.$valid);

        $scope.EntityNameCheck = true;

        $scope.modal.NewEntityName = $scope.modal.EntityName;

        if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
            if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                $scope.modal.isBusinessNameChanged = true;
            }
            else {
                $scope.modal.isBusinessNameChanged = false;
            }
        }

        var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

        if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
            $scope.EntityNameCheck = false;
        }
        else {
            $scope.EntityNameCheck = true;
        }

        var isAddressUpload = ($scope.modal.IsUploadAddress) ? ($scope.modal.UploadListOfAddresses.length > 0 ? true : false) : true;

        var isOrgSubmittedSOSProof = ($scope.modal.IsBondWaiverSubmittedProofOfSurety) ? true : ($scope.modal.BondWaiversSOSBondUploadList.length > 0 ? true : false);

        var isJurisdictionValid = ($scope.modal.JurisdictionState != NaN && $scope.modal.JurisdictionState != null && $scope.modal.JurisdictionState != undefined && $scope.modal.JurisdictionState != "") ? true : false;

        //var isBondWaiver = ($scope.modal.IsBondWaiver) ? ($scope.modal.BondWaiversUploadedSuretyBondsList.length > 0 ? true : false) : true;

        var isCollectedContributions = ($scope.modal.IsOrganizationCollectedContributionsInWA) ? (($scope.modal.ContributionServicesTypeId == null || $scope.modal.ContributionServicesTypeId == undefined || $scope.modal.ContributionServicesTypeId == "") ? false : true) : true;

        var isRegisteredOutside = ($scope.modal.IsRegisteredOutSideOfWashington) ? (($scope.modal.FinancialInfoStateId == null || $scope.modal.FinancialInfoStateId == undefined || $scope.modal.FinancialInfoStateId == "") ? false : true) : true;

        var isOfficerHighPay = ($scope.modal.OfficersHighPayList.length > 0) ? true : false;

        var isExpensesValid = ($scope.modal.AllContributionsReceived < $scope.modal.AmountOfFunds ? false : true);

        var isDatesValid = true;//($scope.modal.HasOrganizationCompletedFullAccountingYear ? ((new Date($scope.modal.AccountingYearEndingDate) > new Date($scope.modal.AccountingYearBeginningDate)) ? true : false) : true);

        var isCharitiesFinancialInfo = ($scope.commercialFundraiserReRegistrationForm.fundraiserFinancialInfo.currentFinInfo.$valid) && (isDatesValid);

        var isCurrentDatesValid = true;
        if (typeof ($scope.modal.AccountingYearBeginningDate) != typeof (undefined)
                    && $scope.modal.AccountingYearBeginningDate != null) {
            if ($scope.modal.AccountingYearEndingDate && $scope.modal.LastAccountingYearEndDate) {

                if (new Date($scope.modal.AccountingYearBeginningDate) < new Date($scope.modal.LastAccountingYearEndDate) && !$scope.modal.IsCurrentYearExistsForReRegistration) {
                    isCurrentDatesValid = false;
                    $scope.modal.AccEndDateLessThanCurrentYear = true;
                }
                else {
                    isCurrentDatesValid = true;
                    $scope.modal.AccEndDateLessThanCurrentYear = false;
                }
            }
        }

        var isCurrentEndDateValid = true;
        if ($scope.modal.AccountingYearEndingDate != null && $scope.modal.AccountingYearBeginningDate != null) {
            if (new Date($scope.modal.AccountingYearEndingDate) < new Date($scope.modal.AccountingYearBeginningDate)) {
                isCurrentEndDateValid = false;
            }
            else {
                isCurrentEndDateValid = true;
            }
        }

        $scope.checkAccYearVaild = false;
        //if (typeof ($scope.modal.AccountingYearEndingDate) != typeof (undefined) && $scope.modal.AccountingYearEndingDate != null && $scope.modal.AccountingYearEndingDate != "") {
        //    $scope.checkAccYearVaild = wacorpService.checkAccYearEndDateForReg($scope.modal.AccountingYearEndingDate, true);
        //}

        var isCftOfficesListValid = ($scope.checkOfficersCount() > 0);

        var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

        var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.UploadSurityBondList.length > 0 ? true : false) : true);

        var isLegalInfo = ($scope.commercialFundraiserReRegistrationForm.fundraiserLegalInfo.$valid);

        var isFundraiserListValid = true;
        if ($scope.modal.IsCommercialFundraisersContributionsInWA)
            isFundraiserListValid = $scope.modal.FundraisersList.length > 0;

        var Fein = $scope.modal.FEINNumber;
        var isValidFein = Fein == null || Fein == '' ? false : Fein.replace(/-/g, '').length == 9;

        var Ubi = $scope.modal.UBINumber;
        var isValidUbi = true;
        //if (!$scope.modal.IsFundraiserOverrideMandetoryReq) {
        //isValidUbi = (Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9) ? true : false;
        isValidUbi = $scope.modal.IsFundraiserOverrideMandetoryReq ? true : ((Ubi != null && Ubi != '' && Ubi != undefined && Ubi.length == 9) ? true : false);
        //}

        var isSignatureAttestationValidate = ($scope.commercialFundraiserReRegistrationForm.SignatureForm.$valid);
        //var isCorrespondenceAddressValid = $scope.commercialFundraiserReRegistrationForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.commercialFundraiserReRegistrationForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
        var isCorrespondenceAddressValid = $scope.commercialFundraiserReRegistrationForm.cftCorrespondenceAddressForm.$valid;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

        var isFormValidate = isOrgNameValid && isEntityInfo && isAddressUpload && !$scope.checkAccYearVaild && isJurisdictionValid
                                && isOrgSubmittedSOSProof && isCharitiesFinancialInfo && isCftOfficesListValid
                                   && isLegalActionsListValid && isLegalActionsUploadValid && isEntityNameValid && isCurrentEndDateValid
                                        && isFundraiserListValid && isCollectedContributions && isExpensesValid
                                            && isRegisteredOutside && isOfficerHighPay && isSignatureAttestationValidate && isValidFein && isValidUbi && isLegalInfo && isAdditionalUploadValid && isCorrespondenceAddressValid;
        $scope.fillRegData();

        if (isFormValidate) {
            $scope.validateErrorMessage = false;
            $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
            $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
            $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

            $rootScope.modal = $scope.modal;
            $location.path('/fundraiserReRegistrationReview');
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        //}
        //else {
        //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
        //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
        //        return false;
        //    }
        //}
    };

    $scope.checkOfficersCount = function () {
        var count = 0;
        angular.forEach($scope.modal.CFTOfficersList, function (value) {
            if (value.OfficerStatus != 'D')
                count++;
        });

        if (count == 0 || count == undefined)
            return $scope.modal.CFTOfficersList.length = 0;
        else
            return $scope.modal.CFTOfficersList.length;
    };

    $scope.fillRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.FinancialId = $scope.modal.FinancialId || null;

        //if ($scope.modal.HasOrganizationCompletedFullAccountingYear)
        //    $scope.modal.oldFiscalYear = $scope.modal.AccountingYearBeginningDate != '01/01/0001' || $scope.modal.AccountingYearBeginningDate != null ? $scope.modal.AccountingYearBeginningDate : null;
        //else
        //    $scope.modal.oldFiscalYear = $scope.modal.FirstAccountingYearEndDate != '01/01/0001' || $scope.modal.FirstAccountingYearEndDate != null ? $scope.modal.FirstAccountingYearEndDate : null;

        //Organization Information
        $scope.modal.EntityName = $scope.modal.EntityName != null && $scope.modal.EntityName != '' ? $scope.modal.EntityName : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        //$scope.modal.UBINumber = $scope.modal.UBINumber.replace(/\s/g, '');
        $scope.modal.RegistrationNumber = $scope.modal.RegistrationNumber || null;
        //$scope.modal.IsEntityRegisteredInWA = false;
        //$scope.modal.IsFundraiserOverrideMandetoryReq = $scope.modal.IsFundraiserOverrideMandetoryReq;
        //$scope.modal.IsFundraiserOverrideMandetoryReq = false;
        $scope.modal.HotList = false;
        $scope.modal.AttorneyGeneral = false;
        $scope.modal.AKANamesList = angular.isNullorEmpty($scope.modal.AKANamesList) ? [] : $scope.modal.AKANamesList;
        //$scope.modal.JurisdictionState = "";
        //$scope.modal.JurisdictionStateDesc = "";
        //$scope.modal.UploadOverrideList = angular.isNullorEmpty($scope.modal.UploadOverrideList) ? [] : $scope.modal.UploadOverrideList;
        //$scope.modal.UploadOverrideList = [];

        //Contact information
        $scope.modal.EntityEmailAddress = $scope.modal.EntityEmailAddress != null && $scope.modal.EntityEmailAddress != '' ? $scope.modal.EntityEmailAddress : null;
        $scope.modal.EntityConfirmEmailAddress = $scope.modal.EntityConfirmEmailAddress != null && $scope.modal.EntityConfirmEmailAddress != '' ? $scope.modal.EntityConfirmEmailAddress : null;
        $scope.modal.EntityWebsite = $scope.modal.EntityWebsite != null && $scope.modal.EntityWebsite != '' ? $scope.modal.EntityWebsite : null;
        $scope.modal.IsForeignContact = $scope.modal.IsForeignContact;
        $scope.modal.CountryCode = $scope.modal.CountryCode || null;
        $scope.modal.EntityPhoneNumber = $scope.modal.EntityPhoneNumber;
        $scope.modal.PhoneExtension = $scope.modal.PhoneExtension
        $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
        $scope.modal.IsSameasStreetAddr = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
        $scope.modal.IsUploadAddress = $scope.modal.IsUploadAddress;
        //$scope.modal.UploadListOfAddresses = angular.isNullorEmpty($scope.modal.UploadListOfAddresses) ? [] : $scope.modal.UploadListOfAddresses;

        //Surety Bond
        $scope.modal.IsBondWaiverSubmittedProofOfSurety = $scope.modal.IsBondWaiverSubmittedProofOfSurety;
        $scope.modal.BondWaiversSOSBondUploadList = angular.isNullorEmpty($scope.modal.BondWaiversSOSBondUploadList) ? [] : $scope.modal.BondWaiversSOSBondUploadList;
        $scope.modal.BondWaiversBondExpirationDate = $scope.modal.BondWaiversBondExpirationDate;
        //$scope.modal.IsBondWaiver = $scope.modal.IsBondWaiver;
        //$scope.modal.IsBondWaiver = false;
        //$scope.modal.BondWaiversUploadedSuretyBondsList = angular.isNullorEmpty($scope.modal.BondWaiversUploadedSuretyBondsList) ? [] : $scope.modal.BondWaiversUploadedSuretyBondsList;
        //$scope.modal.BondWaiversUploadedSuretyBondsList = [];

        //Financial Information
        $scope.modal.HasOrganizationCompletedFullAccountingYear = $scope.modal.HasOrganizationCompletedFullAccountingYear;
        $scope.modal.AccountingYearBeginningDate = $scope.modal.AccountingYearBeginningDate;
        $scope.modal.AccountingYearEndingDate = $scope.modal.AccountingYearEndingDate;
        $scope.modal.FirstAccountingYearEndDate = $scope.modal.FirstAccountingYearEndDate;

        $scope.modal.AllContributionsReceived = ($scope.modal.AllContributionsReceived == null) ? null : $scope.modal.AllContributionsReceived;
        $scope.modal.AveragePercentToCharity = ($scope.modal.AveragePercentToCharity == null) ? null : $scope.modal.AveragePercentToCharity;
        $scope.modal.AmountOfFunds = ($scope.modal.AmountOfFunds == null) ? null : $scope.modal.AmountOfFunds;

        $scope.modal.SolicitationComments = $scope.modal.SolicitationComments;
        $scope.modal.IsOrganizationCollectedContributionsInWA = $scope.modal.IsOrganizationCollectedContributionsInWA;
        if ($scope.modal.ContributionServicesTypeId != null && $scope.modal.ContributionServicesTypeId.length > 0 && angular.isArray($scope.modal.ContributionServicesTypeId)) {
            $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }
        $scope.modal.IsRegisteredOutSideOfWashington = $scope.modal.IsRegisteredOutSideOfWashington;
        if ($scope.modal.FinancialInfoStateId != null && $scope.modal.FinancialInfoStateId.length > 0 && angular.isArray($scope.modal.FinancialInfoStateId)) {
            $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }
        if ($scope.modal.OfficersHighPayList.length > 0) {
            $scope.modal.OfficersHighPay.IsPayOfficers = true;
        } else {
            $scope.modal.OfficersHighPay.IsPayOfficers = false;
        }

        //Person Accepting Responsibility
        $scope.modal.IsSameAsAddressContactInfo = $scope.modal.IsSameAsAddressContactInfo;
        //$scope.modal.CFTOfficersList = angular.isNullorEmpty($scope.modal.CFTOfficersList) ? [] : $scope.modal.CFTOfficersList;

        //Financial Preparer
        $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID;
        $scope.modal.LegalInfo.FirstName = $scope.modal.LegalInfo.FirstName || null;
        $scope.modal.LegalInfo.LastName = $scope.modal.LegalInfo.LastName || null;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName || null;
        $scope.modal.LegalInfo.EntityRepresentativeFirstName = $scope.modal.LegalInfo.EntityRepresentativeFirstName || null;
        $scope.modal.LegalInfo.EntityRepresentativeLastName = $scope.modal.LegalInfo.EntityRepresentativeLastName || null;
        $scope.modal.LegalInfo.Title = $scope.modal.LegalInfo.Title || null;
        $scope.modal.LegalInfo.LegalInfoAddress = $scope.modal.LegalInfo.LegalInfoAddress || null;
        $scope.modal.LegalInfo.IsAnyLegalActions = $scope.modal.LegalInfo.IsAnyLegalActions;
        //CFR Sub’s
        $scope.modal.IsCommercialFundraisersContributionsInWA = $scope.modal.IsCommercialFundraisersContributionsInWA;
        //Filing Correspondence
        $scope.modal.CFTAttention = $scope.modal.CFTAttention;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        //Attestation
        $scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;

        $rootScope.modal = $scope.modal;
    };

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillRegData();
        $scope.modal.OnlineNavigationUrl = "/fundraiserReRegistration";
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // FundraiserSaveandClose method is available in constants.js
        wacorpService.post(webservices.CFT.FundraiserSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});
wacorpApp.controller('fundraiserReRegistrationReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Commercial Fundraiser Amendment Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            $location.path("/fundraiserReRegistration");
        }
        else {
            $scope.modal = $rootScope.modal;
            if ($scope.modal.UBINumber != '' && $scope.modal.UBINumber != undefined) {
                $scope.modal.UBINumber = $scope.modal.UBINumber.replace(/(?!^)(?=(?:\d{3})+(?:\.|$))/gm, ' ');
            }
        }
        //$scope.modal = $rootScope.Modal;
        $scope.usaCode = usaCode;
    };


    $scope.FundraiserAmendmentAddToCart = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = ($scope.modal.UBINumber != null && $scope.modal.UBINumber != '') ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        if ($scope.modal.IsOrganizationCollectedContributionsInWA && ($scope.modal.ContributionServicesTypeId != null || $scope.modal.ContributionServicesTypeId != undefined)) {
            if ($scope.modal.ContributionServicesTypeId.length > 0 && angular.isArray($scope.modal.ContributionServicesTypeId))
                $scope.modal.ContributionServicesTypeId = $scope.modal.ContributionServicesTypeId.join(",");
        }

        if ($scope.modal.IsRegisteredOutSideOfWashington && ($scope.modal.FinancialInfoStateId != null || $scope.modal.FinancialInfoStateId != undefined)) {
            if ($scope.modal.FinancialInfoStateId.length > 0 && angular.isArray($scope.modal.FinancialInfoStateId))
                $scope.modal.FinancialInfoStateId = $scope.modal.FinancialInfoStateId.join(",");
        }

        $scope.modal.IsOnline = true;

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // FundraiserAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.FundraiserAddToCart, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
            $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/fundraiserReRegistration/' + $scope.modal.FundRaiserID);
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

});

wacorpApp.controller('trusteeReRegistrationController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    var originalEntityName = "";

    function getNavigation() {
        //if ([ResultStatus.ACTIVE, ResultStatus.DELINQUENT].indexOf($scope.selectedBusiness.Status) >= constant.ZERO) {
        $rootScope.TrustID = $scope.selectedBusiness.TrustID;
        $rootScope.trusteeRenewalModal = null;
        $rootScope.transactionID = null;
        $location.path('/TrusteeRenewalSearch/' + $scope.selectedBusiness.TrustID);
        //}
        //else {
        //    wacorpService.alertDialog(messages.selectedEntity.replace('{0}', $scope.selectedBusiness.Status));
        //}
    }


    /* --------Commercial Trust Renewal Functionality------------- */
    // scope variables
    $scope.modal = {
        SignatureAttestation: {}
    };
    $scope.validateErrorMessage = false;
    $scope.isShowContinue = true;
    $scope.isReview = false;
    $scope.OfficersCount = false;

    var getIRSDocumentList = function () {
        lookupService.irsDocumentsList(function (response) { $scope.IRSDocumentTypes = response.data; });
    };

    //// page load
    $scope.Init = function () {
        getIRSDocumentList();
        $scope.messages = messages;
        $rootScope.BusinessTypeID = 8;
        //get business information
        var data = null;
        if ($rootScope.transactionID > 0)
            data = { params: { trustID: null, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3589, transactionID: $rootScope.transactionID } };
        else
            data = { params: { trustID: $routeParams.TrustID, businessTypeID: $rootScope.BusinessTypeID, filingTypeID: 3589, transactionID: $rootScope.transactionID } };

        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            if (($rootScope.BusinessTypeID == undefined || $rootScope.BusinessTypeID == null) && ($rootScope.transactionID == undefined || $rootScope.transactionID == null)) {
                $rootScope.IsShoppingCart = false;
                $location.path('/cftReRegistration');
            }
            wacorpService.get(webservices.CFT.getTrustReRegistrationDetails, data, function (response) {
                $scope.modal = response.data;
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
                //$scope.modal.BusinessFiling.OldFilingHistory = JSON.stringify($scope.modal);
                $scope.modal.EntityName = $scope.modal.EntityName || null;
                $scope.modal.OldEntityName = $scope.modal.EntityName;
                originalEntityName = $scope.modal.EntityName;
                $scope.modal.JurisdictionCountry = response.data.JurisdictionCountry == 0 ? "" : response.data.JurisdictionCountry.toString();
                $scope.modal.JurisdictionState = response.data.JurisdictionState == 0 ? "" : response.data.JurisdictionState.toString();
                $scope.modal.FederalTaxExemptId = response.data.FederalTaxExemptId == null ? "" : response.data.FederalTaxExemptId.toString();
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID || $scope.modal.BusinessTransaction.TransactionId;
                $scope.modal.PurposeId = angular.isNullorEmpty($scope.modal.PurposeId) ? [] : $scope.modal.PurposeId.split(',');
                $scope.modal.ContactPersonAddress.State = response.data.ContactPersonAddress.State == "" ? codes.WA : response.data.ContactPersonAddress.State;
                $scope.modal.ContactPersonAddress.Country = response.data.ContactPersonAddress.Country == "" ? codes.USA : response.data.ContactPersonAddress.Country;
                $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID != null ? $scope.modal.LegalInfo.LegalInfoTypeID : 'I';
                $scope.modal.EntityMailingAddress.State = $scope.modal.EntityMailingAddress.State != null ? $scope.modal.EntityMailingAddress.State : codes.WA;
                $scope.modal.EntityMailingAddress.Country = $scope.modal.EntityMailingAddress.Country != null ? $scope.modal.EntityMailingAddress.Country : codes.USA;
                $scope.modal.EntityStreetAddress.State = $scope.modal.EntityStreetAddress.State != null ? $scope.modal.EntityStreetAddress.State : codes.WA;
                $scope.modal.EntityStreetAddress.County = $scope.modal.EntityStreetAddress.County != null ? $scope.modal.EntityStreetAddress.County : "";
                $scope.modal.EntityStreetAddress.Country = $scope.modal.EntityStreetAddress.Country != null ? $scope.modal.EntityStreetAddress.Country : codes.USA;
                $scope.modal.LegalInfo.LegalInfoAddress.State = $scope.modal.LegalInfo.LegalInfoAddress.State != null ? $scope.modal.LegalInfo.LegalInfoAddress.State : codes.WA;
                $scope.modal.LegalInfo.LegalInfoAddress.Country = $scope.modal.LegalInfo.LegalInfoAddress.Country != null ? $scope.modal.LegalInfo.LegalInfoAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.Country = $scope.modal.CFTCorrespondenceAddress.Country != null ? $scope.modal.CFTCorrespondenceAddress.Country : codes.USA;
                $scope.modal.CFTCorrespondenceAddress.State = $scope.modal.CFTCorrespondenceAddress.State != null ? $scope.modal.CFTCorrespondenceAddress.State : codes.WA;
                $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.DateOfIncorporation = wacorpService.dateFormatService($scope.modal.DateOfIncorporation);
                $scope.modal.DateOfTrustEstablishment = wacorpService.dateFormatService($scope.modal.DateOfTrustEstablishment);
                $scope.modal.ProbatedDate = wacorpService.dateFormatService($scope.modal.ProbatedDate);

                $scope.modal.OldIsFederalTax = $scope.modal.IsFederalTax;
                $scope.modal.OldIsShowFederalTax = $scope.modal.IsShowFederalTax;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.AccountingyearBeginningDate = wacorpService.dateFormatService($scope.modal.AccountingyearBeginningDate);
                $scope.modal.AccountingyearEndingDate = wacorpService.dateFormatService($scope.modal.AccountingyearEndingDate);
                $scope.modal.FirstAccountingyearEndDate = wacorpService.dateFormatService($scope.modal.FirstAccountingyearEndDate);

                if ($scope.modal.AccountingyearBeginningDate == null || $scope.modal.AccountingyearEndingDate == null) {
                    $scope.modal.IsDatesNull = true;
                }

                checkForNAN(); // checkForNAN method is available in this controller only.

                if ($rootScope.IsShoppingCart) {
                    $scope.modal.hideOnlineSaveClose = true;
                }

                $scope.FirstAccountingyearEndDate = new Date();
                $scope.FirstAccountingyearEndDate = $scope.modal.FirstAccountingyearEndDate;
                if ($scope.modal.IsActiveFilingExist) {
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }

                var accEndDate;

                if ($scope.modal.OfficersHighPayList.length > 0) {
                    angular.forEach($scope.modal.OfficersHighPayList, function (cftHihPay) {
                        cftHihPay.SequenceNo = cftHihPay.ID;
                    });
                }

                if (!$rootScope.IsShoppingCart) {
                    if ($scope.modal.CFTOfficersList.length > 0) {
                        angular.forEach($scope.modal.CFTOfficersList, function (cftOffice) {
                            cftOffice.SequenceNo = cftOffice.OfficerID;
                        });
                    }
                }


                if ($scope.modal.LegalInfoEntityList.length > 0) {
                    angular.forEach($scope.modal.LegalInfoEntityList, function (cftLegalInfo) {
                        cftLegalInfo.SequenceNo = cftLegalInfo.LegalInfoId;
                    });
                }

                if ($scope.modal.FEINNumber != null && $scope.modal.FEINNumber != "") {
                    var index = $scope.modal.FEINNumber.indexOf("-");
                    if (index > 0) {
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber;

                    }
                    else
                        $scope.modal.FEINNumber = $scope.modal.FEINNumber.substring(0, 2) + "-" + $scope.modal.FEINNumber.substring(2, $scope.modal.FEINNumber.length);
                }

                $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;

                $scope.modal.IsFEINNumberExistsorNot = true;
                $scope.modal.IsUBINumberExistsorNot = true;

                if ($scope.modal.CountryCode == null || $scope.modal.CountryCode == '' || $scope.modal.CountryCode == 0)
                    $scope.modal.CountryCode = $scope.modal.IsForeignContact ? '' : '1';
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService($scope.modal.SignatureAttestation.AttestationDate);

                $scope.modal.isHavingEntityOnUBISearch = angular.isNullorEmpty($scope.modal.UBINumber) ? false : true;

                $scope.ValidateRenewalDate(); // ValidateRenewalDate method is available in this controller only.
                $scope.modal.isShowReturnAddress = true;

            }, function (response) { });
        }
        else {
            $scope.modal = $rootScope.modal;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            $scope.modal.SignatureAttestation.AttestationDate = wacorpService.dateFormatService(new Date());
            $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
            checkForNAN(); // checkForNAN method is available in this controller only.
            $scope.modal.isShowReturnAddress = true;
        }
    };

    var checkForNAN = function () {
        $scope.modal.BeginingGrossAssets = isNaN($scope.modal.BeginingGrossAssets) ? null : $scope.modal.BeginingGrossAssets;
        $scope.modal.TotalRevenue = isNaN($scope.modal.TotalRevenue) ? null : $scope.modal.TotalRevenue;
        $scope.modal.GrantContributionsProgramService = isNaN($scope.modal.GrantContributionsProgramService) ? null : $scope.modal.GrantContributionsProgramService;
        $scope.modal.Compensation = isNaN($scope.modal.Compensation) ? null : $scope.modal.Compensation;
        $scope.modal.TotalExpenses = isNaN($scope.modal.TotalExpenses) ? null : $scope.modal.TotalExpenses;
        $scope.modal.EndingGrossAssets = isNaN($scope.modal.EndingGrossAssets) ? null : $scope.modal.EndingGrossAssets;
    };

    $scope.TrusteeValidateEndDate = function () {
        return (new Date($scope.modal.AccountingyearEndingDate) < new Date($scope.modal.AccountingyearBeginningDate));
    };

    $scope.ValidateRenewalDate = function () {
        var result = $scope.modal.ErrorMsg == null || $scope.modal.ErrorMsg == "" ? true : false;
        if (!result) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog($scope.modal.ErrorMsg);
            return false;
        }
        return true;
    };

    $scope.Review = function (TrusteeReRegistrationForm) {
        // ValidateRenewalDate method is available in this controller only.
        if ($scope.ValidateRenewalDate()) {
            $scope.validateErrorMessage = true;

            //var endDate = $scope.modal.AccountingyearEndingDate;
            //if (typeof (endDate) != typeof (undefined) && endDate != null && endDate != "") {
            //    // Service Folder: services
            //    // File Name: wacorpService.js (you can search with file name in solution explorer)
            //    var isEndDateMore = wacorpService.isEndDateMoreThanToday(endDate);
            //    if (isEndDateMore) {
            //        // Folder Name: app Folder
            //        // Alert Name: endDateNotGreaterThanTodayDate method is available in alertMessages.js 
            //        wacorpService.alertDialog($scope.messages.CharitiesFinancial.endDateNotGreaterThanTodayDate);
            //        return false;
            //    }
            //}

            $scope.modal.NewEntityName = $scope.modal.EntityName;

            if ((typeof ($scope.modal.NewEntityName) != typeof (undefined) && $scope.modal.NewEntityName != null && $scope.modal.NewEntityName != "") && (typeof ($scope.modal.OldEntityName) != typeof (undefined) && $scope.modal.OldEntityName != null && $scope.modal.OldEntityName != "")) {
                if (angular.lowercase($scope.modal.OldEntityName) != angular.lowercase($scope.modal.NewEntityName) && !$scope.modal.IsOrgNameExists && !$scope.modal.isBusinessNameAvailable) {
                    $scope.modal.isBusinessNameChanged = true;
                }
                else {
                    $scope.modal.isBusinessNameChanged = false;
                }
            }

            var isTrustDesignatesBeneficiaryUpload = $scope.modal.TrustDesignatesBeneficiaryUpload.length > 0 ? true : false;

            //var isTrustInstrumentUpload = $scope.modal.TrustInstrumentUpload.length > 0 ? true : false;

            var isFeinSecValid = $scope.TrusteeReRegistrationForm.fein.mainFein.$valid;

            var isEntityNameValid = $scope.modal.IsOrgNameExists ? true : ($scope.modal.isBusinessNameAvailable ? true : (angular.lowercase($scope.modal.OldEntityName) == angular.lowercase($scope.modal.NewEntityName) ? true : false));

            if (isEntityNameValid && ($scope.modal.isBusinessNameChanged == false)) {
                $scope.EntityNameCheck = false;
            }
            else {
                $scope.EntityNameCheck = true;
            }

            var isEntityInfoValid = ($scope.TrusteeReRegistrationForm.entityInfo.$valid)
                                   && ($scope.modal.isUploadAddress ? ($scope.modal.UploadListOfAddresses.length > 0) : true);

            var isIRSDocumentTypeValid = $scope.modal.IsCurrentYearExistsForReRegistration ? true : ($scope.modal.IRSDocumentId != 0 ? true : false);

            var isFederalUpload = $scope.modal.IsShowFederalTax ? ($scope.modal.FederaltaxUpload.length > 0 ? true : false) : true;

            var isIRSDocumentValid = $scope.modal.IsCurrentYearExistsForReRegistration ? true : ($scope.modal.FinancialInfoIRSUpload.length > 0 ? true : false);

            var isTrustFinancialInfoValid = $scope.TrusteeReRegistrationForm.trustFinancialInfoForm.currentFinInfo.$valid;

            var isCftOfficesListValid = ($scope.checkOfficersCount() > 0); // checkOfficersCount method is available in this controller only.

            var isCurrentDatesValid = true;
            if (typeof ($scope.modal.AccountingyearBeginningDate) != typeof (undefined)
                        && $scope.modal.AccountingyearBeginningDate != null) {
                if ($scope.modal.AccountingyearEndingDate && $scope.modal.LastAccountingYearEndDate) {

                    if (new Date($scope.modal.AccountingyearBeginningDate) < new Date($scope.modal.LastAccountingYearEndDate && !$scope.modal.IsCurrentYearExistsForReRegistration)) {
                        isCurrentDatesValid = false;
                        $scope.modal.AccEndDateLessThanCurrentYear = true;
                    }
                    else {
                        isCurrentDatesValid = true;
                        $scope.modal.AccEndDateLessThanCurrentYear = false;
                    }
                }
            }

            var isCurrentEndDateValid = true;
            if ($scope.modal.AccountingyearEndingDate != null && $scope.modal.AccountingyearBeginningDate != null) {
                if (new Date($scope.modal.AccountingyearEndingDate) < new Date($scope.modal.AccountingyearBeginningDate)) {
                    isCurrentEndDateValid = false;
                }
                else {
                    isCurrentEndDateValid = true;
                }
            }

            $scope.checkAccYearVaild = false;
            //if (typeof ($scope.modal.AccountingyearEndingDate) != typeof (undefined) && $scope.modal.AccountingyearEndingDate != null && $scope.modal.AccountingyearEndingDate != "") {
            //    // Service Folder: services
            //    // File Name: wacorpService.js (you can search with file name in solution explorer)
            //    $scope.checkAccYearVaild = wacorpService.checkAccYearEndDateForReg($scope.modal.AccountingyearEndingDate, true);
            //}

            // var isEstablishmentOfTrust = $scope.modal.ProbateOrder || $scope.modal.LastWillAndTestament || $scope.modal.TrustAgreement || $scope.modal.ArticlesOfIncorporationAndBylaws;

            var isDirectoryInfoValid = $scope.TrusteeReRegistrationForm.directoryInformationForm.$valid;

            var isLegalActionsListValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalInfoEntityList.length > 0 ? true : false) : true);

            var isLegalActionsUploadValid = ($scope.modal.LegalInfo.IsAnyLegalActions ? ($scope.modal.LegalActionsUploads.length > 0 ? true : false) : true);

            //trustLegalInfo
            var isLegalInfo = ($scope.TrusteeReRegistrationForm.trustLegalInfo.$valid);

            var isPurposeValid = $scope.modal.IsIncludedInWACharitableTrust ? ($scope.modal.PurposeId.length <= 3 ? true : false) : true;

            var isSignatureAttestationValid = $scope.TrusteeReRegistrationForm.SignatureForm.$valid;

            //var isCorrespondenceAddressValid = $scope.TrusteeReRegistrationForm.cftCorrespondenceAddressForm.EmailID.$valid && $scope.commercialFundraiserReRegistrationForm.cftCorrespondenceAddressForm.ConfirmEmail.$valid;
            var isCorrespondenceAddressValid = $scope.TrusteeReRegistrationForm.cftCorrespondenceAddressForm.$valid;

            //Upload Additional Documents
            var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.CFTUploadDocumentsList != null && $scope.modal.CFTUploadDocumentsList.length > constant.ZERO) : true;

            var isFormValid = isEntityNameValid && isEntityInfoValid && isTrustFinancialInfoValid && isCftOfficesListValid && isDirectoryInfoValid && isLegalInfo
                                && isFeinSecValid && isIRSDocumentTypeValid && isIRSDocumentValid && isFederalUpload
                                && isLegalActionsUploadValid && isCurrentEndDateValid && isCorrespondenceAddressValid
                                  && isLegalActionsListValid && isSignatureAttestationValid && isAdditionalUploadValid && isPurposeValid && !$scope.checkAccYearVaild;

            $scope.fillRegData(); // fillRegData method is available in this controller only.

            if (isFormValid) {
                $scope.validateErrorMessage = false;
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                $scope.modal.EntityMailingAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityMailingAddress);
                $scope.modal.EntityStreetAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.EntityStreetAddress);
                $scope.modal.LegalInfo.LegalInfoAddress.FullAddress = wacorpService.cftFullAddressService($scope.modal.LegalInfo.LegalInfoAddress);

                var count = 0;
                angular.forEach($scope.modal.CFTFinancialHistoryList, function (value) {
                    if (value.Flag == 'C') {
                        count++;
                    }
                });
                if ($scope.modal.FinInfoCount > 0 && $scope.modal.FinInfoCount > count) {
                    //wacorpService.alertDialog("Financial information history is missing one of the following years information - "+ $scope.modal.FinInfoHistoryDates);
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog("Please enter missing years financial information in history");
                }
                else {
                    $rootScope.modal = $scope.modal;
                    $location.path('/trustReRegistrationReview');
                    ////wacorpService.alertDialog("Financial information history is missing one of the following years information - "+ $scope.modal.FinInfoHistoryDates);
                    //wacorpService.alertDialog("Please enter missing years financial information in History");
                }
            }
            else
                // Folder Name: app Folder
                // Alert Name: InvalidFilingMsg method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
            //}
            //else {
            //    if ($scope.modal.UBINumber != null && $scope.modal.IsUbiAssociated) {
            //        wacorpService.alertDialog($scope.messages.ubiNotAssociated);
            //        return false;
            //    }
            //}
        }
    };


    $scope.checkOfficersCount = function () {
        var count = 0;
        angular.forEach($scope.modal.CFTOfficersList, function (value) {
            if (value.OfficerStatus != 'D')
                count++;
        });

        if (count == 0 || count == undefined)
            return $scope.modal.CFTOfficersList.length = 0;
        else
            return $scope.modal.CFTOfficersList.length;
    };

    $scope.fillRegData = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.FinancialId = $scope.modal.FinancialId || null;

        //Organization Information
        $scope.modal.EntityName = $scope.modal.EntityName != null && $scope.modal.EntityName != '' ? $scope.modal.EntityName : null;
        $scope.modal.FEINNumber = $scope.modal.FEINNumber != null && $scope.modal.FEINNumber != '' ? $scope.modal.FEINNumber : null;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        //$scope.modal.UBINumber = $scope.modal.UBINumber.replace(/\s/g, '');
        $scope.modal.RegistrationNumber = $scope.modal.RegistrationNumber || null;
        $scope.modal.IsEntityRegisteredInWA = false;
        $scope.modal.JurisdictionState = "";
        $scope.modal.JurisdictionStateDesc = "";

        //Contact information
        $scope.modal.EntityEmailAddress = $scope.modal.EntityEmailAddress != null && $scope.modal.EntityEmailAddress != '' ? $scope.modal.EntityEmailAddress : null;
        $scope.modal.EntityConfirmEmailAddress = $scope.modal.EntityConfirmEmailAddress != null && $scope.modal.EntityConfirmEmailAddress != '' ? $scope.modal.EntityConfirmEmailAddress : null;
        $scope.modal.EntityWebsite = $scope.modal.EntityWebsite != null && $scope.modal.EntityWebsite != '' ? $scope.modal.EntityWebsite : null;
        $scope.modal.IsForeignContact = $scope.modal.IsForeignContact;
        $scope.modal.CountryCode = $scope.modal.CountryCode || null;
        $scope.modal.EntityPhoneNumber = $scope.modal.EntityPhoneNumber;
        $scope.modal.PhoneExtension = $scope.modal.PhoneExtension
        $scope.modal.EntityMailingAddress = $scope.modal.EntityMailingAddress || null;
        $scope.modal.IsSameasStreetAddr = $scope.modal.IsSameAsEntityMailingAddress;
        $scope.modal.EntityStreetAddress = $scope.modal.EntityStreetAddress || null;
        $scope.modal.IsUploadAddress = $scope.modal.IsUploadAddress;
        //$scope.modal.UploadListOfAddresses = angular.isNullorEmpty($scope.modal.UploadListOfAddresses) ? [] : $scope.modal.UploadListOfAddresses;

        //Financial Information
        $scope.modal.IsFIFullAccountingYear = $scope.modal.IsFIFullAccountingYear;
        $scope.modal.AccountingyearBeginningDate = $scope.modal.AccountingyearBeginningDate;
        $scope.modal.AccountingyearEndingDate = $scope.modal.AccountingyearEndingDate;
        $scope.modal.FirstAccountingyearEndDate = $scope.modal.FirstAccountingyearEndDate;

        $scope.modal.BeginingGrossAssets = ($scope.modal.BeginingGrossAssets == null) ? null : $scope.modal.BeginingGrossAssets;
        $scope.modal.TotalRevenue = ($scope.modal.TotalRevenue == null) ? null : $scope.modal.TotalRevenue;
        $scope.modal.GrantContributionsProgramService = ($scope.modal.GrantContributionsProgramService == null) ? null : $scope.modal.GrantContributionsProgramService;
        $scope.modal.Compensation = ($scope.modal.Compensation == null) ? null : $scope.modal.Compensation;
        $scope.modal.EndingGrossAssets = ($scope.modal.EndingGrossAssets == null) ? null : $scope.modal.EndingGrossAssets;
        $scope.modal.TotalExpenses = ($scope.modal.TotalExpenses == null) ? null : $scope.modal.TotalExpenses;

        $scope.modal.IRSDocumentId = $scope.modal.IRSDocumentId

        if ($scope.modal.IRSDocumentId == 0) {
            $scope.modal.IRSDocumentTye = null;
        }
        else {
            angular.forEach($scope.IRSDocumentTypes, function (val) {
                if ($scope.modal.IRSDocumentId == val.Key) {
                    $scope.modal.IRSDocumentTye = val.Value;
                }
            });
        }

        $scope.modal.FinancialInfoIRSUploadTypeText = $scope.modal.IRSDocumentTye;

        $scope.modal.Comments = $scope.modal.Comments;

        //Person Accepting Responsibility
        $scope.modal.IsSameAsAddressContactInfo = $scope.modal.IsSameAsAddressContactInfo;
        //$scope.modal.CFTOfficersList = angular.isNullorEmpty($scope.modal.CFTOfficersList) ? [] : $scope.modal.CFTOfficersList;

        //Financial Preparer
        $scope.modal.LegalInfo.LegalInfoTypeID = $scope.modal.LegalInfo.LegalInfoTypeID;
        $scope.modal.LegalInfo.FirstName = $scope.modal.LegalInfo.FirstName || null;
        $scope.modal.LegalInfo.LastName = $scope.modal.LegalInfo.LastName || null;
        $scope.modal.LegalInfo.LegalInfoEntityName = $scope.modal.LegalInfo.LegalInfoEntityName || null;
        $scope.modal.LegalInfo.EntityRepresentativeFirstName = $scope.modal.LegalInfo.EntityRepresentativeFirstName || null;
        $scope.modal.LegalInfo.EntityRepresentativeLastName = $scope.modal.LegalInfo.EntityRepresentativeLastName || null;
        $scope.modal.LegalInfo.Title = $scope.modal.LegalInfo.Title || null;
        $scope.modal.LegalInfo.LegalInfoAddress = $scope.modal.LegalInfo.LegalInfoAddress || null;
        $scope.modal.LegalInfo.IsAnyLegalActions = $scope.modal.LegalInfo.IsAnyLegalActions;

        //Legal Information
        //$scope.modal.LegalInfoEntityList = angular.isNullorEmpty($scope.modal.LegalInfoEntityList) ? [] : $scope.modal.LegalInfoEntityList;
        //$scope.modal.UploadSurityBondList = angular.isNullorEmpty($scope.modal.UploadSurityBondList) ? [] : $scope.modal.UploadSurityBondList;

        //Filing Correspondence
        $scope.modal.CFTAttention = $scope.modal.CFTAttention;
        $scope.modal.CorrespondenceEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        if ($scope.modal.CorrespondenceEmailAddress != "" && $scope.modal.CorrespondenceEmailAddress != null)
            $scope.modal.CorrespondenceConfrimEmailAddress = $scope.modal.CorrespondenceEmailAddress;
        $scope.modal.CFTCorrespondenceAddress = $scope.modal.CFTCorrespondenceAddress || null;

        //ONLINE UPLOAD DOCUMENTS
        //$scope.modal.CFTUploadDocumentsList = angular.isNullorEmpty($scope.modal.CFTUploadDocumentsList) ? [] : $scope.modal.CFTUploadDocumentsList;

        //Attestation
        $scope.modal.SignatureOnDocument = $scope.modal.SignatureAttestation.IsAttestationInformationProvided;
        $scope.modal.SignatureAttestation = $scope.modal.SignatureAttestation || null;
        if (typeof ($scope.modal.PurposeId) != typeof (undefined) && $scope.modal.PurposeId != null) {
            if (angular.isArray($scope.modal.PurposeId) && $scope.modal.PurposeId.length > 0)
                $scope.modal.PurposeId = $scope.modal.PurposeId.join(",");
        }
        $rootScope.modal = $scope.modal;
    };

    $scope.calculateEndDate = function (value) {
        if (value != null && value != undefined) {
            var endDate = new Date(value);
            endDate.setYear(endDate.getFullYear() + 1);
            var firstDay = new Date(endDate.getFullYear(), endDate.getMonth(), 1);
            var lastDay = new Date(endDate.getFullYear(), endDate.getMonth(), 0);
            var lastDayWithSlashes = ('0' + (lastDay.getMonth() + 1)).slice(-2) + '/' + (lastDay.getDate()) + '/' + lastDay.getFullYear();
            return lastDayWithSlashes;
        }
    };

    $scope.SaveClose = function () {
        $scope.modal.isBusinessNameAvailable = false;
        $scope.fillRegData();
        $scope.modal.OnlineNavigationUrl = "/trustReRegistration/";
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // TrustSaveandClose method is availble in constants.js
        wacorpService.post(webservices.CFT.TrustSaveandClose, $scope.modal, function (response) {
            $rootScope.BusinessType = null;
            $rootScope.modal = null;
            $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

});
wacorpApp.controller('trusteeReRegistrationReviewController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    /* --------Commercial Trust Renewal Functionality------------- */

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        $scope.isReview = true;
        if ($rootScope.modal == null || $rootScope.modal == undefined) {
            $location.path("/trustReRegistration");
        }
        else {
            $scope.modal = $rootScope.modal;
            if ($scope.modal.UBINumber != '' && $scope.modal.UBINumber != undefined) {
                $scope.modal.UBINumber = $scope.modal.UBINumber.replace(/(?!^)(?=(?:\d{3})+(?:\.|$))/gm, ' ');
            }
        }
        $scope.usaCode = usaCode;
    };


    $scope.TrustReRegistrationAddToCart = function () {
        $scope.modal.CreatedBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.IsOnline = true;
        $scope.modal.UBINumber = ($scope.modal.UBINumber != null && $scope.modal.UBINumber != '') ? $scope.modal.UBINumber.replace(/\s/g, '') : null;
        $scope.modal.UBIJurisdictionId = $scope.modal.JurisdictionCountry == usaCode ? $scope.modal.JurisdictionState : $scope.modal.JurisdictionCountry;
        if (typeof ($scope.modal.PurposeId) != typeof (undefined) && $scope.modal.PurposeId != null) {
            if (angular.isArray($scope.modal.PurposeId) && $scope.modal.PurposeId.length > 0)
                $scope.modal.PurposeId = $scope.modal.PurposeId.join(",");
        }

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // TrusteeAddToCart method is available in constants.js
        wacorpService.post(webservices.CFT.TrusteeAddToCart, $scope.modal, function (response) {
            $rootScope.TrustRenewalModal = null;
            $rootScope.BusinessType = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > constant.ZERO)
                $location.path('/shoppingCart');
            //else
            //    $location.path('/Dashboard');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    $scope.Back = function () {
        $rootScope.modal = $scope.modal;
        $location.path('/trustReRegistration/' + $scope.modal.TrustID);
    };

    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }
});

wacorpApp.controller('cftSearchController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, $window) {
    // variable initilization
    $scope.page = constant.ZERO;
    $scope.page1 = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.pagesCount1 = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.States = [];
    $scope.Counties = [];
    $scope.isButtonSerach = false;
    $scope.cftBusinesssearchcriteria = {};
    $scope.cftAdvFeinSearchcriteria = {};
    $scope.criteria = [];
    $scope.cftBusinessSearch = {};
    $rootScope.cftData = {};
    $rootScope.isAdvanceSearch = false;
    $scope.cftOrganizationSearchType = false;
    $scope.showHome = false;
    $scope.isShowAdvanceSearch = false;
    $scope.hideBasicSearch = false;
    $scope.hideSearchButton = false;
    $scope.search = loadCFList;

    $rootScope.clearCFTSearchResults = function() {
        $scope.clearFun();
        $scope.isShowAdvanceSearch = false;
        $scope.hideSearchButton = false;
    }

    $scope.cftSearchcriteria = {
        Type: searchTypes.RegistrationNumber, EntityName: null, KeyWordSearch: null, PrincipalName: null, PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false,
        RegistrationNumber: null, FEINNo: null, UBINumber: null, PercentToProgramServices: null, BusinessStatusID: null,
        PrincipalAddress: {
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
            State: null, OtherState: null, Country: null, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        CFSearchList: [],
        SearchCriteria: "Contains", SortBy: null, SortType: null
    };

    $scope.clearCFTSearchcriteria = {
        Type: searchTypes.RegistrationNumber, EntityName: null, KeyWordSearch: null, PrincipalName: null, PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false,
        RegistrationNumber: null, FEINNo: null, UBINumber: null, PercentToProgramServices: null,
        PrincipalAddress: {
            FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
            State: null, OtherState: null, Country: null, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
        },
        CFSearchList: [],
        SearchCriteria: "Contains"
    };

    $scope.getPercentType = function () {
        $scope.cftSearchcriteria.PercentToProgramServices = $(event.target || event.srcElement).find("option:selected").text();
    }

    $scope.cftAdvFeinSearchcriteria = {
        CFTId: "", ID: "", EntityName: "", KeyWordSearch: "", PageID: constant.ONE, PageCount: constant.TEN, isCftOrganizationSearchBack: false, IsSearch: false, EntityWebsite: null,
        RegistrationNumber: null, FEINNumber: null, UBINumber: null, Address: null, Businesstype: "", Type: "", SearchValue: "", SearchCriteria: "",
    };

    //scope initialization
    $scope.initCFTSearch = function () {
        $scope.cftOrganizationSearchType = true;
        if ($rootScope.isInitialSearch && $rootScope.data && $rootScope.data.PrincipalAddress) {
            $scope.cftSearchcriteria = $rootScope.data;
            $cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
            $rootScope.data = null;
        }
        else if ($rootScope.isCftOrganizationSearchBack == true && $rootScope.data && $rootScope.data.PrincipalAddress) {
            $scope.showAdvanceSearch();
            $scope.cftSearchcriteria = $rootScope.data;
            $cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
            $rootScope.data = null;
        }
        else {
            $scope.page = $scope.page || constant.ZERO;
            $scope.cftSearchcriteria.PageID = $scope.page == constant.ZERO ? constant.ONE : $scope.page + constant.ONE;
        }
        if ($rootScope.isInitialSearch)
            loadCFList(constant.ZERO, false);
        else if ($rootScope.isCftOrganizationSearchBack)
            loadCFList(constant.ZERO, true);

        $scope.messages = messages;
        if ($rootScope.repository.loggedUser != undefined && $rootScope.repository.loggedUser != null) {
            if ($rootScope.repository.loggedUser.userid != undefined && $rootScope.repository.loggedUser.userid != null && $rootScope.repository.loggedUser.userid > 0) {
                $scope.IsUserLogedIn = true;
            }
            else {
                $scope.IsUserLogedIn = false;
            }
        }
        else {
            $scope.IsUserLogedIn = false;
            $scope.showAdvanceSearch();
        }

    }

    //Get States List
    $scope.getStates = function () {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.statesList(function (response) { $scope.States = response.data; });
    };

    //Get Counties List
    $scope.getCounties = function () {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.countiesList(function (response) { $scope.Counties = response.data; });
    };

    //Get Status List
    $scope.getStatus = function () {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.CFTStatusList(function (response) { $scope.Status = response.data; });
    };

    //***** Added re: CCFS TFS ticket# 3034 - KK, 9/10/2019 
    //Get Tax Exempt Status list
    //$scope.getTaxExemptStatus = function() {
    //    lookupService.CFTTaxExStatusList(function(response) { $scope.TaxExStatus = response.data; });
    //};

    $scope.getStates(); // getStates method is available in this controller only.
    $scope.getCounties(); // getCounties method is available in this controller only.
    $scope.getStatus(); // getStatus method is available in this controller only.

    //***** Added re: CCFS TFS ticket# 3034 - KK, 9/10/2019 
    //$scope.getTaxExStatus(); //!!! Causes buttons to disappear when uncommented

    $scope.setPastedUBI = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.cftSearchcriteria.UBINumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.cftSearchcriteria.UBINumber = pastedText;
            });
        }
    };

    $scope.setUBILength = function (e) {
        if ($scope.cftSearchcriteria.UBINumber != null && $scope.cftSearchcriteria.UBINumber != undefined && $scope.cftSearchcriteria.UBINumber != "" && $scope.cftSearchcriteria.UBINumber.length >= 9)
        {
            if (e.which != 97)
            {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                    // Allow: Ctrl+A, Command+A
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right, down, up
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
                e.preventDefault();
            }
        }
    };

    $scope.setPastedFEIN = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
            $scope.cftSearchcriteria.FEINNo = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 9);
                $scope.cftSearchcriteria.FEINNo = pastedText;
            });
        }
    };

    $scope.setPastedZip = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 5);
            $scope.cftSearchcriteria.FEINNo = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 5);
                $scope.cftSearchcriteria.FEINNo = pastedText;
            });
        }
    };

    $scope.setPastedRemoveSpaces = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\s/g, '');
            if (e.originalEvent.currentTarget.name == "OrganizationName")
                $scope.cftSearchcriteria.EntityName = pastedText;
            else if (e.originalEvent.currentTarget.name == "KeywordSearch")
                $scope.cftSearchcriteria.KeyWordSearch = pastedText;
            else if (e.originalEvent.currentTarget.name == "City")
                $scope.cftSearchcriteria.PrincipalAddress.City = pastedText;
            else if (e.originalEvent.currentTarget.name == "Officers")
                $scope.cftSearchcriteria.PrincipalName = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\s/g, '');
                if (e.originalEvent.currentTarget.name == "OrganizationName")
                    $scope.cftSearchcriteria.EntityName = pastedText;
                else if (e.originalEvent.currentTarget.name == "KeywordSearch")
                    $scope.cftSearchcriteria.KeyWordSearch = pastedText;
                else if (e.originalEvent.currentTarget.name == "City")
                    $scope.cftSearchcriteria.PrincipalAddress.City = pastedText;
                else if (e.originalEvent.currentTarget.name == "Officers")
                    $scope.cftSearchcriteria.PrincipalName = pastedText;
            });
        }
    };
    $scope.setPastedRegNumber = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
            $scope.cftSearchcriteria.RegistrationNumber = pastedText;
            e.preventDefault();
        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                pastedText = pastedText.replace(/\D/g, '').replace(/\s/g, '').substring(0, 7);
                $scope.cftSearchcriteria.RegistrationNumber = pastedText;
            });
        }
    };

    $scope.setPercent = function (e) {
        var pastedText = "";
        if (typeof e.originalEvent.clipboardData !== "undefined") {
            pastedText = e.originalEvent.clipboardData.getData('text/plain');
            var digits = /^[0-9]+$/;
            if (digits.test(pastedText))
                $scope.cftSearchcriteria.PercentToProgramServices = pastedText;
            else {
                e.preventDefault();
                $scope.cftSearchcriteria.PercentToProgramServices = null;
            }

        } else {
            $timeout(function () {
                pastedText = angular.element(e.currentTarget).val();
                var digits = /^[0-9]+$/;
                if (digits.test(pastedText))
                    $scope.cftSearchcriteria.PercentToProgramServices = pastedText;
                else {
                    e.preventDefault();
                    $scope.cftSearchcriteria.PercentToProgramServices = null;
                }
            });
        }
    };


    $scope.allowDecimals = function (e) {

        //var pastedText = "";
        //    pastedText = evt.originalEvent.clipboardData.getData('text/plain');
        var charCode = (e.which) ? e.which : e.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            e.preventDefault();
        }
        else { }
    };


    $scope.setUBILength = function (e) {
        //if ($scope.cftSearchcriteria.UBINumber.length >= 9) {
        //    e.preventDefault();
        //}
        if ($scope.cftSearchcriteria.UBINumber != null && $scope.cftSearchcriteria.UBINumber != undefined && $scope.cftSearchcriteria.UBINumber != "" && $scope.cftSearchcriteria.UBINumber.length >= 9)
        {
            if (e.which != 97)
            {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                    // Allow: Ctrl+A, Command+A
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right, down, up
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
                e.preventDefault();
            }
        }
    };

    // search Charity and Fundraiser list
    $scope.searchCF = function (searchform, flag) {
        if ($scope.isShowAdvanceSearch) {
            $scope.searchCFForAdvance(searchform, flag); // searchCFForAdvance method is available in this controller only.
        }
        else {
            $scope.isShowErrorFlag = true;
            if ($scope[searchform].$valid) {
                $scope.isShowErrorFlag = false;
                $scope.cftSearchcriteria.IsSearch = true;
                $scope.isButtonSerach = true;
                loadCFList(constant.ZERO, flag); // loadCFList method is available in this controller only.
            }
        }
    };

    $scope.searchCFForAdvance = function (searchform, flag) {
        $scope.isShowErrorFlag = false;
        $scope.cftSearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadCFList(constant.ZERO, flag); // loadCFList method is available in this controller only.
    };

    // clear fields    
    $scope.clearFun = function () {
        $scope.cftSearchcriteria = $scope.clearCFTSearchcriteria = {
            Type: searchTypes.RegistrationNumber, EntityName: null, KeyWordSearch: null, PrincipalName: null, PageID: constant.ONE, PageCount: constant.TEN, IsSearch: false,
            RegistrationNumber: null, FEINNo: null, UBINumber: null, PercentToProgramServices: null,
            PrincipalAddress: {
                FullAddress: null, ID: constant.ZERO, StreetAddress1: null, StreetAddress2: null, City: null,
                State: null, OtherState: null, Country: codes.USA, Zip5: null, Zip4: null, PostalCode: null, County: null, CountyName: null
            },
            CFSearchList: []
        };
        $scope.cftSearchcriteria.IsSearch = false;
        $scope.isShowErrorFlag = false;
    };

    $scope.searchAdvFeinData = function (type, value) {
        $scope.cftAdvFeinSearchcriteria.Type = type;
        $scope.cftAdvFeinSearchcriteria.SearchValue = value;
        $('#divAdvCharitiesSearchResult').modal('toggle');
        loadAdvCFeinList(constant.ZERO); // loadAdvCFeinList method is available in this controller only.
    };

    // get Charity and Fundraiser list data from server
    function loadCFList(page, flag, sortBy) {
        //Ticket -- 3167
        $rootScope.isCFTBackButtonPressed = false;
        var data = new Array();
        $scope.cftSearchcriteria.PageID = page == 0 ? 1 : page + 1;
        if (sortBy != undefined) {
            if ($scope.cftSearchcriteria.SortBy == sortBy) {
                if ($scope.cftSearchcriteria.SortType == 'ASC') {
                    $scope.cftSearchcriteria.SortType = 'DESC';
                }
                else {
                    $scope.cftSearchcriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.cftSearchcriteria.SortBy = sortBy;
                $scope.cftSearchcriteria.SortType = 'ASC';
            }
        }
        else {
            if ($scope.cftSearchcriteria.Type == "OrganizationName")
            {
                if($scope.cftSearchcriteria.SortBy==null || $scope.cftSearchcriteria.SortBy=="" || $scope.cftSearchcriteria.SortBy==undefined)
                    $scope.cftSearchcriteria.SortBy = "OrganizationName";

                if ($scope.cftSearchcriteria.SortType == null || $scope.cftSearchcriteria.SortType == "" || $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = "ASC";

            }
            else if ($scope.cftSearchcriteria.Type == "UBINumber")
            {
                if ($scope.cftSearchcriteria.SortBy == null || $scope.cftSearchcriteria.SortBy == "" || $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "UBINumber";

                if ($scope.cftSearchcriteria.SortType == null || $scope.cftSearchcriteria.SortType == "" || $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = "ASC";
            }
            else if ($scope.cftSearchcriteria.Type == "FEINNo")
            {
                if ($scope.cftSearchcriteria.SortBy == null || $scope.cftSearchcriteria.SortBy == "" || $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "FEINNo";

                if ($scope.cftSearchcriteria.SortType == null || $scope.cftSearchcriteria.SortType == "" || $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = "ASC";
            }
            else if ($scope.cftSearchcriteria.Type == "RegistrationNumber")
            {
                if ($scope.cftSearchcriteria.SortBy == null || $scope.cftSearchcriteria.SortBy == "" || $scope.cftSearchcriteria.SortBy == undefined)
                    $scope.cftSearchcriteria.SortBy = "RegistrationNumber";

                if ($scope.cftSearchcriteria.SortType == null || $scope.cftSearchcriteria.SortType == "" || $scope.cftSearchcriteria.SortType == undefined)
                    $scope.cftSearchcriteria.SortType = "ASC";
            }
        }
        data = angular.copy($scope.cftSearchcriteria);
        if (flag == undefined || flag == null)
            flag = $rootScope.flag;
        //$cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
        if (flag) {
            $rootScope.isAdvanceSearch = true;
            $rootScope.isInitialSearch = null;
        }
        else {
            $rootScope.isInitialSearch = true;
            $rootScope.isAdvanceSearch = null;
        }
        $rootScope.flag = flag;
        $scope.isButtonSerach = page == 0;
        wacorpService.post(webservices.CFT.getCFPublicSearchDetails, data, function (response) {
            $scope.cftSearchcriteria.CFSearchList = response.data;
            $cookieStore.put('cftAdvanceSearchcriteria', $scope.cftSearchcriteria);
            if (response.data.length > constant.ZERO) {
                if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                    var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                    var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                                ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                    $scope.pagesCount = response.data.length < $scope.cftSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount : pagecount;
                    $scope.totalCount = totalcount;
                }
                $scope.page = page;
                $scope.BusinessListProgressBar = false;
                focus("tblCFSearch");
            }
            else if (response.data.length == constant.ZERO) {
                $scope.pagesCount = constant.ZERO;
                $scope.totalCount = constant.ZERO;
            }

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });

    }


    // search fein details associated to charity
    $scope.searchAdvFein = function (searchform) {
        $scope.cftAdvFeinSearchcriteria.IsSearch = true;
        $scope.isButtonSerach = true;
        loadAdvCFeinList(searchform); // loadAdvCFeinList method is available in this controller only.
    };


    //to get data for FEIN link
    function loadAdvCFeinList(page) {
        //if ($rootScope.isCftOrganizationSearchBack == true) {
        //    $scope.cftAdvFeinSearchcriteria = $cookieStore.get('cftAdvFeinSearchcriteria');
        //    page = page || constant.ZERO;
        //    $scope.cftAdvFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        //}
        //else {
        page = page || constant.ZERO;
        $scope.cftAdvFeinSearchcriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        //$scope.cftFeinSearchcriteria.Type = $scope.criteria.Type;
        //$scope.cftFeinSearchcriteria.SearchValue = $scope.criteria.SearchValue;
        $scope.cftAdvFeinSearchcriteria.SearchCriteria = "";
        //}
        var data = angular.copy($scope.cftAdvFeinSearchcriteria);
        $scope.isButtonSerach = page == 0;
        // getFEINDataDetails method is available in constants.js
        wacorpService.post(webservices.CFT.getFEINDataDetails, data, function (response) {
            $scope.feinDataDetails = response.data;
            if ($scope.cftAdvFeinSearchcriteria.PageID == 1)
                //$('#divAdvCharitiesSearchResult').modal('toggle');
                $cookieStore.put('cftAdvFeinSearchcriteria', $scope.cftAdvFeinSearchcriteria);

            if ($scope.isButtonSerach && response.data.length > constant.ZERO) {
                var totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + constant.ONE : Math.round(totalcount / response.data.length);
                $scope.pagesCount1 = response.data.length < $scope.cftAdvFeinSearchcriteria.PageCount && page > constant.ZERO ? $scope.pagesCount1 : pagecount;
                $scope.totalCount = totalcount;
            }
            $scope.page1 = page;
            $scope.BusinessListProgressBar = false;
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.cancel = function () {
        $("#divAdvCharitiesSearchResult").modal('toggle');
    }

    $scope.exportCSVServer = function () {
        var criteria = null;
        var searchinfo = angular.copy($scope.cftSearchcriteria);
        searchinfo.PageID = 1;
        searchinfo.PageCount = 9999999;
        wacorpService.post(webservices.CFT.getCFPublicSearchDetails, searchinfo, function (response) {
            var result = [];
            result = response.data;
            $rootScope.exportToCSV(result)

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);

        });

    }

    //Export Data to CSV
    $rootScope.exportToCSV = function (exportData) {

        var arrData = typeof exportData != 'object' ? JSON.parse(exportData) : exportData;

        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
        });

        var CSV = '';
        var row = "";

        var rowData = "";
        //Preapring Candidate Data
        var arrData1 = [];
        candidateColumns = ["Organization Name", "City Name", "Percent to Program Services (Ranges of 10%)", "Status"];
        $.each(arrData, function (index, element) {

            arrData1.push({
                "Organization Name": element.EntityName + ((element.AKANames != null && element.AKANames != '') ? '(' + element.AKANames + ')' : ''), "City Name": element.EntityMailingAddress.City,
                "Percent to Program Services (Ranges of 10%)": element.PercentToProgramServices, "Status": element.Status,

            })
        });
        $.each(arrData1, function (index, Data) {

            rowData = "";
            $.each(Data, function (headerName, Data) {
                if (candidateColumns.indexOf(headerName) != -1) {
                    if (index == 0) {
                        if (headerName == "Organization Name") {
                            headerName = "Organization Name";
                        }
                        else if (headerName == "City Name") {
                            headerName = "	City Name";
                        }
                        else if (headerName == "Percent to Program Services (Ranges of 10%)") {
                            headerName = "Percent to Program Services (Ranges of 10%)";
                        }

                        else if (headerName == "Status") {
                            headerName = "Status";
                        }

                        row += headerName + ',';
                    }
                    if (typeof Data === 'string') {
                        if (Data) {
                            if (Data.indexOf(',') != -1) {
                                Data = '"' + Data + '"';
                            }
                        }
                        //Data = Data.replace(/,/g, " ")
                    }

                    else {
                        if (!Data) {
                            Data = '';
                        }
                        else {
                            Data = Data;
                        }

                    }
                    if (headerName == 'Email' || headerName == 'Email') {
                        rowData = rowData + Data;
                    }
                    else {
                        rowData += Data + ",";
                    }


                }

            });

            if (index == 0) {
                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }
            rowData.slice(0, rowData.length - 1);

            //add a line break after each row
            CSV += rowData + '\r\n';
        });

        row = ""; csv = ""; rowData = "";

        //Generate a file name
        var fileName = "CFTSearchList";


        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        if (navigator.msSaveBlob) {
            var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
            navigator.msSaveBlob(blob, "fileName.csv")

        } else {
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        //}
    }

    //navigate to business information
    $scope.showBusineInfo = function (id, businessType, flag) {
        //if (!flag) {
        //    $scope.cftSearchcriteria.CFSearchList.CFTId = id;
        //    $scope.cftSearchcriteria.CFSearchList.Businesstype = businessType;
        //    $rootScope.data = $scope.cftSearchcriteria.CFSearchList;
        //    $rootScope = $scope.cftSearchcriteria;
        //    $rootScope.isAdvanceSearch = true;
        //    $cookieStore.put('cftBusinessSearchListcriteriaId', $scope.cftSearchcriteria.CFSearchList.CFTId);
        //    $cookieStore.put('cftBusinessSearchListcriteriaType', $scope.cftSearchcriteria.CFSearchList.Businesstype);

        //    $scope.navCharityFoundationOrganization();
        //}
        //else {
        //    $scope.cftSearchcriteria.CFSearchList.CFTId = id;
        //    $scope.cftSearchcriteria.CFSearchList.Businesstype = businessType;
        //    $rootScope.isAdvanceSearch = true;
        //    $cookieStore.put('cftBusinessSearchListcriteriaId', $scope.cftSearchcriteria.CFSearchList.CFTId);
        //    $cookieStore.put('cftBusinessSearchListcriteriaType', $scope.cftSearchcriteria.CFSearchList.Businesstype);
        //    $rootScope.data = $scope.cftSearchcriteria.CFSearchList;
        //    $rootScope = $scope.cftSearchcriteria;
        //    $scope.navigate($rootScope.data);
        //}
        //Ticket -- 3167
        $rootScope.isCFTBackButtonPressed = false;
        if (!flag) {
            $scope.cftSearchcriteria.CFTId = id;
            $scope.cftSearchcriteria.Businesstype = businessType;
            $rootScope.data = $scope.cftSearchcriteria;
            if ($scope.isShowAdvanceSearch) {
                $rootScope.isAdvanceSearch = true;
                $rootScope.isInitialSearch = null;
            }
            else {
                $rootScope.isInitialSearch = true;
                $rootScope.isAdvanceSearch = null;
            }
            //$rootScope.isAdvanceSearch = true;
            //$rootScope.isInitialSearch = true;
            $cookieStore.put('cftBusinessSearchListcriteriaId', $scope.cftSearchcriteria.CFSearchList.CFTId);
            $cookieStore.put('cftBusinessSearchListcriteriaType', $scope.cftSearchcriteria.CFSearchList.Businesstype);            
            // Folder Name: controller
            // File Name: rootController.js (you can search with file name in solution explorer)
            $scope.navCharityFoundationOrganization();
        }
        else {
            $scope.cftSearchcriteria.CFTId = id;
            $scope.cftSearchcriteria.Businesstype = businessType;
            $rootScope.isAdvanceSearch = true;
            $cookieStore.put('cftBusinessSearchListcriteriaId', $scope.cftSearchcriteria.CFSearchList.CFTId);
            $cookieStore.put('cftBusinessSearchListcriteriaType', $scope.cftSearchcriteria.CFSearchList.Businesstype);
            $rootScope.data = $scope.cftSearchcriteria;

            $scope.navigate($rootScope.data); // navigate method is available in this controller only.
        }

    }

    $scope.navigate = function (data) {
        $window.sessionStorage.removeItem('orgData');
        var obj = {
            org: data,
            viewMode: true,
            flag: true,
            isAdvanced: true,

        }
        $window.sessionStorage.setItem('orgData', JSON.stringify(obj));
        $window.open('#/organization', "_blank");
        $window.sessionStorage.removeItem('orgData');
    }

    $scope.showAdvanceSearch = function () {
        $scope.isShowErrorFlag = false;
        $scope.isShowAdvanceSearch = true;
        $scope.hideSearchButton = true;
        $scope.clearFun();
    };

    //$scope.$watch('cftSearchcriteria', function () {
    //    if ($scope.cftSearchcriteria.CFSearchList == undefined)
    //        return;
    //    if ($scope.cftSearchcriteria.CFSearchList.length == constant.ZERO) {
    //        $scope.totalCount = constant.ZERO;
    //        $scope.pagesCount = constant.ZERO;
    //        $scope.totalCount = constant.ZERO;
    //        $scope.page = constant.ZERO;
    //    }
    //}, true);

    $scope.cleartext = function (value) {
        switch (value) {
            case "RegistrationNumber":
                $scope.cftSearchcriteria.EntityName = null;
                $scope.cftSearchcriteria.FEINNo = null;
                $scope.cftSearchcriteria.UBINumber = null;
                break;
            case "FEINNo":
                $scope.cftSearchcriteria.RegistrationNumber = null;
                $scope.cftSearchcriteria.EntityName = null;
                $scope.cftSearchcriteria.UBINumber = null;
                break;
            case "UBINumber":
                $scope.cftSearchcriteria.RegistrationNumber = null;
                $scope.cftSearchcriteria.EntityName = null;
                $scope.cftSearchcriteria.FEINNo = null;
                break;
            case "OrganizationName":
                $scope.cftSearchcriteria.RegistrationNumber = null;
                $scope.cftSearchcriteria.FEINNo = null;
                $scope.cftSearchcriteria.UBINumber = null;
                $scope.cftSearchcriteria.SearchCriteria = "Contains";
                break;
            default:

        }
    };
});
wacorpApp.controller('charitiesOptionalQualifierController', function ($scope, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, focus) {

    // page load
    $scope.Init = function () {
        $scope.messages = messages;
        if ($rootScope.isOptionalReg != null && $rootScope.isOptionalReg != undefined && $rootScope.isOptionalReg == true)
            $scope.isOptionalHeader = "Charitable Organization Optional Registration";
        else if ($rootScope.isRenewal != null && $rootScope.isRenewal != undefined && $rootScope.isRenewal == true)
            $scope.isOptionalHeader = "Charitable Organization Optional Renewal";
        else if ($rootScope.isOptionalAmendment != null && $rootScope.isOptionalAmendment != undefined && $rootScope.isOptionalAmendment == true)
            $scope.isOptionalHeader = "Charitable Organization Optional Amendment";
        else if ($rootScope.isOptionalReRegistration != null && $rootScope.isOptionalReRegistration != undefined && $rootScope.isOptionalReRegistration == true)
            $scope.isOptionalHeader = "Charitable Organization Optional Re-Registration";
        if (localStorage.getItem("IsBack") == "true") {
            if ($rootScope.OptionalData != undefined && $rootScope.OptionalData != null)
                setQualiferData($rootScope.OptionalData); // setQualiferData method is available in this controller only.
        }
    };

    $scope.QualifierInfo = {
        IsIntegratedAuxiliary: null, IsPoliticalOrganization: null, IsRaisingFundsForIndividual: null,
        IsRaisingLessThan50000: null, IsAnyOnePaid: null, IsInfoAccurate: null,
        IntegratedAuxiliary: null, PoliticalOrganization: null, RaisingFundsForIndividual: null,
        RaisingLessThan50000: null, AnyOnePaid: null, InfoAccurate: null,
    };

    $scope.selectedEntity = { CFTId: null };

    // scope variables
    $scope.validateErrorMessage = false;
    $scope.isReview = false;
    $scope.IsQualified = true;
    $scope.isOptionalReg = true;
    $scope.isCharityReg = false;
    $scope.isOptionalHeader = "";

    $scope.continue = function (qualifier) {
        $scope.showErrorMessage = true;
        $scope.IsQualified = ($scope.QualifierInfo.IntegratedAuxiliary != null && $scope.QualifierInfo.PoliticalOrganization != null && $scope.QualifierInfo.RaisingFundsForIndividual != null
            && $scope.QualifierInfo.RaisingLessThan50000 != null && $scope.QualifierInfo.AnyOnePaid != null)
        $scope.isOptionalReg = $('#chkInInfoAccurate').is(':checked') ? true : false;
        if ($scope.IsQualified && $scope.isOptionalReg) {
            $scope.showErrorMessage = false;
            if (wacorpService.validateOptionalQualifiers($scope.QualifierInfo.IntegratedAuxiliary == "Yes" ? true : false, $scope.QualifierInfo.PoliticalOrganization == "Yes" ? true : false,
                $scope.QualifierInfo.RaisingFundsForIndividual == "Yes" ? true : false, $scope.QualifierInfo.RaisingLessThan50000 == "Yes" ? true : false, $scope.QualifierInfo.AnyOnePaid == "Yes" ? true : false)) {
                $rootScope.OptionalData = getQualiferData();
                $scope.selectedEntity.CFTId = $rootScope.CharityID;
                if ($rootScope.isOptionalReg == true) {
                    $location.path('/charitiesOptionalRegistration');
                }
                else if ($rootScope.isOptionalAmendment == true) {
                    $location.path('/charitiesOptionalAmendment/' +$scope.selectedEntity.CFTId);
                }
                else if ($rootScope.isRenewal == true) {
                    $location.path('/charitiesOptionalRenewal/' + $scope.selectedEntity.CFTId);
                }
                else if ($rootScope.isOptionalReRegistration == true || localStorage.getItem("isOptionalReRegistration") == "true") {
                    if ($rootScope.modal != null && $rootScope.modal != undefined) {
                        $rootScope.modal.IsOptionalRegistration = true;
                    }
                    localStorage.setItem("isOptionalReRegistration", true);
                    $location.path('/charitiesReRegistration/' + $scope.selectedEntity.CFTId);
                }
                //else if (localStorage.getItem('isClosure') == "true") {
                //    $location.path('/charitiesClosure/' + $scope.selectedEntity.CFTId);
                //}
            }
            else {
                //redirect if fails Qualifier questions
                $rootScope.OptionalData = null;
                $scope.selectedEntity.CFTId = $rootScope.CharityID;
                if ($rootScope.isOptionalReg == true) {
                    //wacorpService.confirmOkCancel($scope.messages.CharitableOrganization.qualifier1, function (resp) {
                    //    if (resp == "Ok" || resp == undefined) {
                    //        $location.path('/charitiesRegistration');
                    //    }
                    //    else { }
                    //});
                    $location.path('/charitiesRegistration');
                    // Folder Name: app Folder
                    // Alert Name: qualifier1 method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifier1);
                }
                else if($rootScope.isOptionalAmendment == true)
                {
                    $location.path('/charitiesAmendment/' + $scope.selectedEntity.CFTId);
                    // Folder Name: app Folder
                    // Alert Name: qualifierAmendment method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifierAmendment);
                }
                else if ($rootScope.isRenewal == true) {
                    //wacorpService.confirmOkCancel($scope.messages.CharitableOrganization.qualifierRenewal, function (resp) {
                    //    if (resp == "Ok" || resp == undefined) {
                    //        $location.path('/charitiesRenewal/' + $scope.selectedEntity.CFTId);
                    //    }
                    //    else { }
                    //});
                    // Folder Name: app Folder
                    // Alert Name: qualifierRenewal method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifierRenewal);
                    $location.path('/charitiesRenewal/' + $scope.selectedEntity.CFTId);
                }
                else if ($rootScope.isOptionalReRegistration == true) {
                    if ($rootScope.modal != null && $rootScope.modal != undefined) {
                        $rootScope.modal.IsOptionalRegistration = false;
                    }
                    localStorage.setItem("isOptionalReRegistration", false);
                    $location.path('/charitiesReRegistration/' + $scope.selectedEntity.CFTId);
                    // Folder Name: app Folder
                    // Alert Name: qualifierReRegistration method is available in alertMessages.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifierReRegistration);
                }
                localStorage.setItem("isOptional", false);
                localStorage.setItem('isOptionalReg', false);
            }
            localStorage.setItem("IsBack", false);
        }
        else if ($scope.validateQualifierQuestions1() && $scope.isOptionalReg) {
            //redirect if fails Qualifier questions
            $scope.IsQualified = true;
            $rootScope.OptionalData = null;
            $scope.selectedEntity.CFTId = $rootScope.CharityID;
            if ($rootScope.isOptionalReg == true) {
                //wacorpService.confirmOkCancel($scope.messages.CharitableOrganization.qualifier1, function (resp) {
                //    if (resp == "Ok" || resp == undefined) {
                //        $location.path('/charitiesRegistration');
                //    }
                //    else { }
                //});
                $location.path('/charitiesRegistration');
                // Folder Name: app Folder
                // Alert Name: qualifier1 method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifier1);
            }
            else if ($rootScope.isRenewal == true) {
                //wacorpService.confirmOkCancel($scope.messages.CharitableOrganization.qualifierRenewal, function (resp) {
                //    if (resp == "Ok" || resp == undefined) {
                //        $location.path('/charitiesRenewal/' + $scope.selectedEntity.CFTId);
                //    }
                //    else { }
                //});
                // Folder Name: app Folder
                // Alert Name: qualifierRenewal method is available in alertMessages.js (you can search with file name in solution explorer)
                wacorpService.alertDialog($scope.messages.CharitableOrganization.qualifierRenewal);
                $location.path('/charitiesRenewal/' +$scope.selectedEntity.CFTId);
            }
            localStorage.setItem("isOptional", false);
            localStorage.setItem('isOptionalReg', false);
        }
        localStorage.setItem("IsBack", false);
    };

    function getQualiferData() {
        $scope.QualifierInfo.IntegratedAuxiliary = $('#isIntegratedAuxiliary').is(':checked') ? "Yes" : "No";
        $scope.QualifierInfo.PoliticalOrganization = $('#isPoliticalOrganization').is(':checked') ? "Yes" : "No";
        $scope.QualifierInfo.RaisingFundsForIndividual = $('#isRaisingFundsForIndividual').is(':checked') ? "Yes" : "No";
        $scope.QualifierInfo.RaisingLessThan50000 = $('#isRaisingLessThan50000').is(':checked') ? "Yes" : "No";
        $scope.QualifierInfo.AnyOnePaid = $('#isAnyOnePaid').is(':checked') ? "Yes" : "No";
        $scope.QualifierInfo.InfoAccurate = $('#chkInInfoAccurate').is(':checked') ? "Yes" : "No";
        return $scope.QualifierInfo;
    }
    function setQualiferData(data) {
        if (data.InfoAccurate == "Yes")
            data.InfoAccurate = true;
        $scope.QualifierInfo = data;
    }

    $scope.$watch('QualifierInfo', function () {
        $scope.QualifierInfo.IsIntegratedAuxiliary = angular.isNullorEmpty($scope.QualifierInfo.IsIntegratedAuxiliary) ? false : $scope.QualifierInfo.IsIntegratedAuxiliary;
        $scope.QualifierInfo.IsPoliticalOrganization = angular.isNullorEmpty($scope.QualifierInfo.IsPoliticalOrganization) ? false : $scope.QualifierInfo.IsPoliticalOrganization;
        $scope.QualifierInfo.IsRaisingFundsForIndividual = angular.isNullorEmpty($scope.QualifierInfo.IsRaisingFundsForIndividual) ? false : $scope.QualifierInfo.IsRaisingFundsForIndividual;
        $scope.QualifierInfo.IsRaisingLessThan50000 = angular.isNullorEmpty($scope.QualifierInfo.IsRaisingLessThan50000) ? false : $scope.QualifierInfo.IsRaisingLessThan50000;
        $scope.QualifierInfo.IsAnyOnePaid = angular.isNullorEmpty($scope.QualifierInfo.IsAnyOnePaid) ? false : $scope.QualifierInfo.IsAnyOnePaid;
        $scope.QualifierInfo.IsInfoAccurate = angular.isNullorEmpty($scope.QualifierInfo.IsInfoAccurate) ? false : $scope.QualifierInfo.IsInfoAccurate;
    });


    //$scope.validateQualifierQuestions = function () {
    //    if ((!$scope.QualifierInfo.IsAnyOnePaid) && ($scope.QualifierInfo.IsIntegratedAuxiliary || $scope.QualifierInfo.IsPoliticalOrganization
    //         || $scope.QualifierInfo.IsRaisingFundsForIndividual || $scope.QualifierInfo.IsRaisingLessThan50000))
    //        return true;
    //    else
    //        return false;
    //};
    $scope.validateQualifierQuestions = function () {
        if ($scope.QualifierInfo.IntegratedAuxiliary != null && $scope.QualifierInfo.PoliticalOrganization != null && $scope.QualifierInfo.RaisingFundsForIndividual != null
            && $scope.QualifierInfo.RaisingLessThan50000 != null && $scope.QualifierInfo.AnyOnePaid != null) {
            $scope.IsQualified = true;
        }
        else {
            $scope.IsQualified = false;
        }
    };

    $scope.validateQualifierQuestions1 = function () {
        if ($scope.QualifierInfo.AnyOnePaid == "No" && ($scope.QualifierInfo.IntegratedAuxiliary == "No" && $scope.QualifierInfo.PoliticalOrganization == "No" && $scope.QualifierInfo.RaisingFundsForIndividual == "No"
                    && $scope.QualifierInfo.RaisingLessThan50000 == "No"))
            return false;
        else if ($scope.QualifierInfo.AnyOnePaid == "Yes" && ($scope.QualifierInfo.IntegratedAuxiliary == "Yes" && $scope.QualifierInfo.PoliticalOrganization == "Yes" && $scope.QualifierInfo.RaisingFundsForIndividual == "Yes"
                && $scope.QualifierInfo.RaisingLessThan50000 == "Yes"))
            return false;
        else if (($scope.QualifierInfo.AnyOnePaid == "No") && ($scope.QualifierInfo.IntegratedAuxiliary != null && $scope.QualifierInfo.PoliticalOrganization != null && $scope.QualifierInfo.RaisingFundsForIndividual != null
            && $scope.QualifierInfo.RaisingLessThan50000 != null)) {
            return true;
        }
        else {
            return false;
        }
    };

    $scope.validateAccurate = function () {
        $scope.isOptionalReg = $('#chkInInfoAccurate').is(':checked') ? true : false;
    };
});

wacorpApp.controller('oneClickARSearchController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $rootScope.modal = null; $rootScope.searchCriteria = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if (["Active", "Delinquent", "Administratively Dissolved", "Terminated"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            var data = { params: { businessId: $scope.selectedBusiness.BusinessID, filingTypeName: "Annual Report", isOnline: true, IsOneClickAR: true } };
            // ValidateBusinessStatus method is available in constants.js
            wacorpService.get(webservices.Common.ValidateBusinessStatus, data, function (response) {
                var result = response.data;

                //One click AR alert
                if (result.Key == 0 && result.Value != null) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(result.Value);
                    $location.path('/expressAnnualReportSearch/BusinessSearch'); //***** AR w/ changes - per Mike, KK, 11/18/2019 *****
                    return;
                }

                if (result.Key != 0) {
                    if (result.Key == BusinessStatus.AdministrativelyDissolved) {
                        var msg = result.Value.replace($scope.messages.AnnualReport.OneClickBeforeReplace, $scope.messages.AnnualReport.OneClickAfterReplace);
                        wacorpService.alertDialog(msg);
                        //wacorpService.confirmDialog(result.Value, function () {
                        //    $rootScope.annualReportModal = null;
                        //    $rootScope.transactionID = null;
                        //    $location.path('/oneClickAnnualReport/' + $scope.selectedBusiness.BusinessID);
                        //});
                    }
                        // key 4 for second message for AR
                    else if (result.Key == BusinessStatus.AdministrativelyTerminated) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    }
                    else
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    return;
                }
                else {
                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                    $rootScope.annualReportModal = null;
                    $rootScope.transactionID = null;
                    $location.path('/oneClickAnnualReport/' + $scope.selectedBusiness.BusinessID); //***** AR w/o changes - per Mike, KK, 11/18/2019 *****
                }

            }, function (response) {
                // Folder Name: app Folder
                // Alert Name: serverError method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.serverError);
            });
        }
        else {
            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.AnnualReport.ActiveAndDelinquentStatus);
        }
    }

    // back to home page
    $scope.back = function () {
        $location.path('/home');
    };

});



wacorpApp.controller('oneClickAnnualReportController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {

    /* --------Annual Report Functionality------------- */
    // scope variable
    $scope.modal = {};
    $scope.nobSelectedItems = [];
    $scope.authorizedSectionName = sectionNames.AUTHORIZEDPERSON;
    $scope.validateErrors = false;
    $scope.isPaymentZone = false;
    $scope.isShowContinue = true;
    $scope.isShowFeeList = false;
    $scope.isReview = false;
    $rootScope.payment = {};
    $rootScope.payment.cartItems = [];
    $rootScope.payment.isOneClickAR = false;
    $scope.feeListLayout = PartialViews.FilingFeeListView;
    $scope.feeDetailsDescription = "Annual Report Fee Details";
    function canShowFeeList() {
        if (!angular.isDefined($scope.modal.FeeList))
            return false;
        else if (angular.isNullorEmpty($scope.modal.FeeList))
            return false;
        return $scope.modal.FeeList.length > 0;
    }
    // scope load 
    $scope.InitAnnual = function () {
        $scope.messages = messages;
      
        // get business details
        var data = null;
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 2 is ADM DISSOLUTION/TERMINIATION
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 2 } };
        else
            data = { params: { businessID: $routeParams.id, transactionID: $rootScope.transactionID, filingTypeID: 2 } };
        if ($rootScope.annualReportModal == null || $rootScope.annualReportModal == undefined) {
            // AnnualReportCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.AnnualReportCriteria, data, function (response) {
                $scope.modal = response.data;

                $scope.disableFilings();  //BlockOnlineFilings

                if (!angular.isNullorEmpty($scope.modal.BusinessName)) {
                    $scope.modal.OldBusinessName = $scope.modal.BusinessName;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                    $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;

                    if ($scope.modal.BusinessTransaction.LastARFiledDate != null && $scope.modal.BusinessTransaction.LastARFiledDate != '') {
                        $scope.modal.ExpirationDateReview = new Date($scope.modal.BusinessTransaction.LastARFiledDate);
                        $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
                    }
                    else {
                        $scope.modal.ExpirationDateReview = new Date($scope.modal.NextARDueDate);
                        $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
                    }
                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                    $scope.modal.AuthorizedPerson.PersonType = ResultStatus.INDIVIDUAL;
                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                    // $scope.modal.BINAICSCodeDesc=!angular.isNullorEmpty($scope.modal.BINAICSCodeDesc)?$scope.modal.BINAICSCodeDesc.replace(/&amp;/g, '&'):"";
                    //$scope.modal.BINAICSCodeDesc = !angular.isNullorEmpty($scope.modal.BIOtherDescription)?$scope.modal.BINAICSCodeDesc+','+$scope.modal.BIOtherDescription:$scope.modal.BINAICSCodeDesc;
                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        // Folder Name: app Folder
                        // Alert Name: HasActiveFilings method is available in alertMessages.js
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }

                    // invalid po box address in street address 
                    if ($scope.modal.PrincipalOffice.PrincipalStreetAddress
                        && (wacorpService.validatePoBox($scope.modal.PrincipalOffice.PrincipalStreetAddress.StreetAddress1) || wacorpService.validatePoBox($scope.modal.PrincipalOffice.PrincipalStreetAddress.StreetAddress1))
                        ) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        var isACP = wacorpService.validatePoBoxAddress($scope.modal.PrincipalOffice.PrincipalStreetAddress);
                        if (!isACP)
                            $scope.modal.PrincipalOffice.PrincipalStreetAddress.invalidPoBoxAddress = true;
                    }
                }
            }, function (response) { $scope.isShowContinue = false; });
        }
        else {
            $scope.modal = $rootScope.annualReportModal;
        }



    };

    // back to annual report business serarch
    $scope.back = function () {        
        $location.path('/oneClickARSearch/BusinessSearch');
    };

    // validate & continue annual report payment
    $scope.ClickToPay = function (annualReportForm) {
        
        if (!angular.isDefined($scope.modal.BusinessStatus)) {
            // Folder Name: app Folder
            // Alert Name: UnableFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.AnnualReport.UnableFilingMsg);
            return;
        }

        if (["Active", "Delinquent"].indexOf($scope.modal.BusinessStatus) < 0) {
            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.AnnualReport.ActiveAndDelinquentStatus);
            return;
        }

        if (!$scope.modal.IsEligibleFilingType) {
            // Folder Name: app Folder
            // Alert Name: InvalidFilingTypeMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.AnnualReport.InvalidFilingTypeMsg);
            return;
        }

        $scope.isReview = true;
        $scope.validateErrors = true;
        $scope.isPaymentZone = false;

        var isAnnualReportFormValidate = ($scope.annualReportForm.$valid);

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;

        //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
        if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	        $scope.modal.IsEmailOptionChecked = false;
        }

        var isAuthorizedPersonValidate = ($scope.annualReportForm.AuthorizedPersonForm.$valid);

        var isPrincipalOfficeValidate = !$scope.modal.PrincipalOffice.PrincipalStreetAddress.invalidPoBoxAddress;

        var isFormsValid = isAuthorizedPersonValidate && isAnnualReportFormValidate && isRegisteredAgentValidStates && isPrincipalOfficeValidate;

        
        if (isFormsValid) {
            $scope.validateErrors = false;
            $rootScope.annualReportModal = $scope.modal;
            $scope.modal.UBI = $scope.modal.UBINumber;
            $scope.modal.FilingType = $scope.modal.BusinessFiling.FilingTypeName;
            $scope.modal.CreatedDateTime = new Date();
            $scope.modal.Amount = $scope.modal.BusinessTransaction.FilingFee;
            $scope.modal.FilingAmount = $scope.modal.BusinessTransaction.FilingFee;
            $scope.modal.IsExpedite = true;
            $scope.modal.PracessingAmount = $scope.modal.BusinessTransaction.PracessingAmount;
            $scope.modal.ID = 1;
            $scope.modal.BusinessTypeId = $scope.modal.BusinessTypeID;
            $scope.modal.FilingTypeID = $scope.modal.BusinessFiling.FilingTypeID;

            if ($rootScope.payment.cartItems.length == 0) {
                $scope.modal.BusinessName = $scope.modal.OldBusinessName;
                $scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.DBABusinessName) ? $scope.modal.BusinessName + " DBA " + $scope.modal.DBABusinessName : $scope.modal.BusinessName;
                $rootScope.payment.cartItems.push(angular.copy($scope.modal));
            }
            $rootScope.payment.Amount = $scope.modal.BusinessTransaction.FilingFee;
            $rootScope.payment.isUserPayment = false;
            $rootScope.payment.isOneClickAR = true;
            $scope.isPaymentZone = true;
        }
        else {
            $scope.isReview = false;
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };

    $scope.oneClickARBackFromPayment = function () {
        $scope.isPaymentZone = false;
        $scope.isReview = false;
        $location.path('/oneClickAnnualReport/' + $scope.modal.BusinessID);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    $scope.oneClickARMakePayment = function (paymentModel) {
        $scope.modal.BusinessName = $scope.modal.OldBusinessName;

        // get review HTML
        var $reviewHTML = $("section.panel-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");
        
        $scope.modal.OneClickARPayment = paymentModel;
        // work order number
        $scope.modal.OneClickARPayment.WorkOrderNumber = $scope.WorkOrderNumber;

        wacorpService.post(webservices.OnlineFiling.OneClickARAddToCart, $scope.modal, function (regResponse) {
            // work order number
            $scope.WorkOrderNumber = regResponse.data.OneClickARPayment.WorkOrderNumber
            
            if (regResponse.data.IsFilingSuccess) {
                $scope.isPaymentZone = false;
                $rootScope.payment.isOneClickAR = false;
                $rootScope.paymentDone = regResponse.data;
                $location.path('/oneClickAnnualReportSuccess');
            }
            else {
                // Payment Amount Mismatched
                $rootScope.isPlaceYourOrderButtonDisable = false;

                if (regResponse.data.Message.StatusMode == 1) {
                    // Folder Name: app Folder
                    // Alert Name: PaymentAmountMisMatch method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.ShoppingCart.PaymentAmountMisMatch);
                }
                else if (regResponse.data.Message.Text == null || regResponse.data.Message.Text == "" || regResponse.data.Message.Text == "<br/>") {
                    // Folder Name: app Folder
                    // Alert Name: payment method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.ShoppingCart.payment);
                } else {
                    // Folder Name: app Folder
                    // Alert Name: Text method is available in alertMessages.js 
                    wacorpService.alertDialog(regResponse.data.Message.Text);
                }
            }
        }, function (error) {
            $rootScope.isPlaceYourOrderButtonDisable = false;
            $scope.isexception = true;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });
    }

    $scope.viewTransactionDocumentsList = function getTransactionDocumentsList(Transactionid) {
        var criteria = {
            ID: Transactionid
        };
        // GetTransactionDocumentsListForAR method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.GetTransactionDocumentsListForAR, criteria,
            function (response) {
                if (response.data != null) {
                    $scope.transactionDocumentsList = angular.copy(response.data);
                    $("#divSearchResult").modal('toggle');
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: noDataFound method is available in alertMessages.js 
                    wacorpService.alertDialog($scope.messages.noDataFound);
            },
            function (response) {
                // Folder Name: app Folder
                // Alert Name: Message method is available in alertMessages.js 
                wacorpService.alertDialog(response.data.Message);
            }
        );
    }

    //BlockOnlineFilings
    $scope.disableFilings = function () {
        //BLOCK NP
        if ($scope.modal.BusinessTypeID === 73 ||
            $scope.modal.BusinessTypeID === 74 ||
            $scope.modal.BusinessTypeID === 26 ||
            $scope.modal.BusinessTypeID === 27) {

            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.AnnualReport.disabledFiling);
            $scope.back();

        };
        //BLOCK NP
    }
    //BlockOnlineFilings

});
wacorpApp.controller('expressAnnualReportSearchController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $rootScope.modal = null; $rootScope.searchCriteria = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if (["Active", "Delinquent", "Administratively Dissolved", "Terminated"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            var data = { params: { businessId: $scope.selectedBusiness.BusinessID, filingTypeName: "Annual Report", isOnline: true } };
            // ValidateBusinessStatus method is available in constants.js
            wacorpService.get(webservices.Common.ValidateBusinessStatus, data, function (response) {
                var result = response.data;

                if (result.Key != 0) {
                    if (result.Key == BusinessStatus.AdministrativelyDissolved) {
                        var msg = result.Value.replace($scope.messages.AnnualReport.OneClickBeforeReplace, $scope.messages.AnnualReport.OneClickAfterReplace);
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(msg);
                        //wacorpService.confirmDialog(result.Value, function () {
                        //    $rootScope.annualReportModal = null;
                        //    $rootScope.transactionID = null;
                        //    $location.path('/oneClickAnnualReport/' + $scope.selectedBusiness.BusinessID);
                        //});
                    }
                        // key 4 for second message for AR
                    else if (result.Key == BusinessStatus.AdministrativelyTerminated) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    }
                    else
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    return;
                }
                else {
                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                    $rootScope.annualReportModal = null;
                    $rootScope.transactionID = null;
                    $location.path('/expressAnnualReport/' + $scope.selectedBusiness.BusinessID);
                }
            }, function (response) {
                // Folder Name: app Folder
                // Alert Name: serverError method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.serverError);
            });
        }
        else {
            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.AnnualReport.ActiveAndDelinquentStatus);
        }
    }

    // back to home page
    $scope.back = function () {
        $location.path('/home');
    };
});
wacorpApp.controller('expressAnnualReportController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if (["Active", "Delinquent", "Administratively Dissolved", "Terminated"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            var data = { params: { businessId: $scope.selectedBusiness.BusinessID, filingTypeName: "Annual Report", isOnline: true } };
            // ValidateBusinessStatus method is available in constants.js
            wacorpService.get(webservices.Common.ValidateBusinessStatus, data, function (response) {
                var result = response.data;
                if (result.Key != 0) {
                    if (result.Key == BusinessStatus.AdministrativelyDissolved) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.confirmDialog(result.Value, function () {
                            $rootScope.reinstatementModal = null;
                            $rootScope.transactionID = null;
                            $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);
                        });
                    }
                        // key 4 for second message for AR
                    else if (result.Key == BusinessStatus.AdministrativelyTerminated) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    }
                    else
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    return;
                }
                else {
                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                    $rootScope.annualReportModal = null;
                    $rootScope.transactionID = null;
                    $location.path('/expressAnnualReport/' + $scope.selectedBusiness.BusinessID); //***** AR w/ changes - per Mike, KK, 11/18/2019 *****
                }
            }, function (response) {
                // Folder Name: app Folder
                // Alert Name: serverError method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.serverError);
            });
        }
        else {
            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.AnnualReport.ActiveAndDelinquentStatus);
        };
    }


    /* --------Express Annual Report Functionality------------- */

    // scope variable
    $scope.modal = {};
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    $scope.nobSelectedItems = [];
    $scope.authorizedSectionName = sectionNames.AUTHORIZEDPERSON;
    $scope.validateErrors = false;
    $scope.validateAgentErrors = false;
    $scope.principalsCount = 0;
    $scope.isShowContinue = true;
    $scope.isShowFeeList = false;
    $scope.feeListLayout = PartialViews.FilingFeeListView;
    $scope.feeDetailsDescription = "Annual Report Fee Details";
    function canShowFeeList() {
        if (!angular.isDefined($scope.modal.FeeList))
            return false;
        else if (angular.isNullorEmpty($scope.modal.FeeList))
            return false;
        return $scope.modal.FeeList.length > 0;
    }
    // scope load 
    $scope.Init = function () {
            $scope.messages = messages;
            getNaicsCodes(); // getNaicsCodes method is available in this controller only.
            getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in this controller only.
            // get business details
            if ($rootScope.modal != null || $rootScope.modal != undefined) {
                $rootScope.annualReportModal = $rootScope.modal;
                //$rootScope.modal = null;
            }
            var data = null;
            if ($rootScope.transactionID > 0)
                // here filingTypeID: 2 is ADM DISSOLUTION/TERMINIATION
                data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 2 } };
            else
                data = { params: { businessID: $routeParams.id, transactionID: $rootScope.transactionID, filingTypeID: 2 } };
            if ($rootScope.annualReportModal == null || $rootScope.annualReportModal == undefined) {
                // AnnualReportCriteria method is available in constants.js
                wacorpService.get(webservices.OnlineFiling.AnnualReportCriteria, data, function (response) {
                    $scope.modal = response.data;

                    $scope.disableFilings();  //BlockOnlineFilings

                    if (!angular.isNullorEmpty($scope.modal.BusinessName)) {
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                        $scope.modal.EffectiveDateType = $scope.modal.EffectiveDate == null ? 'DateOfFiling' : $scope.modal.EffectiveDateType;
                        $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";
                        $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                        $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;
                        $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertStringToObject($scope.modal.NatureOfBusinessEntity.NAICSCode);
                        $scope.modal.NatureOfBusinessEntity.IsOtherNAICS = !angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.OtherDescription) ? true : false;
                        $scope.modal.NatureOfBusinessEntity.BusinessID = $scope.modal.BusinessID;
                        $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                        $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;
                        $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                        $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                        //   $scope.modal.BINAICSCodeDesc=!angular.isNullorEmpty($scope.modal.BINAICSCodeDesc)?$scope.modal.BINAICSCodeDesc.replace(/&amp;/g, '&'):"";
                        // $scope.modal.BINAICSCodeDesc = !angular.isNullorEmpty($scope.modal.BIOtherDescription)?$scope.modal.BINAICSCodeDesc+','+$scope.modal.BIOtherDescription:$scope.modal.BINAICSCodeDesc;
                        if ($scope.modal.IsActiveFilingExist) {
                            //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                            // Folder Name: app Folder
                            // Alert Name: HasActiveFilings method is available in alertMessages.js
                            wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                            });
                        }
                        $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                        $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                        $scope.modal.OldBusinessName = $scope.modal.BusinessName;
                    }
                }, function (response) { $scope.isShowContinue = false; });

                

            }
            else {
                $scope.modal = $rootScope.annualReportModal;
            
                if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && angular.isArray($scope.modal.NatureOfBusinessEntity.NAICSCode) && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
                    $scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode.split(',');
                }
                else {
                    $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode;
                }
                if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                    $scope.modal.EffectiveDate = "";
            }

            
    };

    // back to express annual report business serarch
    $scope.back = function () {
        $location.path('/expressAnnualReportSearch/BusinessSearch');
    };

    // validate & continue express annual report for review
    $scope.ContinueSave = function (annualReportForm) {
        if (!angular.isDefined($scope.modal.BusinessStatus)) {
            // Folder Name: app Folder
            // Alert Name: UnableFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.AnnualReport.UnableFilingMsg);
            return;
        }

        if (["Active", "Delinquent"].indexOf($scope.modal.BusinessStatus) < 0) {
            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.AnnualReport.ActiveAndDelinquentStatus);
            return;
        }

        if (!$scope.modal.IsEligibleFilingType) {
            // Folder Name: app Folder
            // Alert Name: InvalidFilingTypeMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.AnnualReport.InvalidFilingTypeMsg);
            return;
        }

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[annualReportForm]);

        $scope.validateErrors = true;
        // registered agent
        $scope.validateAgentErrors = $scope.modal.Agent.IsNewAgent ? true : ($scope.modal.Agent.IsAgentEdit ? true : false);
        $scope.validateOneAgent = $scope.modal.Agent.AgentID == 0 && !$scope.modal.Agent.IsNewAgent;

        // registered agent
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
                   ((!$scope.modal.Agent.IsNewAgent ? ($scope.modal.Agent.AgentID != 0 && $scope.modal.Agent.StreetAddress.FullAddress) ? true : (false && !$scope.modal.Agent.IsNoncommercialStreetAddress) : true) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 : true) && $scope[annualReportForm].RegisteredAgentForm.$valid));

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;
        $scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial && !isRegisteredAgentValid ? true : false;
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        $scope.checkRAStreetAddress = wacorpService.isRAStreetAddressValid($scope.modal.Agent.StreetAddress);//to check RA street address is valid or not

        $scope.validateNonCommercialStreetAddress = !isRegisteredAgentValid && !$scope.modal.Agent.IsNoncommercialStreetAddress && !$scope.checkRAStreetAddress ? true : false;

        // nature of business
        $scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusinessEntity.IsOtherNAICS ? $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0 : ($scope.modal.NatureOfBusinessEntity.IsOtherNAICS && !$scope.modal.NatureOfBusinessEntity.OtherDescription ? false : true)));

            //!($scope.modal.NatureOfBusinessEntity.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusinessEntity.OtherDescription == null ? true : $scope.modal.NatureOfBusinessEntity.OtherDescription.length <= 0)));

        // nature of business for non profit
        $scope.validateNatureOfBusinessNonProfit = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusinessEntity.IsOtherNAICS ? $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0 : ($scope.modal.NatureOfBusinessEntity.IsOtherNAICS && !$scope.modal.NatureOfBusinessEntity.OtherDescription ? false : true)));

            //!($scope.modal.NatureOfBusinessEntity.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusinessEntity.OtherDescription == null ? true : $scope.modal.NatureOfBusinessEntity.OtherDescription.length <= 0)));

        // general partners
        $scope.isGeneralPartnersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartners, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount() > 0);

        // general partners signature confirmation
        $scope.isGeneralPartnersAignConfimValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GeneralPartnersSignatureConfirmation, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                    ($scope.modal.isGeneralPartnerSignatureConfirmation == "true" || $scope.modal.isGeneralPartnerSignatureConfirmation == true));

        // governing persons
        $scope.isGoverningPersonValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.ExpressANprincipalsCount("GOVERNINGPERSON") > 0);

        // trustees
        $scope.isTrusteesValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.Trustees, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        $scope.principalsCount() > 0);

        //// principal office in wa
        //$scope.isPrincipalOfficeInWAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                    $scope[annualReportForm].PrincipalOffice.$valid);

        // principal office
        $scope.isPrincipalOfficeValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
                                                $scope[annualReportForm].PrincipalOffice.$valid);

            //(!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOffice, $scope.modal, $scope.modal.BusinessTypeID) ||
            //                                $scope[annualReportForm].PrincipalOffice.$valid);

        //$scope.modal.PrincipalOfficeInWA.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOfficeInWA.PrincipalMailingAddress);
        $scope.modal.PrincipalOffice.PrincipalMailingAddress.FullAddress = wacorpService.fullAddressService($scope.modal.PrincipalOffice.PrincipalMailingAddress);

        // purpose and powers
        $scope.isPurposeAndPowersValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PurposeAndPowers, $scope.modal, $scope.modal.BusinessTypeID) ||
                                        ($scope[annualReportForm].PurposeAndPowers.$valid));

        var isEffectiveDateValid = ($scope[annualReportForm].EffectiveDate.$valid);
        var isCorrespondenceAddressValid = $scope[annualReportForm].CorrespondenceAddress.$valid;

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;

        var isOtherFormsValid = (isFormValid($scope[annualReportForm].AttestationOfSocialPurposeForm)
                                && isFormValid($scope[annualReportForm].AuthorizedPersonForm)
                                && isFormValid($scope[annualReportForm].DescriptionOfBusinessIncludedForm)
                                && isFormValid($scope[annualReportForm].AttestationOfSocialPurposeForm)
                                && isFormValid($scope[annualReportForm].GeneralPartnersSignatureConfirmationForm)
                                && isFormValid($scope[annualReportForm].NumberOfPartnersForm)
                                && isFormValid($scope[annualReportForm].PurposeOfCorporationForm
                                && $scope.isPrincipalOfficeValid));

        if (isRegisteredAgentValid
            && $scope.validateNatureOfBusiness
            && $scope.validateNatureOfBusinessNonProfit
            && $scope.isGeneralPartnersAignConfimValid
            && $scope.isGoverningPersonValid
            //&& $scope.isPrincipalOfficeInWAValid
            && $scope.isTrusteesValid
            && $scope.isPrincipalOfficeValid
            && $scope.isPurposeAndPowersValid
            && isOtherFormsValid
            && isEffectiveDateValid
            && isAdditionalUploadValid && isCorrespondenceAddressValid && isRegisteredAgentValidStates) {

            if ($scope.modal.BusinessTransaction.LastARFiledDate != null && $scope.modal.BusinessTransaction.LastARFiledDate != '') {
                $scope.modal.ExpirationDateReview = new Date($scope.modal.BusinessTransaction.LastARFiledDate);
                $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
            }
            else {
                $scope.modal.ExpirationDateReview = new Date($scope.modal.NextARDueDate);
                $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
            }

            $scope.modal.IsReveiwPDFFieldsShow = true;
            $scope.isReviewAgent = false;
            $scope.validateErrors = false;
            $scope.validateRegAgentErrors = false;
            $scope.validatePrincipalOfficeInWAErrors = false;
            $scope.validateprincipalErrors = false;
            $scope.modal.BusinessFiling.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.EffectiveDate;
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	            $scope.modal.IsEmailOptionChecked = false;
            }
            $rootScope.annualReportModal = $scope.modal;
            $scope.isShowFeeList = canShowFeeList(); // canShowFeeList method is available in this controller only.
            if (!$scope.isShowFeeList)
                $location.path("/expressAnnualReportReview");
        }
        else
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // bind Naics codes to multi select dropdpwn
    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
            //$scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode;
        });
    }

    // bind Naics codes For Non Profit to multi select dropdpwn
    function getNaicsCodesNonProfit() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            $scope.NaicsCodesNonProfit = response.data;
            //$scope.modal.NatureOfBusinessEntity.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusinessEntity.NAICSCode) ? [] : $scope.modal.NatureOfBusinessEntity.NAICSCode;
        });
    }

    //  check whether form is valid / not
    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    // validate principals count
    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    $scope.ExpressANprincipalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '200px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };

    $scope.clearOtherDescription = function () {
        $scope.modal.NatureOfBusinessEntity.OtherDescription = null;
    }

    //to trim empty spaces for NOB Other
    $scope.validateOtherNOB = function () {
         
        $scope.modal.NatureOfBusinessEntity.OtherDescription = $scope.modal.NatureOfBusinessEntity.OtherDescription ? angular.copy($scope.modal.NatureOfBusinessEntity.OtherDescription.trim()) : (($scope.modal.NatureOfBusinessEntity.OtherDescription == undefined || $scope.modal.NatureOfBusinessEntity.OtherDescription == "") ? $scope.modal.NatureOfBusinessEntity.OtherDescription = null : $scope.modal.NatureOfBusinessEntity.OtherDescription);
    }

    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.NatureOfBusinessEntity.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusinessEntity.OtherDescription == null ? true : $scope.modal.NatureOfBusinessEntity.OtherDescription.length <= 0))
    }

    //BlockOnlineFilings
    $scope.disableFilings = function () {
        //BLOCK NP

        if ($scope.modal.BusinessTypeID === 73 ||
            $scope.modal.BusinessTypeID === 74 ||
            $scope.modal.BusinessTypeID === 26 ||
            $scope.modal.BusinessTypeID === 27) {

            // Folder Name: app Folder
            // Alert Name: ActiveAndDelinquentStatus method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.AnnualReport.disabledFiling);
            $scope.back();

        };
        //BLOCK NP
    }
    //BlockOnlineFilings
});
wacorpApp.controller('expressAnnualReportReviewController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService) {
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    $scope.isPaymentZone = false;
    $scope.isShowContinue = true;
    $scope.isShowFeeList = false;
    $rootScope.payment = {};
    $rootScope.payment.cartItems = [];
    $rootScope.payment.isExpressAR = false;
    $scope.authorizedSectionName = sectionNames.AUTHORIZEDPERSON;
    //scope load
    $scope.Init = function () {
        if (!angular.isNullorEmpty($rootScope.annualReportModal)) {
            $scope.modal = $rootScope.annualReportModal;

            if ($scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID)) {
                getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in this controller only.
            }
            else {
                getNaicsCodes();// getNaicsCodes method is available in this controller only.
            }
        }
        else
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            $scope.navAnnualReport();
    }

    // validate & continue annual report payment
    $scope.ClickToPay = function (annualReportForm) {
        $rootScope.annualReportModal = $scope.modal;
        $scope.modal.UBI = $scope.modal.UBINumber;
        $scope.modal.FilingType = $scope.modal.BusinessFiling.FilingTypeName;
        $scope.modal.CreatedDateTime = new Date();
        $scope.modal.Amount = $scope.modal.BusinessTransaction.FilingFee;
        $scope.modal.FilingAmount = $scope.modal.BusinessTransaction.FilingFee;
        $scope.modal.IsExpedite = true;
        $scope.modal.PracessingAmount = $scope.modal.BusinessTransaction.PracessingAmount;
        $scope.modal.ID = 1;
        $scope.modal.BusinessTypeId = $scope.modal.BusinessTypeID;
        $scope.modal.FilingTypeID = $scope.modal.BusinessFiling.FilingTypeID;

        if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && angular.isArray($scope.modal.NatureOfBusinessEntity.NAICSCode) && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusinessEntity.NAICSCode);
        }
        else {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode;
        }

        // get review HTML
        var $reviewHTML = $("section.panel-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");

        if ($rootScope.payment.cartItems.length == 0) {
            $scope.modal.BusinessName = $scope.modal.OldBusinessName;
            $scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.DBABusinessName) ? $scope.modal.BusinessName + " DBA " + $scope.modal.DBABusinessName : $scope.modal.BusinessName;
            $rootScope.payment.cartItems.push(angular.copy($scope.modal));
        }
        $rootScope.payment.Amount = $scope.modal.BusinessTransaction.FilingFee;
        $rootScope.payment.isUserPayment = false;
        $rootScope.payment.isExpressAR = true;
        $scope.isPaymentZone = true;
    };

    // back to annual report flow
    $scope.back = function () {
        $rootScope.annualReportModal = $scope.modal;
        if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && angular.isArray($scope.modal.NatureOfBusinessEntity.NAICSCode) && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
            $rootScope.annualReportModal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode.join(",");
        }
        else {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode;
        }
        $scope.isPaymentZone = false;
        $location.path('/expressAnnualReport/' + $scope.modal.BusinessID);
    };

    $scope.expressARBackFromPayment = function () {
        $scope.isPaymentZone = false;
        $location.path('/expressAnnualReportReview');
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // get selected Naics Codes
    function getNaicsCodes() {
        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc = '';
        if (angular.isArray($scope.modal.NatureOfBusinessEntity.NAICSCode)) {
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            lookupService.NaicsCodes(function (response) {
                var principalsList = $scope.modal.NatureOfBusinessEntity.NAICSCode.filter(function (naicscode) {
                    for (var i = 0; i < response.data.length; i++) {
                        if (naicscode == response.data[i].Key) {
                            $scope.NaicsCodes.push(response.data[i]);
                            $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc += $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                            break;
                        }
                    }
                });
            });
        }
    }

    // get selected Naics Codes for Non Profit
    function getNaicsCodesNonProfit() {
        $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc = '';
        if (angular.isArray($scope.modal.NatureOfBusinessEntity.NAICSCode)) {
            // Service Folder: services
            // File Name: lookupService.js (you can search with file name in solution explorer)
            lookupService.NaicsCodesNonProfit(function (response) {
                var principalsList = $scope.modal.NatureOfBusinessEntity.NAICSCode.filter(function (naicscode) {
                    for (var i = 0; i < response.data.length; i++) {
                        if (naicscode == response.data[i].Key) {
                            $scope.NaicsCodesNonProfit.push(response.data[i]);
                            $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc += $scope.modal.NatureOfBusinessEntity.NAICSCodeDesc == '' ? response.data[i].Value : ', ' + response.data[i].Value;
                            break;
                        }
                    }
                });
            });
        }
    }

    $scope.expressARMakePayment = function (paymentModel) {
        $scope.modal.BusinessName = $scope.modal.OldBusinessName;
        $scope.modal.OneClickARPayment = paymentModel;
        // work order number
        $scope.modal.OneClickARPayment.WorkOrderNumber = $scope.WorkOrderNumber;

        if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && angular.isArray($scope.modal.NatureOfBusinessEntity.NAICSCode) && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusinessEntity.NAICSCode);
        }
        else {
            $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.modal.NatureOfBusinessEntity.NAICSCode;
        }
        // ExpressARAddToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.ExpressARAddToCart, $scope.modal, function (regResponse) {
            // work order number
            $scope.WorkOrderNumber = regResponse.data.OneClickARPayment.WorkOrderNumber

            if (regResponse.data.IsFilingSuccess) {
                $scope.isPaymentZone = false;
                $rootScope.payment.isExpressAR = false;
                $rootScope.paymentDone = regResponse.data;
                //$location.path('/oneClickAnnualReportSuccess');
                $location.path('/expressAnnualReportSuccess');
            }
            else {// Payment Amount Mismatched
                $rootScope.isPlaceYourOrderButtonDisable = false;
                // here StatusMode = 1 is payment amount mismatch
                if (regResponse.data.Message.StatusMode == 1) {
                    // Folder Name: app Folder
                    // Alert Name: PaymentAmountMisMatch method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.ShoppingCart.PaymentAmountMisMatch);
                }
                else if (regResponse.data.Message.Text == null || regResponse.data.Message.Text == "" || regResponse.data.Message.Text == "<br/>") {
                    // Folder Name: app Folder
                    // Alert Name: payment method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.ShoppingCart.payment);
                } else {
                    // Folder Name: app Folder
                    // Alert Name: Text method is available in alertMessages.js
                    wacorpService.alertDialog(regResponse.data.Message.Text);
                }
                if ($scope.modal.NatureOfBusinessEntity.NAICSCode != null && $scope.modal.NatureOfBusinessEntity.NAICSCode.length > 0) {
                    $scope.modal.NatureOfBusinessEntity.NAICSCode = $scope.convertStringToObject($scope.modal.NatureOfBusinessEntity.NAICSCode);
                }
            }
        }, function (error) {
            $rootScope.isPlaceYourOrderButtonDisable = false;
            $scope.isexception = true;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(error.data);
        });
    }

    $scope.viewTransactionDocumentsList = function getTransactionDocumentsList(Transactionid) {
        var criteria = {
            ID: Transactionid
        };
        // GetTransactionDocumentsListForAR method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.GetTransactionDocumentsListForAR, criteria,
            function (response) {
                if (response.data != null) {
                    $scope.transactionDocumentsList = angular.copy(response.data);
                    $("#divSearchResult").modal('toggle');
                }
                else
                    // Folder Name: app Folder
                    // Alert Name: noDataFound method is available in alertMessages.js
                    wacorpService.alertDialog($scope.messages.noDataFound);
            },
            function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data.Message);
            }
        );
    }
});
wacorpApp.controller('requalificationController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, ScopesData, focus, $timeout) {

    /* --------Business Search Functionality------------- */
    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    function getNavigation() {
        if ([ResultStatus.Terminated].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            var data = { params: { businessId: $scope.selectedBusiness.BusinessID, filingTypeName: "Requalification", isOnline: true } };
            // ValidateBusinessStatus method is available in constants.js
            wacorpService.get(webservices.Common.ValidateBusinessStatus, data, function (response) {
                var result = response.data;
                if (result.Key != 0) {
                    if (result.Key == BusinessStatus.Terminated) {
                        wacorpService.confirmDialog(result.Value, function () {
                            var data1 = { params: { businessId: $scope.selectedBusiness.BusinessID } };
                            // isrequalificationARWithInDueDate method is available in constants.js
                            wacorpService.get(webservices.Common.isrequalificationARWithInDueDate, data1, function (result) {
                                var result1 = result.data;
                                if (result1.isAddCurrentARFee) {
                                    // Folder Name: app Folder
                                    // Alert Name: requalificationARalert method is available in alertMessages.js 
                                    wacorpService.confirmDialog($scope.messages.Requalification.requalificationARalert, function () {
                                        $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                        $rootScope.requalificationModal = null;
                                        $rootScope.transactionID = null;
                                        $rootScope.addCurrentARFee = 'Y';
                                        $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                                    },
                                        function () {
                                            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                            $rootScope.requalificationModal = null;
                                            $rootScope.transactionID = null;
                                            $rootScope.addCurrentARFee = 'N';
                                            $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                                        }
                                    );
                                }
                                else {
                                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                    $rootScope.requalificationModal = null;
                                    $rootScope.transactionID = null;
                                    $rootScope.addCurrentARFee = 'N';
                                    $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                                }
                            },

                             function (response) {
                                 // Folder Name: app Folder
                                 // Alert Name: serverError method is available in alertMessages.js 
                                 wacorpService.alertDialog($scope.messages.serverError);
                             });

                        });
                    }
                        // key 4 for second message for AR
                    else
                        // Service Folder: services
                        // File Name: wacorpService.js (you can search with file name in solution explorer)
                        wacorpService.alertDialog(result.Value);
                    return;
                }
                else {
                    var data1 = { params: { businessId: $scope.selectedBusiness.BusinessID } };
                    // isrequalificationARWithInDueDate method is available in constants.js
                    wacorpService.get(webservices.Common.isrequalificationARWithInDueDate, data1, function (result) {
                        var result1 = result.data;
                        if (result1.isAddCurrentARFee) {
                            // Folder Name: app Folder
                            // Alert Name: requalificationARalert method is available in alertMessages.js 
                            wacorpService.confirmDialog($scope.messages.Requalification.requalificationARalert, function () {
                                $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                $rootScope.requalificationModal = null;
                                $rootScope.transactionID = null;
                                $rootScope.addCurrentARFee = 'Y';
                                $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                            },
                                function () {
                                    $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                                    $rootScope.requalificationModal = null;
                                    $rootScope.transactionID = null;
                                    $rootScope.addCurrentARFee = 'N';
                                    $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                                }
                            );
                        }
                        else {
                            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
                            $rootScope.requalificationModal = null;
                            $rootScope.transactionID = null;
                            $rootScope.addCurrentARFee = 'N';
                            $location.path('/Requalification/' + $scope.selectedBusiness.BusinessID);
                        }
                    },

                     function (response) {
                         // Folder Name: app Folder
                         // Alert Name: serverError method is available in alertMessages.js 
                         wacorpService.alertDialog($scope.messages.serverError);
                     });
                }

            }, function (response) {
                // Folder Name: app Folder
                // Alert Name: serverError method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.serverError);
            });
        }
        else {
            // Folder Name: app Folder
            // Alert Name: administrativeDissolvedMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.Requalification.administrativeDissolvedMsg);
        }
    }

    /* --------Annual Report Functionality------------- */

    // scope variable
    $scope.modal = {};
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    $scope.validateErrors = false;
    $scope.validateAgentErrors = false;
    $scope.validateOneAgent = false;
    $scope.principalsCount = 0;
    $scope.isShowContinue = true;
    $scope.isShowFeeList = false;
    $scope.uploadFilesCount = 0;
    $scope.CountriesList;
    $scope.StatesList;
    $scope.feeListLayout = PartialViews.FilingFeeListView;
    $scope.feeDetailsDescription = "Requalification Fee Details";
    function canShowFeeList() {
        if (!angular.isDefined($scope.modal.FeeList))
            return false;
        else if (angular.isNullorEmpty($scope.modal.FeeList))
            return false;
        return $scope.modal.FeeList.length > 0;
    }
    // scope load 
    $scope.Init = function () {
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.requalificationModal = $rootScope.modal;
            //$rootScope.modal = null;
        }

        $scope.modal.isBusinessNameAvailable = false;
        $scope.modal.IsAmendmentEntityNameChange = true;


        $scope.messages = messages;
        var lookupCountriesParams = { params: { name: 'JurisdictionCountry' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupCountriesParams, function (response) {
            $scope.CountriesList = response.data;
            $timeout(function () {
                $("#id-JurisdictionCountry").val($scope.modal.JurisdictionCountry);
                //$("#id-JurisdictionState").val($scope.modal.JurisdictionState);
            }, 1000);

        }, function (response) {
        });

        var lookupStatesParams = { params: { name: 'ForeignJurisdictionStates' } };
        // GetLookUpData method is available in constants.js
        wacorpService.get(webservices.OnlineFilingsLookup.GetLookUpData, lookupStatesParams, function (response) {
            $scope.StatesList = response.data;
            $timeout(function () {
                var state = $scope.modal.JurisdictionState;
                $("#id-JurisdictionState").val(state == 0 ? $scope.modal.JurisdictionState = state.toString().replace(0, "") : (state == null ? $scope.modal.JurisdictionState = "" : $scope.modal.JurisdictionState));
            }, 1000);
        }, function (response) {
        });
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
        });
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            $scope.NaicsCodesNonProfit = response.data;
        });

        $scope.unitedstates = "UNITED STATES";
        $scope.CountryChangeDesc(); // CountryChangeDesc method is available in this controller only.
        // get business details
        var data = null;
        if ($rootScope.transactionID > 0)
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 1062, addCurrentARFee: $rootScope.addCurrentARFee } };
        else
            data = { params: { businessID: $routeParams.id, transactionID: $rootScope.transactionID, filingTypeID: 1062, addCurrentARFee: $rootScope.addCurrentARFee } };
        if ($rootScope.requalificationModal == null || $rootScope.requalificationModal == undefined) {
            // GetRequalificationBusinessCriteria method is available in constants.js
            wacorpService.get(webservices.OnlineFiling.GetRequalificationBusinessCriteria, data, function (response) {
                $scope.modal = response.data;
                if (!angular.isNullorEmpty($scope.modal.BusinessName)) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
                    $scope.modal.EffectiveDateType = $scope.modal.EffectiveDateType || "DateOfFiling";
                    calcDuration(); // calcDuration method is available in this controller only
                    $scope.modal.DateOfFormationInHomeJurisdiction = $scope.modal.DateOfFormationInHomeJurisdiction == "0001-01-01T00:00:00" ? "" : wacorpService.dateFormatService($scope.modal.DateOfFormationInHomeJurisdiction);
                    //$scope.modal.DBABusinessName = !angular.isNullorEmpty(response.data.NewDBABusinessName) ? response.data.NewDBABusinessName : response.data.DBABusinessName;
                    $scope.modal.PrincipalOffice = $scope.modal.PrincipalOffice;

                    //$scope.modal.BusinessName = !angular.isNullorEmpty(response.data.NewBusinessName) ? response.data.NewBusinessName : response.data.BusinessName;
                    $scope.modal.NewBusinessName = !angular.isNullorEmpty(response.data.NewBusinessName) ? response.data.NewBusinessName : response.data.BusinessName;
                    $scope.modal.NewBusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
                    $scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;

                    $scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;
                    $scope.modal.NewDBABusinessName = !angular.isNullorEmpty($scope.modal.NewDBABusinessName) ? $scope.modal.NewDBABusinessName : $scope.modal.DBABusinessName;
                    $scope.modal.DBABusinessName = !angular.isNullorEmpty($scope.modal.NewDBABusinessName) ? $scope.modal.NewDBABusinessName : $scope.modal.DBABusinessName;

                    $scope.modal.NameReservedId = ($scope.modal.NameReservedId == 0 ? null : $scope.modal.NameReservedId);
                    $scope.modal.IsLLLPElection = $scope.modal.IsLLLPElection ? $scope.modal.IsLLLPElection : false;
                    $scope.modal.AuthorizedPerson.PersonType = $scope.modal.AuthorizedPerson.PersonType || "I";

                    $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
                    $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
                    $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0 || $scope.modal.JurisdictionCountry == "") ? usaCode : $scope.modal.JurisdictionCountry.toString();
                    $scope.modal.JurisdictionState = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0) ? null : $scope.modal.JurisdictionState.toString();
                    $scope.modal.JurisdictionDescReview = angular.isNullorEmpty($scope.modal.JurisdictionDescReview) ? "WASHINGTON" : $scope.modal.JurisdictionDescReview;

                    $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertStringToObject($scope.modal.NatureOfBusiness.NAICSCode);
                    $scope.modal.NatureOfBusiness.IsOtherNAICS = !angular.isNullorEmpty($scope.modal.NatureOfBusiness.OtherDescription) ? true : false;// Is Other NAICS check box in Nature Of Business Condition
                    $scope.modal.NatureOfBusiness.BusinessID = $scope.modal.BusinessID;

                    $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;

                    if ($scope.modal.Indicator.OldNote == null || $scope.modal.Indicator.OldNote == undefined || $scope.modal.Indicator.OldNote == "")
                        $scope.modal.Indicator.OldNote = $scope.modal.Indicator.Note;
                    if ($rootScope.IsRequalification && $scope.modal.Indicator.OldIndicators != null) {
                        $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.split(',');
                    }
                    else if ($scope.modal.Indicator.OldIndicators == null || $scope.modal.Indicator.OldIndicators == undefined || $scope.modal.Indicator.OldIndicators == "")
                        $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.Indicators;

                    $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                    $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;
                    $scope.modal.IsAmendmentEntityNameChange = true;
                    $scope.isShowReturnAddress = true;
                    if ($scope.modal.IsLLLPElection) {
                        isLLLPElectionReview();
                    }

                    if ($scope.modal.IsActiveFilingExist) {
                        //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                        wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                        });
                    }
                    $scope.modal.EmailAddress = $scope.modal.CorrespondenceAddress.CorrespondenceEmailAddress;
                }
            }, function (response) { $scope.isShowContinue = false; });
        }
        else {

            $scope.modal = $rootScope.requalificationModal;
            if ($scope.modal.Indicator.OldIndicators != null) {
                if (!$.isArray($scope.modal.Indicator.OldIndicators))
                    $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.split(',');
                else {
                }
            }
            //$scope.modal.NewBusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
            //$scope.modal.BusinessName = !angular.isNullorEmpty($scope.modal.NewBusinessName) ? $scope.modal.NewBusinessName : $scope.modal.BusinessName;
            $scope.modal.OldBusinessName = !angular.isNullorEmpty($scope.modal.OldBusinessName) ? $scope.modal.OldBusinessName : $scope.modal.BusinessName;
            //$scope.modal.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.OldDBABusinessName) ? $scope.modal.OldDBABusinessName : $scope.modal.DBABusinessName;

            $scope.modal.JurisdictionDesc = angular.isNullorEmpty($scope.modal.JurisdictionDesc) ? "WASHINGTON" : $scope.modal.JurisdictionDesc;
            $scope.modal.Jurisdiction = ($scope.modal.Jurisdiction == null || $scope.modal.Jurisdiction == "0") ? "" : $scope.modal.Jurisdiction.toString();
            //$scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0 || $scope.modal.JurisdictionState == "") ? usaCode : $scope.modal.JurisdictionCountry.toString();
            $scope.modal.JurisdictionState = ($scope.modal.JurisdictionState == null || $scope.modal.JurisdictionState == 0) ? null : $scope.modal.JurisdictionState.toString();
            $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry);
            $scope.modal.IsAmendmentEntityNameChange = true;


            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
            }
            if ($scope.modal.EffectiveDateType == 'DateOfFiling')
                $scope.modal.EffectiveDate = "";

            $scope.modal.EffectiveDate = wacorpService.dateFormatService($scope.modal.EffectiveDate);
            $scope.isShowReturnAddress = true;

            // OSOS ID--3192
            $scope.modal.JurisdictionCountry = ($scope.modal.JurisdictionCountry == null || $scope.modal.JurisdictionCountry == 0) ? "" : $scope.modal.JurisdictionCountry.toString();
        }

    };

    // back to annual report business serarch
    $scope.back = function () {
        $location.path('/ReinstatementIndex');
    };

    // validate & continue annual report for review
    $scope.ContinueSave = function (reinstatementForm) {
        $scope.showEntityErrorMessage = true;
        $scope.validateErrorMessage = true;
        var indicatorFlag = false;

        if (["Terminated"].indexOf($scope.modal.BusinessStatus) < 0) {
            // Folder Name: app Folder
            // Alert Name: administrativeDissolvedMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.Requalification.administrativeDissolvedMsg);
            return;
        }

        //The use of below block of code is to validate the address component whether the user had given valid data or Empty data.
        //If the user had given empty data then it will throw the error for the respective component.
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        wacorpService.nullCheckAddressCompnent($scope.modal, $scope[reinstatementForm]);

        //if (!$scope.modal.IsEligibleFilingType) {
        //    wacorpService.alertDialog($scope.messages.Requalification.InvalidFilingTypeMsg);
        //    return;
        //}

        $scope.validateErrors = true;

        var indicatorFlag = false;

        if ($scope.modal.IsDBASectionExist && $scope.modal.DBABusinessName && $scope.modal.invalidDBAIndicator) {
            $scope.modal.IsDBAInUse = true;
        }

        if (!$scope.modal.IsDBAInUse && ($scope.modal.DBABusinessName == null || $scope.modal.DBABusinessName == ''))
            indicatorFlag = wacorpService.isIndicatorValid($scope.modal) ? true : false;

        //Entity Name
        var businessNameCount = $scope.availableBusinessCount(); // availableBusinessCount method is available in this controller only

        var isBusinessNameExists = ($scope.modal.isBusinessNameAvailable === true || ($scope.modal.isBusinessNameAvailable !== false && !$scope.modal.isBusinessNameAvailable ? true : $scope.modal.isBusinessNameAvailable))
         || $scope.modal.IsNameReserved;
        //var isBusinessNameExists = (!$scope.modal.IsNameReserved ? (($scope.modal.isBusinessNameAvailable == null || $scope.modal.isBusinessNameAvailable == undefined) ? true : $scope.modal.isBusinessNameAvailable) : true);

        var businessNameValid = isBusinessNameExists ? isBusinessNameExists : (businessNameCount > 0);

        var indicator = wacorpService.isIndicatorValid($scope.modal);

        var isEntityValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EntityName, $scope.modal, $scope.modal.BusinessTypeID) ||
                             ($scope[reinstatementForm].NewEntityName.$valid
                             && (($scope.modal.IsDBAInUse && $scope.modal.DBABusinessName != null && $scope.modal.DBABusinessName != '') ? (businessNameValid || $scope.modal.IsDBAInUse) : businessNameValid)
                             && ((!$scope.modal.IsNameReserved
                            //&& $scope.modal.isBusinessNameAvailable == ""
                             && indicator)
                            || ($scope.modal.IsNameReserved && $scope.modal.BusinessName != "")))
                              );

        var isDBAValid = !$scope.modal.IsDBAInUse ||
                           (
                           (!$scope.ScreenPart($scope.modal.AllScreenParts.DbaName, $scope.modal, $scope.modal.BusinessTypeID)
                          || ($scope[reinstatementForm].DBAName.$valid) && $scope.modal.isDBANameAvailable && $scope.modal.IsDBAInUse) || $scope.modal.IsNameReserved);

        if ($scope.modal.IsDBAInUse && ($scope.modal.DBABusinessName != null || $scope.modal.DBABusinessName != '' || $scope.modal.DBABusinessName != undefined)) {
            $rootScope.$broadcast("checkDBAIndicator");//DBA Name Indicator

        }
        else if (!indicatorFlag) {
            $rootScope.$broadcast("checkIndicator");//Entity Name Indicator
        }

        // registered agent
        $scope.validateAgentErrors = $scope.modal.Agent.IsNewAgent ? true : ($scope.modal.Agent.IsAgentEdit ? true : false);
        $scope.validateOneAgent = $scope.modal.Agent.AgentID == 0 && !$scope.modal.Agent.IsNewAgent;
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // registered agent
        var isRegisteredAgentValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.RegisteredAgent, $scope.modal, $scope.modal.BusinessTypeID) ||
                   ((!$scope.modal.Agent.IsNewAgent ? ($scope.modal.Agent.AgentID != 0 && $scope.modal.Agent.StreetAddress.FullAddress) ? true : (false && !$scope.modal.Agent.IsNoncommercialStreetAddress) : true) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 : true) && (!$scope.modal.Agent.IsNonCommercial ? $scope.modal.Agent.StreetAddress.StreetAddress1 != "" : true) && $scope[reinstatementForm].RegisteredAgentForm.$valid));

        var isRegisteredAgentValidStates = !$scope.modal.Agent.StreetAddress.IsInvalidState && !$scope.modal.Agent.MailingAddress.IsInvalidState && !$scope.modal.Agent.StreetAddress.invalidPoBoxAddress;

        $scope.validateStreetAddress = !$scope.modal.Agent.IsNonCommercial && !isRegisteredAgentValid ? true : false;

        $scope.checkRAStreetAddress = wacorpService.isRAStreetAddressValid($scope.modal.Agent.StreetAddress); //to check RA street address is valid or not 

        $scope.validateNonCommercialStreetAddress = !isRegisteredAgentValid && !$scope.modal.Agent.IsNoncommercialStreetAddress && !$scope.checkRAStreetAddress ? true : false;

        var isJurisdictionFormValid = $scope[reinstatementForm].JurisdictionForm.$valid;

        var dateOfFormationInHomeJurisdiction = $scope[reinstatementForm].DOFHomeJurisdiction.$valid;

        // Nature of business
        $scope.validateNatureOfBusiness = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusiness, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusiness.IsOtherNAICS ? $scope.modal.NatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.NatureOfBusiness.IsOtherNAICS && !$scope.modal.NatureOfBusiness.OtherDescription ? false : true)));

        $scope.NatureOfBusinessNonProfit = (!$scope.ScreenPart($scope.modal.AllScreenParts.NatureOfBusinessNonprofit, $scope.modal, $scope.modal.BusinessTypeID) ||
            (!$scope.modal.NatureOfBusiness.IsOtherNAICS ? $scope.modal.NatureOfBusiness.NAICSCode.length > 0 : ($scope.modal.NatureOfBusiness.IsOtherNAICS && !$scope.modal.NatureOfBusiness.OtherDescription ? false : true)));

        // governing persons
        $scope.isGoverningPersonValid = $scope.principalsCount("GOVERNINGPERSON") > 0;

        //(!$scope.ScreenPart($scope.modal.AllScreenParts.GoverningPersons, $scope.modal, $scope.modal.BusinessTypeID) ||


        // principal office in wa
        $scope.isPrincipalOfficeInWAValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
                                          $scope[reinstatementForm].PrincipalOffice.$valid);

        //(!$scope.ScreenPart($scope.modal.AllScreenParts.PrincipalOfficeInWashington, $scope.modal, $scope.modal.BusinessTypeID) ||
        //                                    $scope[reinstatementForm].PrincipalOffice.$valid);



        //Upload Certificate of Existence
        var isArticalUploadValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.UploadCertificateOfExistence, $scope.modal, $scope.modal.BusinessTypeID)
            || $scope.modal.IsArticalsExist && ($scope.modal.CertificateOfFormation != null && $scope.modal.CertificateOfFormation.length > constant.ZERO));


        //Check to hide effective date section for Np and Foreign NP TFS 2345
        //var isEffectiveDateValid = ($scope[reinstatementForm].EffectiveDate.$valid);
        var isEffectiveDateValid = (!$scope.ScreenPart($scope.modal.AllScreenParts.EffectiveDate, $scope.modal, $scope.modal.BusinessTypeID)
	        || $scope[reinstatementForm].EffectiveDate.$valid);

        //Upload Additional Documents
        var isAdditionalUploadValid = $scope.modal.IsAdditionalDocumentsExist ? ($scope.modal.IsAdditionalDocumentsExist && $scope.modal.UploadDocumentsList != null && $scope.modal.UploadDocumentsList.length > constant.ZERO) : true;
        var isCorrespondenceAddressValid = $scope[reinstatementForm].CorrespondenceAddress.$valid;

        var isOtherFormsValid = (isFormValid($scope[reinstatementForm].AuthorizedPersonForm));



        if (isRegisteredAgentValid
            && $scope.validateNatureOfBusiness
            && $scope.NatureOfBusinessNonProfit
            && $scope.isGoverningPersonValid
            && $scope.isPrincipalOfficeInWAValid
            && isOtherFormsValid && isEntityValid && isJurisdictionFormValid && dateOfFormationInHomeJurisdiction
            && isEffectiveDateValid && isAdditionalUploadValid && isCorrespondenceAddressValid && isDBAValid && isArticalUploadValid && !$scope.modal.invalidDBAIndicator && isRegisteredAgentValidStates) {
            if ($rootScope.addCurrentARFee == 'Y') {
                $scope.modal.ExpirationDateReview = new Date($scope.modal.BusinessTransaction.LastARFiledDate);
                $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
            }
            else {
                $scope.modal.ExpirationDateReview = new Date($scope.modal.NextARDueDate);
                $scope.modal.ExpirationDateReview.setFullYear($scope.modal.ExpirationDateReview.getFullYear() + 1);
            }

            $scope.modal.IsReveiwPDFFieldsShow = true;
            $scope.validateErrorMessage = false;
            $scope.isReviewAgent = false;
            $scope.validateErrors = false;
            $scope.validateOneAgent = false;
            $scope.validateAgentErrors = false;
            $scope.validatePrincipalOfficeInWAErrors = false;
            $scope.validateprincipalErrors = false;
            $scope.modal.BusinessFiling.EffectiveDate = $scope.modal.EffectiveDateType == 'DateOfFiling' ? new Date() : $scope.modal.EffectiveDate;
            //Checking for Emailoptin checkbox checked if the RA email is not available -- 1684 GT
            if (($scope.modal.Agent.EmailAddress == "" || $scope.modal.Agent.EmailAddress == null || $scope.modal.Agent.EmailAddress == undefined)) {
	            $scope.modal.IsEmailOptionChecked = false;
            }
            var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.

            if (countryDesc == $scope.unitedstates) {
                var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.JurisdictionState); // selectedJurisdiction method is available in this controller only.
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionState);
                $scope.modal.JurisdictionDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionStateDesc = angular.copy(stateDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
            }
            else {
                $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionCountry);
                $scope.modal.JurisdictionDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
                $scope.modal.JurisdictionStateDesc = null;
            }
            $scope.modal.IsAmendmentEntityNameChange = true;

            $rootScope.requalificationModal = $scope.modal;
            $rootScope.modal = $scope.modal;
            $scope.isShowFeeList = canShowFeeList();
            if (!$scope.isShowFeeList)
                $location.path("/RequalificationReview");
        }
        else {
            //if (isBusinessNameExists && !isEntityValid && !$scope.modal.IsDBAInUse) {
            //    setTimeout(function () {
            //        $("#txtBusiessName").trigger("blur");
            //    }, 500);
            //    //return false;
            //}
            // Folder Name: app Folder
            // Alert Name: InvalidFilingMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.InvalidFilingMsg);
        }
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };


    $scope.searchBusinessNames = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                businessName: $scope.modal.BusinessName
            }
        };
        // GetBusinessNames method is available in constants.js
        wacorpService.get(webservices.Common.GetBusinessNames, config, function (response) {
            $scope.businessNames = response.data;
            $scope.searchlookupText = "Lookup";
        }, function (response) { $scope.searchlookupText = "Lookup"; });
    };

    $scope.GetReservedBusiness = function () {
        $scope.searchlookupText = "Processing ..."
        var config = {
            params: {
                registrationID: parseInt($scope.NameReservedID)
            }
        };
        // GetReservedBusiness method is available in constants.js
        wacorpService.get(webservices.Common.GetReservedBusiness, config, function (response) {
            if (response.data.BusinessName != null)
                $scope.modal.BusinessName = response.data.BusinessName;
            else
                // Folder Name: app Folder
                // Alert Name: noReserverBusiness method is available in alertMessages.js
                wacorpService.alertDialog($scope.messages.BusinessFormation.noReserverBusiness);
        }, function (response) { });
    };

    $scope.isemptyCheckShowCommentsandNote = function () {
        return $scope.showComments && angular.isNullorEmpty($scope.model.Note);
    };


    // bind Naics codes to multi select dropdpwn
    function getNaicsCodes() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            $scope.NaicsCodes = response.data;
            //$scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
        });
    }

    // bind Naics codes to multi select dropdpwn for Non Profit
    function getNaicsCodesNonProfit() {
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            $scope.NaicsCodesNonProfit = response.data;
            //$scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
        });
    }


    //  check whether form is valid / not
    function isFormValid(form) {
        if (form == undefined) return true;
        return form.$valid
    }

    // validate principals count
    //$scope.principalsCount = function (baseType) {
    //    var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
    //        return (principal.Status != principalStatus.DELETE);
    //    });
    //    return principalsList.length;
    //};


    $scope.principalsCount = function (baseType) {
        var principalsList = $scope.modal.PrincipalsList.filter(function (principal) {
            return (principal.PrincipalBaseType.toUpperCase() == baseType.toUpperCase() && principal.Status != principalStatus.DELETE);
        });
        return principalsList.length;
    };

    // multi dropdown settings
    $scope.dropdownsettings = {
        scrollableHeight: '130px',
        key: "Value",
        value: "Key",
        scrollable: true,
        isKeyList: false,
        selectall: false
    };
    // check business count availability
    $scope.availableBusinessCount = function () {

        if ($scope.modal.businessNames == undefined || $scope.modal.businessNames == null) {
            return 0;
        }
        else {

            var availableBusinesscount = 0;

            for (var index in $scope.modal.businessNames) {
                if ($scope.modal.businessNames[index].AvailableStatus == "Available") {
                    availableBusinesscount++;
                    break;
                }
            }
            return availableBusinesscount;
        }
    };
    $scope.clearOtherDescription = function () {
        $scope.modal.NatureOfBusiness.OtherDescription = null;
    }

    //to trim empty spaces for NOB Other
    $scope.validateOtherNOB = function () {

        $scope.modal.NatureOfBusiness.OtherDescription = $scope.modal.NatureOfBusiness.OtherDescription ? angular.copy($scope.modal.NatureOfBusiness.OtherDescription.trim()) : (($scope.modal.NatureOfBusiness.OtherDescription == undefined || $scope.modal.NatureOfBusiness.OtherDescription == "") ? $scope.modal.NatureOfBusiness.OtherDescription = null : $scope.modal.NatureOfBusiness.OtherDescription);
    }


    $scope.natureOfBussinesVal = function () {
        return ($scope.modal.NatureOfBusiness.NAICSCode.length <= 0 && ($scope.modal.NatureOfBusiness.OtherDescription == null ? true : $scope.modal.NatureOfBusiness.OtherDescription.length <= 0))
    }

    $scope.CountryChangeDesc = function () {
        $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only.

    };

    $scope.selectedJurisdiction = function (items, selectedVal) {
        var result = "";
        angular.forEach(items, function (item) {
            if (selectedVal == item.Key) {
                result = item.Value;
            }
        });
        return result;
    }
    //duration calculation
    function calcDuration() {
        $scope.modal.DurationYears = $scope.modal.DurationYears == 0 ? null : $scope.modal.DurationYears;

        $scope.modal.DurationExpireDate = wacorpService.dateFormatService($scope.modal.DurationExpireDate);

        if ($scope.modal.DurationYears > 0) {
            $scope.modal.DurationType = "rdoDureationYears";
        }
        else if ($scope.modal.DurationExpireDate != null) {
            $scope.modal.DurationType = "rdoDureationDate";
        }
        else {
            $scope.DurationType = "rdoPerpetual";
        }

        //To set duration expire date 
        if ($scope.modal.DurationType == 'rdoDureationDate') {
            $scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? wacorpService.dateFormatService(new Date()) : wacorpService.dateFormatService($scope.modal.DurationExpireDate);
            //$scope.modal.DurationExpireDate = $scope.modal.DurationExpireDate == "0001-01-01T00:00:00" ? null : $scope.modal.DurationExpireDate;
        } else {
            $scope.modal.DurationExpireDate = null;
        }

        $scope.modal.DurationType = ($scope.modal.DurationYears == null && ($scope.modal.DurationExpireDate == null || $scope.modal.DurationExpireDate == "")) && $scope.modal.IsPerpetual ? 'rdoPerpetual' : ($scope.modal.DurationYears > 0 ? 'rdoDureationYears' : ($scope.modal.DurationExpireDate != null ? 'rdoDureationDate' : 'rdoPerpetual'));
        if ($scope.modal.DurationType == 'rdoPerpetual') {
            $scope.modal.IsPerpetual = true;
        }
    }

    // check duration mode
    $scope.IsPerpetual = function (obj) {
        if (obj == 'rdoDureationDate') {
            $scope.modal.IsPerpetual = false;
            //$scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
        else if (obj == 'rdoDureationYears') {
            $scope.modal.IsPerpetual = false;
            $scope.modal.DurationExpireDate = null;
        }
        else {
            $scope.modal.IsPerpetual = true;
            $scope.modal.DurationExpireDate = null;
            $scope.modal.DurationYears = null;
        }
    }

    // validate principals count
    $scope.uploadFilesCount = function (baseType, uploadList) {
        var uploadFilesList = uploadList.filter(function (uploadinfo) {
            return (uploadinfo.DocumentType == baseType);
        });
        return uploadFilesList.length;
    };

    $scope.CountryChangeDesc = function () {
        $scope.modal.JurisdictionCountryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only
        if ($scope.modal.JurisdictionCountryDesc.toUpperCase() == 'UNITED STATES') {
            $scope.modal.JurisdictionState = '';
        };
    }
    //Save into Draft
    $scope.SaveAsDraft = function (iscloseDraft) {
        $scope.isShowReturnAddress = true;
        if ($scope.modal.JurisdictionCountry == 261) {
            var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only
            var stateDesc = $scope.selectedJurisdiction($scope.StatesList, $scope.modal.JurisdictionState); // selectedJurisdiction method is available in this controller only
            $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionState);
            $scope.modal.JurisdictionDesc = angular.copy(stateDesc);
            $scope.modal.JurisdictionStateDesc = angular.copy(stateDesc);
            $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
        }
        else {
            var countryDesc = $scope.selectedJurisdiction($scope.CountriesList, $scope.modal.JurisdictionCountry); // selectedJurisdiction method is available in this controller only
            $scope.modal.Jurisdiction = angular.copy($scope.modal.JurisdictionCountry);
            $scope.modal.JurisdictionDesc = angular.copy(countryDesc);
            $scope.modal.JurisdictionCountryDesc = angular.copy(countryDesc);
            $scope.modal.JurisdictionStateDesc = null;
            $scope.modal.JurisdictionState = null;
        }

        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.UBINumber = $scope.modal.UBINumber != null && $scope.modal.UBINumber != '' ? $scope.modal.UBINumber.replace(/-/g, '') : $scope.modal.UBINumber;
        $scope.modal.OnlineNavigationUrl = '/Requalification';
        $scope.modal.CartStatus = 'Incomplete';
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $scope.modal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $scope.modal.IsAmendmentEntityNameChange = true;

        $scope.modelDraft = {};
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        angular.copy($scope.modal, $scope.modelDraft);
        var index = 0;
        angular.forEach($scope.modelDraft.AllScreenParts, function (value, key) {
            $scope.modelDraft['AllScreenParts[' + index + '].Key'] = key;
            $scope.modelDraft['AllScreenParts[' + index + '].Value'] = value;
            index++;
        });

        index = 0;
        angular.forEach($scope.modelDraft.EntityTypesWithScreens, function (value, key) {
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Key'] = key;
            $scope.modelDraft['EntityTypesWithScreens[' + index + '].Value'] = value;
            index++;
        });

        if ($scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined && $scope.modal.Indicator.OldIndicators.length > 0) {
            $scope.modelDraft.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.join();
        }

        wacorpService.post(webservices.OnlineFiling.requalificationSaveAsDraft, $scope.modelDraft, function (response) {
            if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
                $scope.modal.NatureOfBusiness.NAICSCode = angular.isNullorEmpty($scope.modal.NatureOfBusiness.NAICSCode) ? [] : $scope.modal.NatureOfBusiness.NAICSCode;
            }

            $scope.modal.OnlineCartDraftID = response.data.ID;
            $rootScope.BusinessType = null;
            if (iscloseDraft) {
                $location.path('/Dashboard');
            }
            else {
                // Folder Name: app Folder
                // Alert Name: SaveDraftSuccess method is available in alertMessages.js 
                wacorpService.alertDialog($scope.messages.SaveDraftSuccess);
            }
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    }

    var newNote = helptext.Corporations.LLLP;
    $scope.IsLLLPElection = function (obj) {
        if (obj) {
            var _addIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _addindicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            //var _addIndicatorArray = $scope.modal.Indicator.Indicators;
            var _addIndicatorArray = [];

            if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _addIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _addIndicatorArray;
            }
            else
                _addIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _addIndicatorsCSV.indexOf("LLLP");
            if (indexCSV <= 0) {
                //_addIndicatorsCSV = _addIndicatorsCSV + ",LLLP";
                _addIndicatorsCSV = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsCSV = _addIndicatorsCSV;

            var indexDsisplay = _addindicatorsDisplay.indexOf("LLLP");
            if (indexDsisplay <= 0) {
                //_addindicatorsDisplay = _addindicatorsDisplay + ", LLLP";
                _addindicatorsDisplay = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsDisplay = _addindicatorsDisplay

            var index = _addIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                // _addIndicatorArray.push("LLLP");
                _addIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    var indicators = _addindicatorsDisplay.split(',');
                    angular.forEach(indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.Indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = newNote;
            $scope.modal.Indicator.Indicators = _addIndicatorArray;
        }
        else {
            var _removeIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _removeIndicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            //var _removeIndicatorArray = $scope.modal.Indicator.Indicators;
            var _removeIndicatorArray = [];

            if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _removeIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _removeIndicatorArray;
            }
            else
                _removeIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _removeIndicatorsCSV.indexOf("LLLP");
            if (indexCSV >= 0) {
                //_removeIndicatorsCSV = _removeIndicatorsCSV.replace(',LLLP', '');
                _removeIndicatorsCSV = _removeIndicatorsCSV.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsCSV = _removeIndicatorsCSV;

            var indexDisplay = _removeIndicatorsDisplay.indexOf("LLLP");
            if (indexDisplay >= 0) {
                //_removeIndicatorsDisplay = _removeIndicatorsDisplay.replace(', LLLP', '');
                _removeIndicatorsDisplay = _removeIndicatorsDisplay.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsDisplay = _removeIndicatorsDisplay;

            var index = _removeIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_removeIndicatorArray.splice(index, 1);
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            else if (index > 1) {
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = $scope.modal.Indicator.OldNote;
            $scope.modal.Indicator.Indicators = $scope.modal.Indicator.OldIndicators;
        }
        $("#txtBusiessName").trigger("blur");
    }

    //isLLLPElectionReview
    function isLLLPElectionReview() {
        if ($scope.modal.IsLLLPElection) {
            var _addIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _addindicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            //var _addIndicatorArray = $scope.modal.Indicator.Indicators;
            var _addIndicatorArray = [];

            if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _addIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _addIndicatorArray;
            }
            else
                _addIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _addIndicatorsCSV.indexOf("LLLP");
            if (indexCSV <= 0) {
                //_addIndicatorsCSV = _addIndicatorsCSV + ",LLLP";
                _addIndicatorsCSV = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsCSV = _addIndicatorsCSV;

            var indexDsisplay = _addindicatorsDisplay.indexOf("LLLP");
            if (indexDsisplay <= 0) {
                //_addindicatorsDisplay = _addindicatorsDisplay + ", LLLP";
                _addindicatorsDisplay = "LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.";
            }
            $scope.modal.Indicator.IndicatorsDisplay = _addindicatorsDisplay

            var index = _addIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_addIndicatorArray.push("LLLP");
                _addIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    var indicators = _addindicatorsDisplay.split(',');
                    angular.forEach(indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.Indicators, function (data, Key) {
                        _addIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = newNote;
            $scope.modal.Indicator.Indicators = _addIndicatorArray;
        }
        else {
            var _removeIndicatorsCSV = $scope.modal.Indicator.IndicatorsCSV;
            var _removeIndicatorsDisplay = $scope.modal.Indicator.IndicatorsDisplay;
            //var _removeIndicatorArray = $scope.modal.Indicator.Indicators;
            var _removeIndicatorArray = [];

            if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                var list = $scope.modal.Indicator.IndicatorsCSV.split(',');
                angular.forEach(list, function (data, Key) {
                    _removeIndicatorArray.push(data);
                });
                $scope.modal.Indicator.Indicators = _removeIndicatorArray;
            }
            else
                _removeIndicatorArray = $scope.modal.Indicator.Indicators;

            var indexCSV = _removeIndicatorsCSV.indexOf("LLLP");
            if (indexCSV >= 0) {
                //_removeIndicatorsCSV = _removeIndicatorsCSV.replace(',LLLP', '');
                _removeIndicatorsCSV = _removeIndicatorsCSV.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsCSV = _removeIndicatorsCSV;

            var indexDisplay = _removeIndicatorsDisplay.indexOf("LLLP");
            if (indexDisplay >= 0) {
                //_removeIndicatorsDisplay = _removeIndicatorsDisplay.replace(', LLLP', '');
                _removeIndicatorsDisplay = _removeIndicatorsDisplay.replace('LIMITED LIABILITY LIMITED PARTNERSHIP,LLLP,L.L.L.P.', $scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined ? $scope.modal.Indicator.OldIndicators : $scope.modal.Indicator.Indicators);
            }
            $scope.modal.Indicator.IndicatorsDisplay = _removeIndicatorsDisplay;

            var index = _removeIndicatorArray.indexOf("LLLP");
            if (index <= 0) {
                //_removeIndicatorArray.splice(index, 1);
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            else if (index > 1) {
                var indicators = "";
                _removeIndicatorArray = [];
                if ($scope.modal.BusinessType == "FOREIGN LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
                else if ($scope.modal.BusinessType == "FOREIGN LIMITED LIABILITY LIMITED PARTNERSHIP") {
                    angular.forEach($scope.modal.Indicator.OldIndicators, function (data, Key) {
                        _removeIndicatorArray.push(data);
                    });
                }
            }
            $scope.modal.Indicator.Note = $scope.modal.Indicator.OldNote;
            $scope.modal.Indicator.Indicators = _removeIndicatorArray;
        }
    };

});

wacorpApp.controller('reinstatementIndexController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, ScopesData, focus) {
    // declare scope variables
    $scope.page = 0;
    $scope.pagesCount = 0;
    $scope.totalCount = 0;
    $scope.businessSearchCriteria = { Type: "businessname", ID: "", IsSearch: true, PageID: 1, PageCount: 10, BusinessTypeId: 0, IsOnline: true, SearchType: "InitialReport", isSearchClick: false };
    $scope.selectedBusiness = null;
    $scope.search = loadbusinessList;
    $scope.isEntityOrUBIRequired = $scope.isEntityOrUBIRequired || messages.EntityNameRequired;
    focus('searchField');

    // search business list
    $scope.submit = function (searchform) {
        $scope.isShowErrorFlag = true;
        $scope.isEntityOrUBIRequired = $scope.businessSearchCriteria.Type == 'businessname' ? messages.EntityNameRequired : messages.UBINumberRequired;
        if ($scope[searchform].$valid) {
            $scope.businessSearchCriteria.isSearchClick = true;
            $scope.isShowErrorFlag = false;
            loadbusinessList($scope.page); // loadbusinessList method is available in this controller.
        }
    };
    // clear fields
    $scope.clearFun = function () {
        $scope.businessSearchCriteria.ID = "";
        $scope.businessSearchCriteria.isSearchClick = false;
        focus('searchField');
    };

    // get selected business information
    $scope.getSelectedBusiness = function (business) {
        $scope.selectedBusiness = business;
    }

    // navigate to annual report
    $scope.getNavigation = function () {
        if ([ResultStatus.AdministrativelyDissolved].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            //if (["Active", "Delinquent"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0) {
            $rootScope.BusinessID = $scope.selectedBusiness.BusinessID;
            $rootScope.reinstatementModal = null;
            $rootScope.transactionID = null;
            $location.path('/Reinstatement/' + $scope.selectedBusiness.BusinessID);

        }
        else {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog('Selected business is ' + $scope.selectedBusiness.BusinessStatus);
        }
    };
    // get business list data from server
    function loadbusinessList(page) {
        page = page || 0;
        $scope.businessSearchCriteria.PageID = page == 0 ? 1 : page + 1;
        $scope.selectedBusiness = null;
        var data = $scope.businessSearchCriteria
        // getBusinessNames method is available in constants.js
        wacorpService.post(webservices.BusinessSearch.getBusinessNames, data, function (response) {
            $scope.BusinessList = response.data;
            if ($scope.totalCount == 0) {
                var totalcount = response.data[0].Criteria.TotalRowCount;
                $scope.pagesCount = Math.round(totalcount / response.data.length);
                $scope.totalCount = totalcount;
            }
            $scope.page = page;
            $scope.BusinessListProgressBar = false;
            focus('tblBusinessSearch');
        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }

    $scope.$watch('BusinessList', function () {
        if ($scope.BusinessList == undefined)
            return;
        if ($scope.BusinessList.length == 0) {
            $scope.totalCount = 0;
            $scope.pagesCount = 0;
            $scope.totalCount = 0;
            $scope.page = 0;
        }
    }, true);
});



wacorpApp.controller('requalificationReviewController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, ScopesData, focus) {
    $scope.NaicsCodes = [];
    $scope.NaicsCodesNonProfit = [];
    //scope load
    $scope.Init = function () {
        if (!angular.isNullorEmpty($rootScope.requalificationModal)) {
            $scope.modal = $rootScope.requalificationModal;
            getNaicsCodes(); // getNaicsCodes method is available in this controller only.
            getNaicsCodesNonProfit(); // getNaicsCodesNonProfit method is available in this controller only.
        }
        else
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            $scope.navRequalification();
    }

    // add requalification filing to cart 
    $scope.AddToCart = function () {
        
        $scope.modal.NewBusinessName = $scope.modal.BusinessName;
        $scope.modal.BusinessName = $scope.modal.OldBusinessName;
        $scope.modal.OldBusinessName = $scope.modal.OldBusinessName;

        $scope.modal.NewDBABusinessName = $scope.modal.DBABusinessName;
        $scope.modal.DBABusinessName = $scope.modal.OldDBABusinessName;
        $scope.modal.OldDBABusinessName = $scope.modal.OldDBABusinessName;

        if ($scope.modal.Indicator.OldIndicators != null && $scope.modal.Indicator.OldIndicators != undefined && $scope.modal.Indicator.OldIndicators.length > 0) {

            $scope.modal.Indicator.OldIndicators = $scope.modal.Indicator.OldIndicators.join();
        }

        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.CartStatus = 'Incomplete-Shopping Cart';

        //TFS 2751 hiding NP Checkboxes in PDF
        if (typeof (document.getElementById("divNPCheckboxes")) !== 'undefined') {
            $("#divNPCheckboxes").hide();
        };
        //TFS 2751

        // get review HTML
        var $reviewHTML = $("section.content-body");
        $reviewHTML.find("[data-ng-hide='isReview'],input:checkbox, button, input:button, .btn, .remove").remove();
        $scope.modal.ReviewHTML = $reviewHTML.html().replace(" REVIEW", " ").replace(" Review", " ");

        $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusiness.NAICSCode);
        
        //TFS 1143 submitting filing means you have said agent consents
        if (!(typeof $scope.modal.Agent === typeof undefined)) {//TFS 1410
            $scope.modal.Agent.IsRegisteredAgentConsent =
                true;
        }
        if (!(typeof $scope.modal.IsRegisteredAgentConsent === typeof undefined)) {//TFS 1410
            $scope.modal.IsRegisteredAgentConsent = true; 
        }
        //TFS 1143

        // AddRequalificationToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AddRequalificationToCart, $scope.modal, function (response) {
            $rootScope.requalificationModal = null;
            $rootScope.modal = null;
            $rootScope.transactionID = null;
            $location.path('/shoppingCart');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };

    // back to annual report flow
    $scope.back = function () {
        $rootScope.requalificationModal = $scope.modal;
        if ($scope.modal.NatureOfBusiness.NAICSCode != null && $scope.modal.NatureOfBusiness.NAICSCode.length > 0) {
            $rootScope.requalificationModal.NatureOfBusiness.NAICSCode = $scope.modal.NatureOfBusiness.NAICSCode.join(",");
        }
        $location.path('/Requalification/' + $scope.modal.BusinessID);
    };

    // show/hide the screen parts based on entity types
    $scope.ScreenPart = function (screenPart, modal, businessTypeID) {
        if (angular.isNullorEmpty(screenPart))
            return false;
        return !angular.isUndefined(modal) && ($.inArray(parseInt(businessTypeID), modal.EntityTypesWithScreens[screenPart]) > -1) ? true : false;
    };

    // get selected Naics Codes
    function getNaicsCodes() {
        var naicDesc = "";
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodes(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodes.push(response.data[i]);
                        naicDesc += (naicDesc == "" ? response.data[i].Value : (", " + response.data[i].Value));
                        break;
                    }
                }
            });
            $scope.modal.NatureOfBusiness.NAICSCodeDesc = naicDesc;
        });
    }
    // get selected Naics Codes for non profit
    function getNaicsCodesNonProfit() {
        var naicDesc = "";
        // Service Folder: services
        // File Name: lookupService.js (you can search with file name in solution explorer)
        lookupService.NaicsCodesNonProfit(function (response) {
            var principalsList = $scope.modal.NatureOfBusiness.NAICSCode.filter(function (naicscode) {
                for (var i = 0; i < response.data.length; i++) {
                    if (naicscode == response.data[i].Key) {
                        $scope.NaicsCodesNonProfit.push(response.data[i]);
                        naicDesc += (naicDesc == "" ? response.data[i].Value : (", " + response.data[i].Value));
                        break;
                    }
                }
            });
            $scope.modal.NatureOfBusiness.NAICSCodeDesc = naicDesc;
        });
    }

    // add annual filing to cart 
    $scope.AddMoreItems = function () {
        $scope.modal.createdBy = $rootScope.repository.loggedUser.userid;
        $scope.modal.NatureOfBusiness.NAICSCode = $scope.convertObjectToString($scope.modal.NatureOfBusiness.NAICSCode);
        // AddReinstatementToCart method is available in constants.js
        wacorpService.post(webservices.OnlineFiling.AddReinstatementToCart, $scope.modal, function (response) {
            $rootScope.requalificationModal = null;
            $rootScope.transactionID = null;
            //if ($scope.modal.BusinessTransaction.TransactionId > 0)
            $location.path('/Dashboard');

        }, function (response) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
        });
    };
});

wacorpApp.controller('CommercialRegisteredAgentsController', function ($scope, $routeParams, $location, $rootScope, lookupService, wacorpService, focus) {

    $scope.agent = {};
    $scope.agentList = [];

    $scope.page = constant.ZERO;
    $scope.pagesCount = constant.ZERO;
    $scope.totalCount = constant.ZERO;
    $scope.AgentCriteria = { PageID: constant.ONE, PageCount: constant.TWENTYFIVE, SortBy: null, SortType: null };
    $scope.search = loadbusinessList;
    var totalcount = 0;
    $scope.initagentslist = function () {

        loadbusinessList(constant.ZERO); // loadbusinessList method is available in this controller only.


    };

    function GetList(page) {
        // getCommercialAgentsList method is available in constants.js
        wacorpService.get(webservices.CommercialAgents.getCommercialAgentsList, "", function (response) {
            if (response != null) {
                $scope.agentList = response.data;
            }
        }, function (response) {
            // Folder Name: app Folder
            // Alert Name: serverError method is available in alertMessages.js 
            wacorpService.alertDialog($scope.messages.serverError);
        });
    };



    // get Agent list data from server


    function loadbusinessList(page, sortBy) {

        page = page || constant.ZERO;
        $scope.AgentCriteria.PageID = page == constant.ZERO ? constant.ONE : page + constant.ONE;
        if (sortBy != undefined) {
            if ($scope.AgentCriteria.SortBy == sortBy) {
                if ($scope.AgentCriteria.SortType == 'ASC') {
                    $scope.AgentCriteria.SortType = 'DESC';
                }
                else {
                    $scope.AgentCriteria.SortType = 'ASC';
                }
            }
            else {
                $scope.AgentCriteria.SortBy = sortBy;
                $scope.AgentCriteria.SortType = 'ASC';
            }
        }
        //  $scope.selectedBusiness = null;
        var data = angular.copy($scope.AgentCriteria);
        $scope.isButtonSerach = page == 0;
        // getCommercialAgentsList method is available in constants.js
        wacorpService.post(webservices.CommercialAgents.getCommercialAgentsList, data, function (response) {
            $scope.agentList = response.data;
            if (response.data.length > 0) {
                if (totalcount == 0) {
                    totalcount = response.data[constant.ZERO].Criteria.TotalRowCount;
                }
                var pagecount = totalcount / response.data.length > Math.round(totalcount / response.data.length)
                            ? Math.round(totalcount / response.data.length) + 1 : Math.round(totalcount / response.data.length);
                $scope.pagesCount = response.data.length < $scope.AgentCriteria.PageCount && page > 0 ? $scope.pagesCount : pagecount;
                $scope.totalCount = totalcount;

            }
            $scope.page = page;

        }, function (response) {
            //  $scope.selectedBusiness = null;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });

    }

    $scope.$watch('BusinessList', function () {

        if ($scope.agentList == undefined)
            return;
        if ($scope.agentList.length == constant.ZERO) {

            $scope.totalCount = constant.ZERO;
            $scope.pagesCount = constant.ZERO;
            $scope.totalCount = constant.ZERO;
            $scope.page = constant.ZERO;
        }
    }, true);



    // back to home page
    $scope.back = function () {
        $location.path('/home');
    };


    // export to csv


    $scope.exportCSVServer = function () {

        var pageName = "candidate";
        // $scope.fetchResults();
        $scope.AgentCriteria.PageCount = 9999999;
        $scope.AgentCriteria.PageID = 1;

        var data = angular.copy($scope.AgentCriteria);
        // getCommercialAgentsList method is available in constants.js
        wacorpService.post(webservices.CommercialAgents.getCommercialAgentsList, data, function (response) {
            $scope.agentList = response.data;
            var result = [];
            result = response.data;
            $rootScope.exportToCSV(result, pageName)

        }, function (response) {
            //  $scope.selectedBusiness = null;
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(response.data);
            // Folder Name: controller
            // Controller Name: rootController.js (you can search with file name in solution explorer)
            searchResultsLoading(false);
        });
    }










    //Export Data to CSV
    $rootScope.exportToCSV = function (exportData, pageName) {


        var arrData = typeof exportData != 'object' ? JSON.parse(exportData) : exportData;

        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
        });

        var CSV = '';
        //Set Report title in first row or line

        //CSV += ReportTitle + '\r\n\n';

        ////This condition will generate the Label/Header
        //if (ShowLabel) {
        var row = "";

        var rowData = "";
        //Preapring Candidate Data



        if (pageName == "candidate") {

            var arrData1 = [];
            //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
            //candidateColumns = ["Name", "UBI", "Contact", "Email"];
            candidateColumns = ["Name", "Contact", "Email"];
            //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
            $.each(arrData, function (index, element) {

                arrData1.push({
                    "Name": (element.FirstName == "" || element.LastName == "") ? 
                        element.EntityName : 
                            element.FirstName + ' ' + element.LastName
                            //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
                            //,"UBI": element.UBI
                            //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
                            , "Contact" : 
                            element.AgentStreet1 + ' ' + element.AgentStreet2 + ' ' + element.City + ' ' + element.State + ' ' + element.Zip4 + ' ' + element.Zip5,
                    "Email": element.EmailAddress,

                })
            });
            $.each(arrData1, function (index, Data) {

                rowData = "";
                $.each(Data, function (headerName, Data) {
                    if (candidateColumns.indexOf(headerName) != -1) {
                        if (index == 0) {
                            if (headerName == "Name") {
                                headerName = "Name";
                            }
                            //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
                            //else if (headerName == "UBI") {
                            //    headerName = "UBI";
                            //}
                            //TFS 1067 Remove UBI field from Commercial Registered Agent - Entity Type - PCC TFS 3036
                            else if (headerName == "Contact") {
                                headerName = "Contact";
                            }
                            else if (headerName == "Email") {
                                headerName = "Email";
                            }

                            row += headerName + ',';
                        }
                        if (typeof Data === 'string') {
                            if (Data) {
                                if (Data.indexOf(',') != -1) {
                                    Data = '"' + Data + '"';
                                }
                            }
                            //Data = Data.replace(/,/g, " ")
                        }

                        else {
                            if (!Data) {
                                Data = '';
                            }
                            else {
                                Data = Data;
                            }

                        }
                        if (headerName == 'Email' || headerName == 'Email') {
                            rowData = rowData + Data;
                        }
                        else {
                            rowData += Data + ",";
                        }


                    }

                });

                if (index == 0) {
                    row = row.slice(0, -1);

                    //append Label row with line break
                    CSV += row + '\r\n';
                }
                rowData.slice(0, rowData.length - 1);

                //add a line break after each row
                CSV += rowData + '\r\n';
            });
        }
        row = ""; csv = ""; rowData = "";







        //Generate a file name
        var fileName = "CommercialAgentsList";


        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        if (navigator.msSaveBlob) {
            var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
            navigator.msSaveBlob(blob, "fileName.csv")

        } else {
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        //}
    }







    //// export to xls


    //$scope.exportXLSServer = function () {
    //    var pageName = "candidate";
    //    // $scope.fetchResults();
    //    $scope.AgentCriteria.PageCount = 9999999;
    //    $scope.AgentCriteria.PageID = 1;

    //    var data = angular.copy($scope.AgentCriteria);
    //    wacorpService.post(webservices.CommercialAgents.getCommercialAgentsList, data, function (response) {
    //        $scope.agentList = response.data;
    //        var result = [];
    //        result = response.data;
    //        $rootScope.exportToXLS(result, pageName)

    //    }, function (response) {
    //        //  $scope.selectedBusiness = null;
    //        wacorpService.alertDialog(response.data);
    //        searchResultsLoading(false);
    //    });
    //}


    ////Export Data to xls
    //$rootScope.exportToXLS = function (exportData, pageName) {


    //    var arrData = typeof exportData != 'object' ? JSON.parse(exportData) : exportData;

    //    var formatter = new Intl.NumberFormat('en-US', {
    //        style: 'currency',
    //        currency: 'USD',
    //        minimumFractionDigits: 2,
    //    });

    //    var CSV = '';
    //    //Set Report title in first row or line

    //    //CSV += ReportTitle + '\r\n\n';

    //    ////This condition will generate the Label/Header
    //    //if (ShowLabel) {
    //    var row = "";

    //    var rowData = "";
    //    //Preapring Candidate Data



    //    if (pageName == "candidate") {

    //        var arrData1 = [];
    //        candidateColumns = ["Name", "UBI", "Contact"];
    //        $.each(arrData, function (index, element) {
    //            arrData1.push({
    //                "Name": (element.FirstName == "" || element.LastName == "") ? element.EntityName : element.FirstName + ' ' + element.LastName, "UBI": element.UBI, "Contact": element.AgentStreet1 + ' ' + element.AgentStreet2 + ' ' + element.City + ' ' + element.State + ' ' + element.Zip4 + ' ' + element.Zip5,


    //            })
    //        });
    //        $.each(arrData1, function (index, Data) {
    //            rowData = "";
    //            $.each(Data, function (headerName, Data) {
    //                if (candidateColumns.indexOf(headerName) != -1) {
    //                    if (index == 0) {
    //                        if (headerName == "Name") {
    //                            headerName = "Name";
    //                        }
    //                        else if (headerName == "UBI") {
    //                            headerName = "UBI";
    //                        }
    //                        else if (headerName == "Contact") {
    //                            headerName = "Contact";
    //                        }

    //                        row += headerName + ',';
    //                    }
    //                    if (typeof Data === 'string') {
    //                        if (Data) {
    //                            if (Data.indexOf(',') != -1) {
    //                                Data = '"' + Data + '"';
    //                            }
    //                        }
    //                        //Data = Data.replace(/,/g, " ")
    //                    }

    //                    else {
    //                        if (!Data) {
    //                            Data = '';
    //                        }
    //                        else {
    //                            Data = Data;
    //                        }

    //                    }
    //                    if (headerName == 'Contact' || headerName == 'Contact') {
    //                        rowData = rowData + Data;
    //                    }
    //                    else {
    //                        rowData += Data + ",";
    //                    }


    //                }

    //            });
    //            if (index == 0) {
    //                row = row.slice(0, -1);

    //                //append Label row with line break
    //                CSV += row + '\r\n';
    //            }
    //            rowData.slice(0, rowData.length - 1);

    //            //add a line break after each row
    //            CSV += rowData + '\r\n';
    //        });
    //    }
    //    row = ""; csv = ""; rowData = "";







    //    //Generate a file name
    //    var fileName = "CommercialAgentsList";


    //    //Initialize file format you want csv or xls
    //    var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

    //    // Now the little tricky part.
    //    // you can use either>> window.open(uri);
    //    // but this will not work in some browsers
    //    // or you will not get the correct file extension    

    //    //this trick will generate a temp <a /> tag
    //    if (navigator.msSaveBlob) {
    //        var blob = new Blob([CSV], { type: "text/csv;charset=utf-8;" });
    //        navigator.msSaveBlob(blob, "fileName.csv")

    //    } else {
    //        var link = document.createElement("a");
    //        link.href = uri;

    //        //set the visibility hidden so it will not effect on your web-layout
    //        link.style = "visibility:hidden";
    //        link.download = fileName + ".xls";

    //        //this part will append the anchor tag and remove it after automatic click
    //        document.body.appendChild(link);
    //        link.click();
    //        document.body.removeChild(link);
    //    }
    //    //}
    //}









});
wacorpApp.controller('expressPDFCertificateController', function ($scope, $q, $timeout, $routeParams, $location, $rootScope, $cookieStore, lookupService, wacorpService, ScopesData, $filter) {

    $scope.selectedBusiness = null;
    $scope.submitBusiness = getNavigation;
    $scope.modalEntity = { CertifiedCopies: [], BusinessTransaction: {}, BusinessInfo: {}, UserId: 0, TotalAmount: 0, FilingTypeId: 0 };
    $scope.modal = { CertifiedCopies: [], BusinessTransaction: {}, BusinessInfo: {}, UserId: 0, TotalAmount: 0, FilingTypeId: 0 };
    $scope.businessSearchCriteria = { Type: "businessname", ID: "", IsSearch: true, PageID: 1, PageCount: 10, BusinessTypeId: 0, IsOnline: true, SearchType: "", isSearchClick: false };
    $scope.filingAmount = WAFeeProvider.AGENTREGISTRATIONFEE;
    $scope.surChargeAmt = 0;
    $scope.totalNoOfPages = 0;
    $scope.surChargeAmt_1 = 0;
    $scope.totalIterationsCount = 0;
    $scope.transactionDocumentsList = [];
    $scope.SearchType = "searchExpressPDFCoE";
    /* --------Business Search Functionality------------- */
    function getNavigation() {
        if (["FOREIGN BANK CORPORATION", "FOREIGN BANK LIMITED LIABILITY COMPANY", "WA BANK CORPORATION", "WA BANK LIMITED LIABILITY COMPANY"].indexOf($scope.selectedBusiness.BusinessType) == -1) {
            if (["Active"].indexOf($scope.selectedBusiness.BusinessStatus) >= 0 && $scope.selectedBusiness.UBINumber != "") {
                $location.path('/ExpressPDFCertificate/' + $scope.selectedBusiness.BusinessID);
            }
            else {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog('The entity selected is not in good standing with the Office of the Secretary of State. For other certificates please contact the records desk at recordsdesk@sos.wa.gov');
            }
        }
        else
        {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog('The entity selected is not in good standing with the Office of the Secretary of State. For other certificates please contact the records desk at recordsdesk@sos.wa.gov');
        }
    }

    $scope.initExpressPDF = function () {
        $scope.navExpressPDFCertificate();
    };

    /* --------Certified Copies------------- */
    $scope.initCopyRequest = function () {
        $scope.loadBusinessFilings(); // loadBusinessFilings method is available in this controller only.
    };

    $scope.editCartFilings = function () {
        var data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 0 } };
        // getExpressPDFBusinessCriteria method is available in constants.js
        wacorpService.get(webservices.OnlineFiling.getExpressPDFBusinessCriteria, data, function (response) {
            $scope.selectedModal = response.data;
            $scope.loadBusinessFilings(response.data.BusinessID); // loadBusinessFilings method is available in this controller only.
        }, function (response) { });
    };

    $scope.loadBusinessFilings = function () {
        var data = null;
        if ($rootScope.modal != null || $rootScope.modal != undefined) {
            $rootScope.modal = $rootScope.modal;
           // $scope.modal = $rootScope.modal;
        }
        if ($rootScope.transactionID > 0)
            // here filingTypeID: 110 is RECORDS/CERTIFICATE REQUEST
            data = { params: { businessID: null, transactionID: $rootScope.transactionID, filingTypeID: 5 } };
        else
            data = { params: { businessID: $routeParams.id, transactionID: null, filingTypeID: 5, cftType: $rootScope.cftType } };

        $scope.modal.CFTType = $rootScope.cftType;
        // getExpressPDFBusinessCriteria method is available in constants.js
        wacorpService.get(webservices.OnlineFiling.getExpressPDFBusinessCriteria, data, function (response) {
            if (response.data != null) {
                $rootScope.cftType = null;
                $scope.modal = response.data;
                $rootScope.modal = response.data;
                if ($rootScope.modal != null || $rootScope.modal != undefined) {
                    $scope.modal.OnlineCartDraftID = $rootScope.modal.OnlineCartDraftID;
                    $scope.modal.CorrespondenceAddress = $rootScope.modal.CorrespondenceAddress;
                }

                $scope.modal.CorrespondenceAddress.State = $scope.modal.CorrespondenceAddress.State == null || $scope.modal.CorrespondenceAddress.State == "" ? codes.WA : $scope.modal.CorrespondenceAddress.State;
                $scope.modal.CorrespondenceAddress.Country = $scope.modal.CorrespondenceAddress.Country == null || $scope.modal.CorrespondenceAddress.Country == "" ? codes.USA : $scope.modal.CorrespondenceAddress.Country;

                //$scope.addFilingToList($scope.modal);
                // here BusinessTypeID = 5 is CERTIFIED COPIES
                $scope.modal.BusinessInfo.BusinessTypeID = 5;
                $scope.modal.BusinessTransaction.TransactionId = $rootScope.transactionID;
                $scope.modal.BusinessTransaction.OrganizationType = $scope.modal.CFTType;
                if ($rootScope.transactionID > 0) {
                    $scope.setSelectedFilings(response.data.CertifiedCopies); // setSelectedFilings method is available in this controller only.
                }
                else if ($rootScope.modal.CertifiedCopies.length != 0) {
                    if ($rootScope.modal != null || $rootScope.modal != undefined) {
                        $scope.modal = $rootScope.modal;
                    }
                    $scope.setSelectedFilings($rootScope.modal.CertifiedCopies); // setSelectedFilings method is available in this controller only.
                }
                if ($scope.modal.BusinessInfo.IsActiveFilingExist) {
                    //wacorpService.alertDialog($scope.messages.HasActiveFilings);
                    // Folder Name: app Folder
                    // Alert Name: HasActiveFilings method is available in alertMessages.js 
                    wacorpService.confirmOkCancel($scope.messages.HasActiveFilings, function () {
                    });
                }
                
                $scope.modal.BusinessInfo.OldDBABusinessName = !angular.isNullorEmpty($scope.modal.BusinessInfo.OldDBABusinessName) ? $scope.modal.BusinessInfo.OldDBABusinessName : $scope.modal.BusinessInfo.DBABusinessName;
            }
        }, function (businessFilingResponse) {
            // Service Folder: services
            // File Name: wacorpService.js (you can search with file name in solution explorer)
            wacorpService.alertDialog(businessFilingResponse.data);
        });
    };
    $scope.addFilingToList = function (modal) {
        var newBusinessFiling = angular.copy(modal.BusinessFiling);
    }

    $scope.setSelectedFilings = function (items) {
        if ($scope.modal.CFTType != undefined && $scope.modal.CFTType != "") {
            $scope.modal.BusinessInfo.BusinessID = $scope.modal.CharitiesEntityInfo.CFTId
        }
        else {
            $scope.modal.BusinessInfo.BusinessID = $scope.modal.BusinessInfo.BusinessID;
        }
        var businessfilingconfig = { params: { businessId: $scope.modal.BusinessInfo.BusinessID, cftType: $scope.modal.CFTType } };
        // getExpressPDFAllCertifiedCopies method is available in constants.js
        wacorpService.get(webservices.CopyRequest.getExpressPDFAllCertifiedCopies, businessfilingconfig,
            function (response) {
                $scope.modal.CertifiedCopies = response.data;
                $scope.addFilingToList($scope.modal);
                for (var i = 0; i < items.length; i++) {
                    for (var j = 0; j < $scope.modal.CertifiedCopies.length; j++) {
                        if (items[i].FilingNumber == $scope.modal.CertifiedCopies[j].FilingNumber && items[i].FilingTypeName == $scope.modal.CertifiedCopies[j].FilingTypeName) {
                            $scope.modal.CertifiedCopies[j].CopyRequest = items[i].CopyRequest;
                            $scope.modal.CertifiedCopies[j].ApostilleCopies = items[i].ApostilleCopies;
                            $scope.GetFilingFee(items[i].FilingNumber);
                            break;
                        }
                    }
                }
            },
        function (response) {

        });
    }

    $scope.Continue = function () {
        $scope.selectedModal = angular.copy($scope.modal);
        var selectedFilings = [];
        angular.forEach($scope.modal.CertifiedCopies, function (item) {
            selectedFilings.push(item);
        });

        if (selectedFilings.length > 0) {
            $scope.selectedModal.CertifiedCopies = selectedFilings;
            $scope.selectedModal.BusinessTransaction.CopyRequestEntityList = selectedFilings;// Assign to businesstransaction to CopyRequestEntityList
            $scope.isReview = true;
        }
        else {
            $scope.isReview = false;
        }
    };

    // add certificates to cart
    $scope.addToCart = function () {
        $scope.selectedModal = angular.copy($scope.modal);
        var selectedFilings = [];
        angular.forEach($scope.modal.CertifiedCopies, function (item) {
            selectedFilings.push(item);
        });

        if (selectedFilings.length > 0) {
            $scope.selectedModal.CertifiedCopies = selectedFilings;
            $scope.selectedModal.BusinessTransaction.CopyRequestEntityList = selectedFilings;// Assign to businesstransaction to CopyRequestEntityList
            $scope.isReview = true;
        }
        else {
            $scope.isReview = false;
        }

        $scope.selectedModal.UserId = $rootScope.repository.loggedUser.userid;
        if ($scope.selectedModal.CertifiedCopies.length > 0) {
            // addToCartForExpressPDF method is available in constants.js
            wacorpService.post(webservices.OnlineFiling.addToCartForExpressPDF, $scope.selectedModal, function (response) {
                $rootScope.transactionID = null;
                if (response.data.ID > 0)
                    $location.path('/shoppingcart');
                else
                    $location.path('/Dashboard');
            }, function (response) {
                // Service Folder: services
                // File Name: wacorpService.js (you can search with file name in solution explorer)
                wacorpService.alertDialog(response.data);
            });
        }
        else
            // Folder Name: app Folder
            // Alert Name: emptyCartMsg method is available in alertMessages.js
            wacorpService.alertDialog($scope.messages.CopyRequest.emptyCartMsg);
    };

    //navigate to business information
    $scope.showBusineInfo = function (id, businessType) {
        $rootScope.isBackButtonHide = false;
        $scope.businesssearchcriteria.businessid = id;
        $scope.businesssearchcriteria.businesstype = businessType;
        $cookieStore.put('businesssearchcriteria', $scope.businesssearchcriteria);
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        $scope.navBusinessInformation();
    }

    //navigate to home
    $scope.gotoHome = function () {
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        $scope.navHome();
    };

    $scope.back = function () {
        // Folder Name: controller
        // Controller Name: rootController.js (you can search with file name in solution explorer)
        $scope.navExpressPDFCertificate();
    }

    //Get Filing Fee
    $scope.GetFilingFee = function (id) {
        angular.forEach($scope.modal.CertifiedCopies, function (item) {
            if (item.FilingNumber === id && item.Amount == 0) {
                var filingTypedata = { params: { businessID: item.BusinessID, BusinessTypeName: item.RCBusinessTypeName, businessTypeID: item.RCFBusinessTypeId, filingTypeID: item.RCFilingTypeId, filingType: item.RCFilingTypeName } };
                // calculateAnnualFeeOnline method is available in constants.js
                wacorpService.get(webservices.CopyRequest.calculateAnnualFeeOnline, filingTypedata, function (response) {
                    var fillingFee = $.grep(response.data, function (v) {
                        return v.Description === "FillingFee";
                    });

                    item.TotalAmount = fillingFee[0].FilingFee + fillingFee[0].FilingFee;// certified copies added
                    $scope.modal.TotalAmount = item.TotalAmount;
                }, function (response) {
                    // Service Folder: services
                    // File Name: wacorpService.js (you can search with file name in solution explorer)
                    wacorpService.alertDialog(response.data);
                });
            }
        });
    }

});
/*! ng-dialog - v0.5.9 (https://github.com/likeastore/ngDialog) */
!function(a,b){"undefined"!=typeof module&&module.exports?(b("undefined"==typeof angular?require("angular"):angular),module.exports="ngDialog"):"function"==typeof define&&define.amd?define(["angular"],b):b(a.angular)}(this,function(a){"use strict";var b=a.module("ngDialog",[]),c=a.element,d=a.isDefined,e=(document.body||document.documentElement).style,f=d(e.animation)||d(e.WebkitAnimation)||d(e.MozAnimation)||d(e.MsAnimation)||d(e.OAnimation),g="animationend webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend",h="a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]",i="ngdialog-disabled-animation",j={html:!1,body:!1},k={},l=[],m=!1,n=!1;return b.provider("ngDialog",function(){var b=this.defaults={className:"ngdialog-theme-default",appendClassName:"",disableAnimation:!1,plain:!1,showClose:!0,closeByDocument:!0,closeByEscape:!0,closeByNavigation:!1,appendTo:!1,preCloseCallback:!1,overlay:!0,cache:!0,trapFocus:!0,preserveFocus:!0,ariaAuto:!0,ariaRole:null,ariaLabelledById:null,ariaLabelledBySelector:null,ariaDescribedById:null,ariaDescribedBySelector:null,bodyClassName:"ngdialog-open",width:null};this.setForceHtmlReload=function(a){j.html=a||!1},this.setForceBodyReload=function(a){j.body=a||!1},this.setDefaults=function(c){a.extend(b,c)},this.setOpenOnePerName=function(a){n=a||!1};var d,e=0,o=0,p={};this.$get=["$document","$templateCache","$compile","$q","$http","$rootScope","$timeout","$window","$controller","$injector",function(q,r,s,t,u,v,w,x,y,z){var A=[],B={onDocumentKeydown:function(a){27===a.keyCode&&C.close("$escape")},activate:function(a){var b=a.data("$ngDialogOptions");b.trapFocus&&(a.on("keydown",B.onTrapFocusKeydown),A.body.on("keydown",B.onTrapFocusKeydown))},deactivate:function(a){a.off("keydown",B.onTrapFocusKeydown),A.body.off("keydown",B.onTrapFocusKeydown)},deactivateAll:function(b){a.forEach(b,function(b){var c=a.element(b);B.deactivate(c)})},setBodyPadding:function(a){var b=parseInt(A.body.css("padding-right")||0,10);A.body.css("padding-right",b+a+"px"),A.body.data("ng-dialog-original-padding",b),v.$broadcast("ngDialog.setPadding",a)},resetBodyPadding:function(){var a=A.body.data("ng-dialog-original-padding");a?A.body.css("padding-right",a+"px"):A.body.css("padding-right",""),v.$broadcast("ngDialog.setPadding",0)},performCloseDialog:function(a,b){var c=a.data("$ngDialogOptions"),e=a.attr("id"),h=k[e];if(h){if("undefined"!=typeof x.Hammer){var i=h.hammerTime;i.off("tap",d),i.destroy&&i.destroy(),delete h.hammerTime}else a.unbind("click");1===o&&A.body.unbind("keydown",B.onDocumentKeydown),a.hasClass("ngdialog-closing")||(o-=1);var j=a.data("$ngDialogPreviousFocus");j&&j.focus&&j.focus(),v.$broadcast("ngDialog.closing",a,b),o=0>o?0:o,f&&!c.disableAnimation?(h.$destroy(),a.unbind(g).bind(g,function(){B.closeDialogElement(a,b)}).addClass("ngdialog-closing")):(h.$destroy(),B.closeDialogElement(a,b)),p[e]&&(p[e].resolve({id:e,value:b,$dialog:a,remainingDialogs:o}),delete p[e]),k[e]&&delete k[e],l.splice(l.indexOf(e),1),l.length||(A.body.unbind("keydown",B.onDocumentKeydown),m=!1)}},closeDialogElement:function(a,b){var c=a.data("$ngDialogOptions");a.remove(),0===o&&(A.html.removeClass(c.bodyClassName),A.body.removeClass(c.bodyClassName),B.resetBodyPadding()),v.$broadcast("ngDialog.closed",a,b)},closeDialog:function(b,c){var d=b.data("$ngDialogPreCloseCallback");if(d&&a.isFunction(d)){var e=d.call(b,c);a.isObject(e)?e.closePromise?e.closePromise.then(function(){B.performCloseDialog(b,c)}):e.then(function(){B.performCloseDialog(b,c)},function(){}):e!==!1&&B.performCloseDialog(b,c)}else B.performCloseDialog(b,c)},onTrapFocusKeydown:function(b){var c,d=a.element(b.currentTarget);if(d.hasClass("ngdialog"))c=d;else if(c=B.getActiveDialog(),null===c)return;var e=9===b.keyCode,f=b.shiftKey===!0;e&&B.handleTab(c,b,f)},handleTab:function(a,b,c){var d=B.getFocusableElements(a);if(0===d.length)return void(document.activeElement&&document.activeElement.blur());var e=document.activeElement,f=Array.prototype.indexOf.call(d,e),g=-1===f,h=0===f,i=f===d.length-1,j=!1;c?(g||h)&&(d[d.length-1].focus(),j=!0):(g||i)&&(d[0].focus(),j=!0),j&&(b.preventDefault(),b.stopPropagation())},autoFocus:function(a){var b=a[0],d=b.querySelector("*[autofocus]");if(null===d||(d.focus(),document.activeElement!==d)){var e=B.getFocusableElements(a);if(e.length>0)return void e[0].focus();var f=B.filterVisibleElements(b.querySelectorAll("h1,h2,h3,h4,h5,h6,p,span"));if(f.length>0){var g=f[0];c(g).attr("tabindex","-1").css("outline","0"),g.focus()}}},getFocusableElements:function(a){var b=a[0],c=b.querySelectorAll(h),d=B.filterTabbableElements(c);return B.filterVisibleElements(d)},filterTabbableElements:function(a){for(var b=[],d=0;d<a.length;d++){var e=a[d];"-1"!==c(e).attr("tabindex")&&b.push(e)}return b},filterVisibleElements:function(a){for(var b=[],c=0;c<a.length;c++){var d=a[c];(d.offsetWidth>0||d.offsetHeight>0)&&b.push(d)}return b},getActiveDialog:function(){var a=document.querySelectorAll(".ngdialog");return 0===a.length?null:c(a[a.length-1])},applyAriaAttributes:function(a,b){if(b.ariaAuto){if(!b.ariaRole){var c=B.getFocusableElements(a).length>0?"dialog":"alertdialog";b.ariaRole=c}b.ariaLabelledBySelector||(b.ariaLabelledBySelector="h1,h2,h3,h4,h5,h6"),b.ariaDescribedBySelector||(b.ariaDescribedBySelector="article,section,p")}b.ariaRole&&a.attr("role",b.ariaRole),B.applyAriaAttribute(a,"aria-labelledby",b.ariaLabelledById,b.ariaLabelledBySelector),B.applyAriaAttribute(a,"aria-describedby",b.ariaDescribedById,b.ariaDescribedBySelector)},applyAriaAttribute:function(a,b,d,e){if(d&&a.attr(b,d),e){var f=a.attr("id"),g=a[0].querySelector(e);if(!g)return;var h=f+"-"+b;return c(g).attr("id",h),a.attr(b,h),h}},detectUIRouter:function(){try{return a.module("ui.router"),!0}catch(b){return!1}},getRouterLocationEventName:function(){return B.detectUIRouter()?"$stateChangeSuccess":"$locationChangeSuccess"}},C={__PRIVATE__:B,open:function(f){function g(a,b){return v.$broadcast("ngDialog.templateLoading",a),u.get(a,b||{}).then(function(b){return v.$broadcast("ngDialog.templateLoaded",a),b.data||""})}function h(b){return b?a.isString(b)&&q.plain?b:"boolean"!=typeof q.cache||q.cache?g(b,{cache:r}):g(b,{cache:!1}):"Empty template"}var j=null;if(f=f||{},!(n&&f.name&&(j=f.name+" dialog",this.isOpen(j)))){var q=a.copy(b),D=++e;j=j||"ngdialog"+D,l.push(j),"undefined"!=typeof q.data&&("undefined"==typeof f.data&&(f.data={}),f.data=a.merge(a.copy(q.data),f.data)),a.extend(q,f);var E;p[j]=E=t.defer();var F;k[j]=F=a.isObject(q.scope)?q.scope.$new():v.$new();var G,H,I=a.extend({},q.resolve);return a.forEach(I,function(b,c){I[c]=a.isString(b)?z.get(b):z.invoke(b,null,null,c)}),t.all({template:h(q.template||q.templateUrl),locals:t.all(I)}).then(function(b){var e=b.template,f=b.locals;q.showClose&&(e+='<div class="ngdialog-close"></div>');var g=q.overlay?"":" ngdialog-no-overlay";if(G=c('<div id="'+j+'" class="ngdialog'+g+'"></div>'),G.html(q.overlay?'<div class="ngdialog-overlay"></div><div class="ngdialog-content" role="document">'+e+"</div>":'<div class="ngdialog-content" role="document">'+e+"</div>"),G.data("$ngDialogOptions",q),F.ngDialogId=j,q.data&&a.isString(q.data)){var h=q.data.replace(/^\s*/,"")[0];F.ngDialogData="{"===h||"["===h?a.fromJson(q.data):new String(q.data),F.ngDialogData.ngDialogId=j}else q.data&&a.isObject(q.data)&&(F.ngDialogData=q.data,F.ngDialogData.ngDialogId=j);if(q.className&&G.addClass(q.className),q.appendClassName&&G.addClass(q.appendClassName),q.width){var k=G[0].querySelector(".ngdialog-content");a.isString(q.width)?k.style.width=q.width:k.style.width=q.width+"px"}if(q.disableAnimation&&G.addClass(i),H=q.appendTo&&a.isString(q.appendTo)?a.element(document.querySelector(q.appendTo)):A.body,B.applyAriaAttributes(G,q),q.preCloseCallback){var l;a.isFunction(q.preCloseCallback)?l=q.preCloseCallback:a.isString(q.preCloseCallback)&&F&&(a.isFunction(F[q.preCloseCallback])?l=F[q.preCloseCallback]:F.$parent&&a.isFunction(F.$parent[q.preCloseCallback])?l=F.$parent[q.preCloseCallback]:v&&a.isFunction(v[q.preCloseCallback])&&(l=v[q.preCloseCallback])),l&&G.data("$ngDialogPreCloseCallback",l)}if(F.closeThisDialog=function(a){B.closeDialog(G,a)},q.controller&&(a.isString(q.controller)||a.isArray(q.controller)||a.isFunction(q.controller))){var n;q.controllerAs&&a.isString(q.controllerAs)&&(n=q.controllerAs);var p=y(q.controller,a.extend(f,{$scope:F,$element:G}),!0,n);q.bindToController&&a.extend(p.instance,{ngDialogId:F.ngDialogId,ngDialogData:F.ngDialogData,closeThisDialog:F.closeThisDialog}),G.data("$ngDialogControllerController",p())}if(w(function(){var a=document.querySelectorAll(".ngdialog");B.deactivateAll(a),s(G)(F);var b=x.innerWidth-A.body.prop("clientWidth");A.html.addClass(q.bodyClassName),A.body.addClass(q.bodyClassName);var c=b-(x.innerWidth-A.body.prop("clientWidth"));c>0&&B.setBodyPadding(c),H.append(G),B.activate(G),q.trapFocus&&B.autoFocus(G),q.name?v.$broadcast("ngDialog.opened",{dialog:G,name:q.name}):v.$broadcast("ngDialog.opened",G)}),m||(A.body.bind("keydown",B.onDocumentKeydown),m=!0),q.closeByNavigation){var r=B.getRouterLocationEventName();v.$on(r,function(){B.closeDialog(G)})}if(q.preserveFocus&&G.data("$ngDialogPreviousFocus",document.activeElement),d=function(a){var b=q.closeByDocument?c(a.target).hasClass("ngdialog-overlay"):!1,d=c(a.target).hasClass("ngdialog-close");(b||d)&&C.close(G.attr("id"),d?"$closeButton":"$document")},"undefined"!=typeof x.Hammer){var t=F.hammerTime=x.Hammer(G[0]);t.on("tap",d)}else G.bind("click",d);return o+=1,C}),{id:j,closePromise:E.promise,close:function(a){B.closeDialog(G,a)}}}},openConfirm:function(d){var e=t.defer(),f=a.copy(b);d=d||{},"undefined"!=typeof f.data&&("undefined"==typeof d.data&&(d.data={}),d.data=a.merge(a.copy(f.data),d.data)),a.extend(f,d),f.scope=a.isObject(f.scope)?f.scope.$new():v.$new(),f.scope.confirm=function(a){e.resolve(a);var b=c(document.getElementById(g.id));B.performCloseDialog(b,a)};var g=C.open(f);return g?(g.closePromise.then(function(a){return a?e.reject(a.value):e.reject()}),e.promise):void 0},isOpen:function(a){var b=c(document.getElementById(a));return b.length>0},close:function(a,b){var d=c(document.getElementById(a));if(d.length)B.closeDialog(d,b);else if("$escape"===a){var e=l[l.length-1];d=c(document.getElementById(e)),d.data("$ngDialogOptions").closeByEscape&&B.closeDialog(d,"$escape")}else C.closeAll(b);return C},closeAll:function(a){for(var b=document.querySelectorAll(".ngdialog"),d=b.length-1;d>=0;d--){var e=b[d];B.closeDialog(c(e),a)}},getOpenDialogs:function(){return l},getDefaults:function(){return b}};return a.forEach(["html","body"],function(a){if(A[a]=q.find(a),j[a]){var b=B.getRouterLocationEventName();v.$on(b,function(){A[a]=q.find(a)})}}),C}]}),b.directive("ngDialog",["ngDialog",function(b){return{restrict:"A",scope:{ngDialogScope:"="},link:function(c,d,e){d.on("click",function(d){d.preventDefault();var f=a.isDefined(c.ngDialogScope)?c.ngDialogScope:"noScope";a.isDefined(e.ngDialogClosePrevious)&&b.close(e.ngDialogClosePrevious);var g=b.getDefaults();b.open({template:e.ngDialog,className:e.ngDialogClass||g.className,appendClassName:e.ngDialogAppendClass,controller:e.ngDialogController,controllerAs:e.ngDialogControllerAs,bindToController:e.ngDialogBindToController,scope:f,data:e.ngDialogData,showClose:"false"===e.ngDialogShowClose?!1:"true"===e.ngDialogShowClose?!0:g.showClose,closeByDocument:"false"===e.ngDialogCloseByDocument?!1:"true"===e.ngDialogCloseByDocument?!0:g.closeByDocument,closeByEscape:"false"===e.ngDialogCloseByEscape?!1:"true"===e.ngDialogCloseByEscape?!0:g.closeByEscape,overlay:"false"===e.ngDialogOverlay?!1:"true"===e.ngDialogOverlay?!0:g.overlay,preCloseCallback:e.ngDialogPreCloseCallback||g.preCloseCallback,bodyClassName:e.ngDialogBodyClass||g.bodyClassName})})}}}]),b});
wacorpApp.factory('httpInterceptor', function ($q, $rootScope, $log) {
    var numLoadings = 0;
    return {
        request: function (config) {
            //var hideUrl = "/Registrant/GetRegistrantData"; // don't show the loading indicator for this request
            //var hide = (config.url.indexOf(hideUrl)); // is this isn't -1, it means we should hide the request from the loading indicator
            //if (hide == -1) {
            //    //numLoadings++;
            //    // Show loader
                
            //}
            $rootScope.$broadcast("loader_show");
            return config || $q.when(config)
        },
        response: function (response) {
            //if ((--numLoadings) === 0) {
                // Hide loader
                $rootScope.$broadcast("loader_hide");
            //}
            return response || $q.when(response);
        },
        responseError: function (response) {
            //if (!(--numLoadings)) {
                // Hide loader
                $rootScope.$broadcast("loader_hide");
            //}
            return $q.reject(response);
        }
    };
})
/* FileSaver.js
 * A saveAs() FileSaver implementation.
 * 1.3.0
 *
 * By Eli Grey, http://eligrey.com
 * License: MIT
 *   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
 */

/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */

/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */

var saveAs = saveAs || (function(view) {
	"use strict";
	// IE <10 is explicitly unsupported
	if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
		return;
	}
	var
		  doc = view.document
		  // only get URL when necessary in case Blob.js hasn't overridden it yet
		, get_URL = function() {
			return view.URL || view.webkitURL || view;
		}
		, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
		, can_use_save_link = "download" in save_link
		, click = function(node) {
			var event = new MouseEvent("click");
			node.dispatchEvent(event);
		}
		, is_safari = /constructor/i.test(view.HTMLElement)
		, throw_outside = function(ex) {
			(view.setImmediate || view.setTimeout)(function() {
				throw ex;
			}, 0);
		}
		, force_saveable_type = "application/octet-stream"
		// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
		, arbitrary_revoke_timeout = 1000 * 40 // in ms
		, revoke = function(file) {
			var revoker = function() {
				if (typeof file === "string") { // file is an object URL
					get_URL().revokeObjectURL(file);
				} else { // file is a File
					file.remove();
				}
			};
			setTimeout(revoker, arbitrary_revoke_timeout);
		}
		, dispatch = function(filesaver, event_types, event) {
			event_types = [].concat(event_types);
			var i = event_types.length;
			while (i--) {
				var listener = filesaver["on" + event_types[i]];
				if (typeof listener === "function") {
					try {
						listener.call(filesaver, event || filesaver);
					} catch (ex) {
						throw_outside(ex);
					}
				}
			}
		}
		, auto_bom = function(blob) {
			// prepend BOM for UTF-8 XML and text/* types (including HTML)
			// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
			if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
				return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
			}
			return blob;
		}
		, FileSaver = function(blob, name, no_auto_bom) {
			if (!no_auto_bom) {
				blob = auto_bom(blob);
			}
			// First try a.download, then web filesystem, then object URLs
			var
				  filesaver = this
				, type = blob.type
				, force = type === force_saveable_type
				, object_url
				, dispatch_all = function() {
					dispatch(filesaver, "writestart progress write writeend".split(" "));
				}
				// on any filesys errors revert to saving with object URLs
				, fs_error = function() {
					if (force && is_safari && view.FileReader) {
						// Safari doesn't allow downloading of blob urls
						var reader = new FileReader();
						reader.onloadend = function() {
							var base64Data = reader.result;
							view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
							filesaver.readyState = filesaver.DONE;
							dispatch_all();
						};
						reader.readAsDataURL(blob);
						filesaver.readyState = filesaver.INIT;
						return;
					}
					// don't create more object URLs than needed
					if (!object_url) {
						object_url = get_URL().createObjectURL(blob);
					}
					if (force) {
						view.location.href = object_url;
					} else {
						var opened = view.open(object_url, "_blank");
						if (!opened) {
							// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
							view.location.href = object_url;
						}
					}
					filesaver.readyState = filesaver.DONE;
					dispatch_all();
					revoke(object_url);
				}
			;
			filesaver.readyState = filesaver.INIT;

			if (can_use_save_link) {
				object_url = get_URL().createObjectURL(blob);
				setTimeout(function() {
					save_link.href = object_url;
					save_link.download = name;
					click(save_link);
					dispatch_all();
					revoke(object_url);
					filesaver.readyState = filesaver.DONE;
				});
				return;
			}

			fs_error();
		}
		, FS_proto = FileSaver.prototype
		, saveAs = function(blob, name, no_auto_bom) {
			return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
		}
	;
	// IE 10+ (native saveAs)
	if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
		return function(blob, name, no_auto_bom) {
			name = name || blob.name || "download";

			if (!no_auto_bom) {
				blob = auto_bom(blob);
			}
			return navigator.msSaveOrOpenBlob(blob, name);
		};
	}

	FS_proto.abort = function(){};
	FS_proto.readyState = FS_proto.INIT = 0;
	FS_proto.WRITING = 1;
	FS_proto.DONE = 2;

	FS_proto.error =
	FS_proto.onwritestart =
	FS_proto.onprogress =
	FS_proto.onwrite =
	FS_proto.onabort =
	FS_proto.onerror =
	FS_proto.onwriteend =
		null;

	return saveAs;
}(
	   typeof self !== "undefined" && self
	|| typeof window !== "undefined" && window
	|| this.content
));
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window

if (typeof module !== "undefined" && module.exports) {
  module.exports.saveAs = saveAs;
} else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
  define([], function() {
    return saveAs;
  });
}

/*** Directives and services for responding to idle users in AngularJS
* @author Mike Grabski <me@mikegrabski.com>
* @version v1.3.2
* @link https://github.com/HackedByChinese/ng-idle.git
* @license MIT
*/

!function(a,b,c){"use strict";b.module("ngIdle",["ngIdle.keepalive","ngIdle.idle","ngIdle.countdown","ngIdle.title","ngIdle.localStorage"]),b.module("ngIdle.keepalive",[]).provider("Keepalive",function(){var a={http:null,interval:600};this.http=function(c){if(!c)throw new Error("Argument must be a string containing a URL, or an object containing the HTTP request configuration.");b.isString(c)&&(c={url:c,method:"GET"}),c.cache=!1,a.http=c};var c=this.interval=function(b){if(b=parseInt(b),isNaN(b)||0>=b)throw new Error("Interval must be expressed in seconds and be greater than 0.");a.interval=b};this.$get=["$rootScope","$log","$interval","$http",function(d,e,f,g){function h(a){d.$broadcast("KeepaliveResponse",a.data,a.status)}function i(){d.$broadcast("Keepalive"),b.isObject(a.http)&&g(a.http).then(h)["catch"](h)}var j={ping:null};return{_options:function(){return a},setInterval:c,start:function(){return f.cancel(j.ping),j.ping=f(i,1e3*a.interval),j.ping},stop:function(){f.cancel(j.ping)},ping:function(){i()}}}]}),b.module("ngIdle.idle",["ngIdle.keepalive","ngIdle.localStorage"]).provider("Idle",function(){var a={idle:1200,timeout:30,autoResume:"idle",interrupt:"mousemove keydown DOMMouseScroll mousewheel mousedown touchstart touchmove scroll",windowInterrupt:null,keepalive:!0},c=this.timeout=function(c){if(c===!1)a.timeout=0;else{if(!(b.isNumber(c)&&c>=0))throw new Error("Timeout must be zero or false to disable the feature, or a positive integer (in seconds) to enable it.");a.timeout=c}};this.interrupt=function(b){a.interrupt=b},this.windowInterrupt=function(b){a.windowInterrupt=b};var d=this.idle=function(b){if(0>=b)throw new Error("Idle must be a value in seconds, greater than 0.");a.idle=b};this.autoResume=function(b){b===!0?a.autoResume="idle":b===!1?a.autoResume="off":a.autoResume=b},this.keepalive=function(b){a.keepalive=b===!0},this.$get=["$interval","$log","$rootScope","$document","Keepalive","IdleLocalStorage","$window",function(e,f,g,h,i,j,k){function l(){a.keepalive&&(u.running&&i.ping(),i.start())}function m(){a.keepalive&&i.stop()}function n(){u.idling=!u.idling;var b=u.idling?"IdleStart":"IdleEnd";u.idling?(g.$broadcast(b),m(),a.timeout&&(u.countdown=a.timeout,o(),u.timeout=e(o,1e3,a.timeout,!1))):(l(),g.$broadcast(b)),e.cancel(u.idle)}function o(){if(u.idling){if(u.countdown<=0)return void q();g.$broadcast("IdleWarn",u.countdown),u.countdown--}}function p(a){g.$broadcast("IdleInterrupt",a)}function q(){m(),e.cancel(u.idle),e.cancel(u.timeout),u.idling=!0,u.running=!1,u.countdown=0,g.$broadcast("IdleTimeout")}function r(a,b,c){var d=a.running();a.unwatch(),b(c),d&&a.watch()}function s(){var a=j.get("expiry");return a&&a.time?new Date(a.time):null}function t(a){a?j.set("expiry",{id:v,time:a}):j.remove("expiry")}var u={idle:null,timeout:null,idling:!1,running:!1,countdown:null},v=(new Date).getTime(),w={_options:function(){return a},_getNow:function(){return new Date},getIdle:function(){return a.idle},getTimeout:function(){return a.timeout},setIdle:function(a){r(this,d,a)},setTimeout:function(a){r(this,c,a)},isExpired:function(){var a=s();return null!==a&&a<=this._getNow()},running:function(){return u.running},idling:function(){return u.idling},watch:function(b){e.cancel(u.idle),e.cancel(u.timeout);var c=a.timeout?a.timeout:0;b||t(new Date((new Date).getTime()+1e3*(a.idle+c))),u.idling?n():u.running||l(),u.running=!0,u.idle=e(n,1e3*a.idle,0,!1)},unwatch:function(){e.cancel(u.idle),e.cancel(u.timeout),u.idling=!1,u.running=!1,t(null),m()},interrupt:function(b){if(u.running){if(a.timeout&&this.isExpired())return void q();p(b),(b||"idle"===a.autoResume||"notIdle"===a.autoResume&&!u.idling)&&this.watch(b)}}},x={clientX:null,clientY:null,swap:function(a){var b={clientX:this.clientX,clientY:this.clientY};return this.clientX=a.clientX,this.clientY=a.clientY,b},hasMoved:function(a){var b=this.swap(a);return null===this.clientX||a.movementX||a.movementY?!0:b.clientX!=a.clientX||b.clientY!=a.clientY?!0:!1}};if(h.find("html").on(a.interrupt,function(a){"mousemove"===a.type&&a.originalEvent&&0===a.originalEvent.movementX&&0===a.originalEvent.movementY||("mousemove"!==a.type||x.hasMoved(a))&&w.interrupt()}),a.windowInterrupt)for(var y=a.windowInterrupt.split(" "),z=function(){w.interrupt()},A=0;A<y.length;A++)k.addEventListener?k.addEventListener(y[A],z,!1):k.attachEvent(y[A],z);var B=function(a){if("ngIdle.expiry"===a.key&&a.newValue&&a.newValue!==a.oldValue){var c=b.fromJson(a.newValue);if(c.id===v)return;w.interrupt(!0)}};return k.addEventListener?k.addEventListener("storage",B,!1):k.attachEvent&&k.attachEvent("onstorage",B),w}]}),b.module("ngIdle.countdown",["ngIdle.idle"]).directive("idleCountdown",["Idle",function(a){return{restrict:"A",scope:{value:"=idleCountdown"},link:function(b){b.value=a.getTimeout(),b.$on("IdleWarn",function(a,c){b.$evalAsync(function(){b.value=c})}),b.$on("IdleTimeout",function(){b.$evalAsync(function(){b.value=0})})}}}]),b.module("ngIdle.title",[]).provider("Title",function(){function a(a,b,c){return new Array(b-String(a).length+1).join(c||"0")+a}var c={enabled:!0},d=this.enabled=function(a){c.enabled=a===!0};this.$get=["$document","$interpolate",function(e,f){var g={original:null,idle:"{{minutes}}:{{seconds}} until your session times out!",timedout:"Your session has expired."};return{setEnabled:d,isEnabled:function(){return c.enabled},original:function(a){return b.isUndefined(a)?g.original:void(g.original=a)},store:function(a){(a||!g.original)&&(g.original=this.value())},value:function(a){return b.isUndefined(a)?e[0].title:void(e[0].title=a)},idleMessage:function(a){return b.isUndefined(a)?g.idle:void(g.idle=a)},timedOutMessage:function(a){return b.isUndefined(a)?g.timedout:void(g.timedout=a)},setAsIdle:function(b){this.store();var c={totalSeconds:b};c.minutes=Math.floor(b/60),c.seconds=a(b-60*c.minutes,2),this.value(f(this.idleMessage())(c))},setAsTimedOut:function(){this.store(),this.value(this.timedOutMessage())},restore:function(){this.original()&&this.value(this.original())}}}]}).directive("title",["Title",function(a){return{restrict:"E",link:function(b,c,d){a.isEnabled()&&!d.idleDisabled&&(a.store(!0),b.$on("IdleStart",function(){a.original(c[0].innerText)}),b.$on("IdleWarn",function(b,c){a.setAsIdle(c)}),b.$on("IdleEnd",function(){a.restore()}),b.$on("IdleTimeout",function(){a.setAsTimedOut()}))}}}]),b.module("ngIdle.localStorage",[]).service("IdleStorageAccessor",["$window",function(a){return{get:function(){return a.localStorage}}}]).service("IdleLocalStorage",["IdleStorageAccessor",function(a){function d(){var a={};this.setItem=function(b,c){a[b]=c},this.getItem=function(b){return"undefined"!=typeof a[b]?a[b]:null},this.removeItem=function(b){a[b]=c}}function e(){try{var b=a.get();return b.setItem("ngIdleStorage",""),b.removeItem("ngIdleStorage"),b}catch(c){return new d}}var f=e();return{set:function(a,c){f.setItem("ngIdle."+a,b.toJson(c))},get:function(a){return b.fromJson(f.getItem("ngIdle."+a))},remove:function(a){f.removeItem("ngIdle."+a)},_wrapped:function(){return f}}}])}(window,window.angular);
//# sourceMappingURL=angular-idle.map
